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        SerializedProjectGroupKey, 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    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1329    active_pane: Entity<Pane>,
 1330    last_active_center_pane: Option<WeakEntity<Pane>>,
 1331    last_active_view_id: Option<proto::ViewId>,
 1332    status_bar: Entity<StatusBar>,
 1333    pub(crate) modal_layer: Entity<ModalLayer>,
 1334    toast_layer: Entity<ToastLayer>,
 1335    titlebar_item: Option<AnyView>,
 1336    notifications: Notifications,
 1337    suppressed_notifications: HashSet<NotificationId>,
 1338    project: Entity<Project>,
 1339    follower_states: HashMap<CollaboratorId, FollowerState>,
 1340    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1341    window_edited: bool,
 1342    last_window_title: Option<String>,
 1343    dirty_items: HashMap<EntityId, Subscription>,
 1344    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1345    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1346    database_id: Option<WorkspaceId>,
 1347    app_state: Arc<AppState>,
 1348    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1349    _subscriptions: Vec<Subscription>,
 1350    _apply_leader_updates: Task<Result<()>>,
 1351    _observe_current_user: Task<Result<()>>,
 1352    _schedule_serialize_workspace: Option<Task<()>>,
 1353    _serialize_workspace_task: Option<Task<()>>,
 1354    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1355    pane_history_timestamp: Arc<AtomicUsize>,
 1356    bounds: Bounds<Pixels>,
 1357    pub centered_layout: bool,
 1358    bounds_save_task_queued: Option<Task<()>>,
 1359    on_prompt_for_new_path: Option<PromptForNewPath>,
 1360    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1361    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1362    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1363    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1364    _items_serializer: Task<Result<()>>,
 1365    session_id: Option<String>,
 1366    scheduled_tasks: Vec<Task<()>>,
 1367    last_open_dock_positions: Vec<DockPosition>,
 1368    removing: bool,
 1369    open_in_dev_container: bool,
 1370    _dev_container_task: Option<Task<Result<()>>>,
 1371    _panels_task: Option<Task<Result<()>>>,
 1372    sidebar_focus_handle: Option<FocusHandle>,
 1373    multi_workspace: Option<WeakEntity<MultiWorkspace>>,
 1374}
 1375
 1376impl EventEmitter<Event> for Workspace {}
 1377
 1378#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1379pub struct ViewId {
 1380    pub creator: CollaboratorId,
 1381    pub id: u64,
 1382}
 1383
 1384pub struct FollowerState {
 1385    center_pane: Entity<Pane>,
 1386    dock_pane: Option<Entity<Pane>>,
 1387    active_view_id: Option<ViewId>,
 1388    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1389}
 1390
 1391struct FollowerView {
 1392    view: Box<dyn FollowableItemHandle>,
 1393    location: Option<proto::PanelId>,
 1394}
 1395
 1396#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
 1397pub enum OpenMode {
 1398    /// Open the workspace in a new window.
 1399    NewWindow,
 1400    /// Add to the window's multi workspace without activating it (used during deserialization).
 1401    Add,
 1402    /// Add to the window's multi workspace and activate it.
 1403    #[default]
 1404    Activate,
 1405}
 1406
 1407impl Workspace {
 1408    pub fn new(
 1409        workspace_id: Option<WorkspaceId>,
 1410        project: Entity<Project>,
 1411        app_state: Arc<AppState>,
 1412        window: &mut Window,
 1413        cx: &mut Context<Self>,
 1414    ) -> Self {
 1415        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1416            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1417                if let TrustedWorktreesEvent::Trusted(..) = e {
 1418                    // Do not persist auto trusted worktrees
 1419                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1420                        worktrees_store.update(cx, |worktrees_store, cx| {
 1421                            worktrees_store.schedule_serialization(
 1422                                cx,
 1423                                |new_trusted_worktrees, cx| {
 1424                                    let timeout =
 1425                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1426                                    let db = WorkspaceDb::global(cx);
 1427                                    cx.background_spawn(async move {
 1428                                        timeout.await;
 1429                                        db.save_trusted_worktrees(new_trusted_worktrees)
 1430                                            .await
 1431                                            .log_err();
 1432                                    })
 1433                                },
 1434                            )
 1435                        });
 1436                    }
 1437                }
 1438            })
 1439            .detach();
 1440
 1441            cx.observe_global::<SettingsStore>(|_, cx| {
 1442                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1443                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1444                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1445                            trusted_worktrees.auto_trust_all(cx);
 1446                        })
 1447                    }
 1448                }
 1449            })
 1450            .detach();
 1451        }
 1452
 1453        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1454            match event {
 1455                project::Event::RemoteIdChanged(_) => {
 1456                    this.update_window_title(window, cx);
 1457                }
 1458
 1459                project::Event::CollaboratorLeft(peer_id) => {
 1460                    this.collaborator_left(*peer_id, window, cx);
 1461                }
 1462
 1463                &project::Event::WorktreeRemoved(_) => {
 1464                    this.update_window_title(window, cx);
 1465                    this.serialize_workspace(window, cx);
 1466                    this.update_history(cx);
 1467                }
 1468
 1469                &project::Event::WorktreeAdded(id) => {
 1470                    this.update_window_title(window, cx);
 1471                    if this
 1472                        .project()
 1473                        .read(cx)
 1474                        .worktree_for_id(id, cx)
 1475                        .is_some_and(|wt| wt.read(cx).is_visible())
 1476                    {
 1477                        this.serialize_workspace(window, cx);
 1478                        this.update_history(cx);
 1479                    }
 1480                }
 1481                project::Event::WorktreeUpdatedEntries(..) => {
 1482                    this.update_window_title(window, cx);
 1483                    this.serialize_workspace(window, cx);
 1484                }
 1485
 1486                project::Event::DisconnectedFromHost => {
 1487                    this.update_window_edited(window, cx);
 1488                    let leaders_to_unfollow =
 1489                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1490                    for leader_id in leaders_to_unfollow {
 1491                        this.unfollow(leader_id, window, cx);
 1492                    }
 1493                }
 1494
 1495                project::Event::DisconnectedFromRemote {
 1496                    server_not_running: _,
 1497                } => {
 1498                    this.update_window_edited(window, cx);
 1499                }
 1500
 1501                project::Event::Closed => {
 1502                    window.remove_window();
 1503                }
 1504
 1505                project::Event::DeletedEntry(_, entry_id) => {
 1506                    for pane in this.panes.iter() {
 1507                        pane.update(cx, |pane, cx| {
 1508                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1509                        });
 1510                    }
 1511                }
 1512
 1513                project::Event::Toast {
 1514                    notification_id,
 1515                    message,
 1516                    link,
 1517                } => this.show_notification(
 1518                    NotificationId::named(notification_id.clone()),
 1519                    cx,
 1520                    |cx| {
 1521                        let mut notification = MessageNotification::new(message.clone(), cx);
 1522                        if let Some(link) = link {
 1523                            notification = notification
 1524                                .more_info_message(link.label)
 1525                                .more_info_url(link.url);
 1526                        }
 1527
 1528                        cx.new(|_| notification)
 1529                    },
 1530                ),
 1531
 1532                project::Event::HideToast { notification_id } => {
 1533                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1534                }
 1535
 1536                project::Event::LanguageServerPrompt(request) => {
 1537                    struct LanguageServerPrompt;
 1538
 1539                    this.show_notification(
 1540                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1541                        cx,
 1542                        |cx| {
 1543                            cx.new(|cx| {
 1544                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1545                            })
 1546                        },
 1547                    );
 1548                }
 1549
 1550                project::Event::AgentLocationChanged => {
 1551                    this.handle_agent_location_changed(window, cx)
 1552                }
 1553
 1554                _ => {}
 1555            }
 1556            cx.notify()
 1557        })
 1558        .detach();
 1559
 1560        cx.subscribe_in(
 1561            &project.read(cx).breakpoint_store(),
 1562            window,
 1563            |workspace, _, event, window, cx| match event {
 1564                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1565                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1566                    workspace.serialize_workspace(window, cx);
 1567                }
 1568                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1569            },
 1570        )
 1571        .detach();
 1572        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1573            cx.subscribe_in(
 1574                &toolchain_store,
 1575                window,
 1576                |workspace, _, event, window, cx| match event {
 1577                    ToolchainStoreEvent::CustomToolchainsModified => {
 1578                        workspace.serialize_workspace(window, cx);
 1579                    }
 1580                    _ => {}
 1581                },
 1582            )
 1583            .detach();
 1584        }
 1585
 1586        cx.on_focus_lost(window, |this, window, cx| {
 1587            let focus_handle = this.focus_handle(cx);
 1588            window.focus(&focus_handle, cx);
 1589        })
 1590        .detach();
 1591
 1592        let weak_handle = cx.entity().downgrade();
 1593        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1594
 1595        let center_pane = cx.new(|cx| {
 1596            let mut center_pane = Pane::new(
 1597                weak_handle.clone(),
 1598                project.clone(),
 1599                pane_history_timestamp.clone(),
 1600                None,
 1601                NewFile.boxed_clone(),
 1602                true,
 1603                window,
 1604                cx,
 1605            );
 1606            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1607            center_pane.set_should_display_welcome_page(true);
 1608            center_pane
 1609        });
 1610        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1611            .detach();
 1612
 1613        window.focus(&center_pane.focus_handle(cx), cx);
 1614
 1615        cx.emit(Event::PaneAdded(center_pane.clone()));
 1616
 1617        let any_window_handle = window.window_handle();
 1618        app_state.workspace_store.update(cx, |store, _| {
 1619            store
 1620                .workspaces
 1621                .insert((any_window_handle, weak_handle.clone()));
 1622        });
 1623
 1624        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1625        let mut connection_status = app_state.client.status();
 1626        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1627            current_user.next().await;
 1628            connection_status.next().await;
 1629            let mut stream =
 1630                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1631
 1632            while stream.recv().await.is_some() {
 1633                this.update(cx, |_, cx| cx.notify())?;
 1634            }
 1635            anyhow::Ok(())
 1636        });
 1637
 1638        // All leader updates are enqueued and then processed in a single task, so
 1639        // that each asynchronous operation can be run in order.
 1640        let (leader_updates_tx, mut leader_updates_rx) =
 1641            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1642        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1643            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1644                Self::process_leader_update(&this, leader_id, update, cx)
 1645                    .await
 1646                    .log_err();
 1647            }
 1648
 1649            Ok(())
 1650        });
 1651
 1652        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1653        let modal_layer = cx.new(|_| ModalLayer::new());
 1654        let toast_layer = cx.new(|_| ToastLayer::new());
 1655        cx.subscribe(
 1656            &modal_layer,
 1657            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1658                cx.emit(Event::ModalOpened);
 1659            },
 1660        )
 1661        .detach();
 1662
 1663        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1664        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1665        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1666        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1667        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1668        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1669        let multi_workspace = window
 1670            .root::<MultiWorkspace>()
 1671            .flatten()
 1672            .map(|mw| mw.downgrade());
 1673        let status_bar = cx.new(|cx| {
 1674            let mut status_bar =
 1675                StatusBar::new(&center_pane.clone(), multi_workspace.clone(), window, cx);
 1676            status_bar.add_left_item(left_dock_buttons, window, cx);
 1677            status_bar.add_right_item(right_dock_buttons, window, cx);
 1678            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1679            status_bar
 1680        });
 1681
 1682        let session_id = app_state.session.read(cx).id().to_owned();
 1683
 1684        let mut active_call = None;
 1685        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1686            let subscriptions =
 1687                vec![
 1688                    call.0
 1689                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1690                ];
 1691            active_call = Some((call, subscriptions));
 1692        }
 1693
 1694        let (serializable_items_tx, serializable_items_rx) =
 1695            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1696        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1697            Self::serialize_items(&this, serializable_items_rx, cx).await
 1698        });
 1699
 1700        let subscriptions = vec![
 1701            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1702            cx.observe_window_bounds(window, move |this, window, cx| {
 1703                if this.bounds_save_task_queued.is_some() {
 1704                    return;
 1705                }
 1706                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1707                    cx.background_executor()
 1708                        .timer(Duration::from_millis(100))
 1709                        .await;
 1710                    this.update_in(cx, |this, window, cx| {
 1711                        this.save_window_bounds(window, cx).detach();
 1712                        this.bounds_save_task_queued.take();
 1713                    })
 1714                    .ok();
 1715                }));
 1716                cx.notify();
 1717            }),
 1718            cx.observe_window_appearance(window, |_, window, cx| {
 1719                let window_appearance = window.appearance();
 1720
 1721                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1722
 1723                theme_settings::reload_theme(cx);
 1724                theme_settings::reload_icon_theme(cx);
 1725            }),
 1726            cx.on_release({
 1727                let weak_handle = weak_handle.clone();
 1728                move |this, cx| {
 1729                    this.app_state.workspace_store.update(cx, move |store, _| {
 1730                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1731                    })
 1732                }
 1733            }),
 1734        ];
 1735
 1736        cx.defer_in(window, move |this, window, cx| {
 1737            this.update_window_title(window, cx);
 1738            this.show_initial_notifications(cx);
 1739        });
 1740
 1741        let mut center = PaneGroup::new(center_pane.clone());
 1742        center.set_is_center(true);
 1743        center.mark_positions(cx);
 1744
 1745        Workspace {
 1746            weak_self: weak_handle.clone(),
 1747            zoomed: None,
 1748            zoomed_position: None,
 1749            previous_dock_drag_coordinates: None,
 1750            center,
 1751            panes: vec![center_pane.clone()],
 1752            panes_by_item: Default::default(),
 1753            active_pane: center_pane.clone(),
 1754            last_active_center_pane: Some(center_pane.downgrade()),
 1755            last_active_view_id: None,
 1756            status_bar,
 1757            modal_layer,
 1758            toast_layer,
 1759            titlebar_item: None,
 1760            notifications: Notifications::default(),
 1761            suppressed_notifications: HashSet::default(),
 1762            left_dock,
 1763            bottom_dock,
 1764            right_dock,
 1765            _panels_task: None,
 1766            project: project.clone(),
 1767            follower_states: Default::default(),
 1768            last_leaders_by_pane: Default::default(),
 1769            dispatching_keystrokes: Default::default(),
 1770            window_edited: false,
 1771            last_window_title: None,
 1772            dirty_items: Default::default(),
 1773            active_call,
 1774            database_id: workspace_id,
 1775            app_state,
 1776            _observe_current_user,
 1777            _apply_leader_updates,
 1778            _schedule_serialize_workspace: None,
 1779            _serialize_workspace_task: None,
 1780            _schedule_serialize_ssh_paths: None,
 1781            leader_updates_tx,
 1782            _subscriptions: subscriptions,
 1783            pane_history_timestamp,
 1784            workspace_actions: Default::default(),
 1785            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1786            bounds: Default::default(),
 1787            centered_layout: false,
 1788            bounds_save_task_queued: None,
 1789            on_prompt_for_new_path: None,
 1790            on_prompt_for_open_path: None,
 1791            terminal_provider: None,
 1792            debugger_provider: None,
 1793            serializable_items_tx,
 1794            _items_serializer,
 1795            session_id: Some(session_id),
 1796
 1797            scheduled_tasks: Vec::new(),
 1798            last_open_dock_positions: Vec::new(),
 1799            removing: false,
 1800            sidebar_focus_handle: None,
 1801            multi_workspace,
 1802            open_in_dev_container: false,
 1803            _dev_container_task: None,
 1804        }
 1805    }
 1806
 1807    pub fn new_local(
 1808        abs_paths: Vec<PathBuf>,
 1809        app_state: Arc<AppState>,
 1810        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1811        env: Option<HashMap<String, String>>,
 1812        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1813        open_mode: OpenMode,
 1814        cx: &mut App,
 1815    ) -> Task<anyhow::Result<OpenResult>> {
 1816        let project_handle = Project::local(
 1817            app_state.client.clone(),
 1818            app_state.node_runtime.clone(),
 1819            app_state.user_store.clone(),
 1820            app_state.languages.clone(),
 1821            app_state.fs.clone(),
 1822            env,
 1823            Default::default(),
 1824            cx,
 1825        );
 1826
 1827        let db = WorkspaceDb::global(cx);
 1828        let kvp = db::kvp::KeyValueStore::global(cx);
 1829        cx.spawn(async move |cx| {
 1830            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1831            for path in abs_paths.into_iter() {
 1832                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1833                    paths_to_open.push(canonical)
 1834                } else {
 1835                    paths_to_open.push(path)
 1836                }
 1837            }
 1838
 1839            let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
 1840
 1841            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1842                paths_to_open = paths.ordered_paths().cloned().collect();
 1843                if !paths.is_lexicographically_ordered() {
 1844                    project_handle.update(cx, |project, cx| {
 1845                        project.set_worktrees_reordered(true, cx);
 1846                    });
 1847                }
 1848            }
 1849
 1850            // Get project paths for all of the abs_paths
 1851            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1852                Vec::with_capacity(paths_to_open.len());
 1853
 1854            for path in paths_to_open.into_iter() {
 1855                if let Some((_, project_entry)) = cx
 1856                    .update(|cx| {
 1857                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1858                    })
 1859                    .await
 1860                    .log_err()
 1861                {
 1862                    project_paths.push((path, Some(project_entry)));
 1863                } else {
 1864                    project_paths.push((path, None));
 1865                }
 1866            }
 1867
 1868            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1869                serialized_workspace.id
 1870            } else {
 1871                db.next_id().await.unwrap_or_else(|_| Default::default())
 1872            };
 1873
 1874            let toolchains = db.toolchains(workspace_id).await?;
 1875
 1876            for (toolchain, worktree_path, path) in toolchains {
 1877                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1878                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1879                    this.find_worktree(&worktree_path, cx)
 1880                        .and_then(|(worktree, rel_path)| {
 1881                            if rel_path.is_empty() {
 1882                                Some(worktree.read(cx).id())
 1883                            } else {
 1884                                None
 1885                            }
 1886                        })
 1887                }) else {
 1888                    // We did not find a worktree with a given path, but that's whatever.
 1889                    continue;
 1890                };
 1891                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1892                    continue;
 1893                }
 1894
 1895                project_handle
 1896                    .update(cx, |this, cx| {
 1897                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1898                    })
 1899                    .await;
 1900            }
 1901            if let Some(workspace) = serialized_workspace.as_ref() {
 1902                project_handle.update(cx, |this, cx| {
 1903                    for (scope, toolchains) in &workspace.user_toolchains {
 1904                        for toolchain in toolchains {
 1905                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1906                        }
 1907                    }
 1908                });
 1909            }
 1910
 1911            let window_to_replace = match open_mode {
 1912                OpenMode::NewWindow => None,
 1913                _ => requesting_window,
 1914            };
 1915
 1916            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1917                if let Some(window) = window_to_replace {
 1918                    let centered_layout = serialized_workspace
 1919                        .as_ref()
 1920                        .map(|w| w.centered_layout)
 1921                        .unwrap_or(false);
 1922
 1923                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1924                        let workspace = cx.new(|cx| {
 1925                            let mut workspace = Workspace::new(
 1926                                Some(workspace_id),
 1927                                project_handle.clone(),
 1928                                app_state.clone(),
 1929                                window,
 1930                                cx,
 1931                            );
 1932
 1933                            workspace.centered_layout = centered_layout;
 1934
 1935                            // Call init callback to add items before window renders
 1936                            if let Some(init) = init {
 1937                                init(&mut workspace, window, cx);
 1938                            }
 1939
 1940                            workspace
 1941                        });
 1942                        match open_mode {
 1943                            OpenMode::Activate => {
 1944                                multi_workspace.activate(workspace.clone(), window, cx);
 1945                            }
 1946                            OpenMode::Add => {
 1947                                multi_workspace.add(workspace.clone(), &*window, cx);
 1948                            }
 1949                            OpenMode::NewWindow => {
 1950                                unreachable!()
 1951                            }
 1952                        }
 1953                        workspace
 1954                    })?;
 1955                    (window, workspace)
 1956                } else {
 1957                    let window_bounds_override = window_bounds_env_override();
 1958
 1959                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1960                        (Some(WindowBounds::Windowed(bounds)), None)
 1961                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1962                        && let Some(display) = workspace.display
 1963                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1964                    {
 1965                        // Reopening an existing workspace - restore its saved bounds
 1966                        (Some(bounds.0), Some(display))
 1967                    } else if let Some((display, bounds)) =
 1968                        persistence::read_default_window_bounds(&kvp)
 1969                    {
 1970                        // New or empty workspace - use the last known window bounds
 1971                        (Some(bounds), Some(display))
 1972                    } else {
 1973                        // New window - let GPUI's default_bounds() handle cascading
 1974                        (None, None)
 1975                    };
 1976
 1977                    // Use the serialized workspace to construct the new window
 1978                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1979                    options.window_bounds = window_bounds;
 1980                    let centered_layout = serialized_workspace
 1981                        .as_ref()
 1982                        .map(|w| w.centered_layout)
 1983                        .unwrap_or(false);
 1984                    let window = cx.open_window(options, {
 1985                        let app_state = app_state.clone();
 1986                        let project_handle = project_handle.clone();
 1987                        move |window, cx| {
 1988                            let workspace = cx.new(|cx| {
 1989                                let mut workspace = Workspace::new(
 1990                                    Some(workspace_id),
 1991                                    project_handle,
 1992                                    app_state,
 1993                                    window,
 1994                                    cx,
 1995                                );
 1996                                workspace.centered_layout = centered_layout;
 1997
 1998                                // Call init callback to add items before window renders
 1999                                if let Some(init) = init {
 2000                                    init(&mut workspace, window, cx);
 2001                                }
 2002
 2003                                workspace
 2004                            });
 2005                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 2006                        }
 2007                    })?;
 2008                    let workspace =
 2009                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 2010                            multi_workspace.workspace().clone()
 2011                        })?;
 2012                    (window, workspace)
 2013                };
 2014
 2015            notify_if_database_failed(window, cx);
 2016            // Check if this is an empty workspace (no paths to open)
 2017            // An empty workspace is one where project_paths is empty
 2018            let is_empty_workspace = project_paths.is_empty();
 2019            // Check if serialized workspace has paths before it's moved
 2020            let serialized_workspace_has_paths = serialized_workspace
 2021                .as_ref()
 2022                .map(|ws| !ws.paths.is_empty())
 2023                .unwrap_or(false);
 2024
 2025            let opened_items = window
 2026                .update(cx, |_, window, cx| {
 2027                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 2028                        open_items(serialized_workspace, project_paths, window, cx)
 2029                    })
 2030                })?
 2031                .await
 2032                .unwrap_or_default();
 2033
 2034            // Restore default dock state for empty workspaces
 2035            // Only restore if:
 2036            // 1. This is an empty workspace (no paths), AND
 2037            // 2. The serialized workspace either doesn't exist or has no paths
 2038            if is_empty_workspace && !serialized_workspace_has_paths {
 2039                if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
 2040                    window
 2041                        .update(cx, |_, window, cx| {
 2042                            workspace.update(cx, |workspace, cx| {
 2043                                for (dock, serialized_dock) in [
 2044                                    (&workspace.right_dock, &default_docks.right),
 2045                                    (&workspace.left_dock, &default_docks.left),
 2046                                    (&workspace.bottom_dock, &default_docks.bottom),
 2047                                ] {
 2048                                    dock.update(cx, |dock, cx| {
 2049                                        dock.serialized_dock = Some(serialized_dock.clone());
 2050                                        dock.restore_state(window, cx);
 2051                                    });
 2052                                }
 2053                                cx.notify();
 2054                            });
 2055                        })
 2056                        .log_err();
 2057                }
 2058            }
 2059
 2060            window
 2061                .update(cx, |_, _window, cx| {
 2062                    workspace.update(cx, |this: &mut Workspace, cx| {
 2063                        this.update_history(cx);
 2064                    });
 2065                })
 2066                .log_err();
 2067            Ok(OpenResult {
 2068                window,
 2069                workspace,
 2070                opened_items,
 2071            })
 2072        })
 2073    }
 2074
 2075    pub fn project_group_key(&self, cx: &App) -> ProjectGroupKey {
 2076        self.project.read(cx).project_group_key(cx)
 2077    }
 2078
 2079    pub fn weak_handle(&self) -> WeakEntity<Self> {
 2080        self.weak_self.clone()
 2081    }
 2082
 2083    pub fn left_dock(&self) -> &Entity<Dock> {
 2084        &self.left_dock
 2085    }
 2086
 2087    pub fn bottom_dock(&self) -> &Entity<Dock> {
 2088        &self.bottom_dock
 2089    }
 2090
 2091    pub fn set_bottom_dock_layout(
 2092        &mut self,
 2093        layout: BottomDockLayout,
 2094        window: &mut Window,
 2095        cx: &mut Context<Self>,
 2096    ) {
 2097        let fs = self.project().read(cx).fs();
 2098        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 2099            content.workspace.bottom_dock_layout = Some(layout);
 2100        });
 2101
 2102        cx.notify();
 2103        self.serialize_workspace(window, cx);
 2104    }
 2105
 2106    pub fn right_dock(&self) -> &Entity<Dock> {
 2107        &self.right_dock
 2108    }
 2109
 2110    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 2111        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 2112    }
 2113
 2114    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 2115        let left_dock = self.left_dock.read(cx);
 2116        let left_visible = left_dock.is_open();
 2117        let left_active_panel = left_dock
 2118            .active_panel()
 2119            .map(|panel| panel.persistent_name().to_string());
 2120        // `zoomed_position` is kept in sync with individual panel zoom state
 2121        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2122        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2123
 2124        let right_dock = self.right_dock.read(cx);
 2125        let right_visible = right_dock.is_open();
 2126        let right_active_panel = right_dock
 2127            .active_panel()
 2128            .map(|panel| panel.persistent_name().to_string());
 2129        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2130
 2131        let bottom_dock = self.bottom_dock.read(cx);
 2132        let bottom_visible = bottom_dock.is_open();
 2133        let bottom_active_panel = bottom_dock
 2134            .active_panel()
 2135            .map(|panel| panel.persistent_name().to_string());
 2136        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2137
 2138        DockStructure {
 2139            left: DockData {
 2140                visible: left_visible,
 2141                active_panel: left_active_panel,
 2142                zoom: left_dock_zoom,
 2143            },
 2144            right: DockData {
 2145                visible: right_visible,
 2146                active_panel: right_active_panel,
 2147                zoom: right_dock_zoom,
 2148            },
 2149            bottom: DockData {
 2150                visible: bottom_visible,
 2151                active_panel: bottom_active_panel,
 2152                zoom: bottom_dock_zoom,
 2153            },
 2154        }
 2155    }
 2156
 2157    pub fn set_dock_structure(
 2158        &self,
 2159        docks: DockStructure,
 2160        window: &mut Window,
 2161        cx: &mut Context<Self>,
 2162    ) {
 2163        for (dock, data) in [
 2164            (&self.left_dock, docks.left),
 2165            (&self.bottom_dock, docks.bottom),
 2166            (&self.right_dock, docks.right),
 2167        ] {
 2168            dock.update(cx, |dock, cx| {
 2169                dock.serialized_dock = Some(data);
 2170                dock.restore_state(window, cx);
 2171            });
 2172        }
 2173    }
 2174
 2175    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2176        self.items(cx)
 2177            .filter_map(|item| {
 2178                let project_path = item.project_path(cx)?;
 2179                self.project.read(cx).absolute_path(&project_path, cx)
 2180            })
 2181            .collect()
 2182    }
 2183
 2184    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2185        match position {
 2186            DockPosition::Left => &self.left_dock,
 2187            DockPosition::Bottom => &self.bottom_dock,
 2188            DockPosition::Right => &self.right_dock,
 2189        }
 2190    }
 2191
 2192    pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
 2193        self.all_docks().into_iter().find_map(|dock| {
 2194            let dock = dock.read(cx);
 2195            dock.has_agent_panel(cx).then_some(dock.position())
 2196        })
 2197    }
 2198
 2199    pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
 2200        self.all_docks().into_iter().find_map(|dock| {
 2201            let dock = dock.read(cx);
 2202            let panel = dock.panel::<T>()?;
 2203            dock.stored_panel_size_state(&panel)
 2204        })
 2205    }
 2206
 2207    pub fn persisted_panel_size_state(
 2208        &self,
 2209        panel_key: &'static str,
 2210        cx: &App,
 2211    ) -> Option<dock::PanelSizeState> {
 2212        dock::Dock::load_persisted_size_state(self, panel_key, cx)
 2213    }
 2214
 2215    pub fn persist_panel_size_state(
 2216        &self,
 2217        panel_key: &str,
 2218        size_state: dock::PanelSizeState,
 2219        cx: &mut App,
 2220    ) {
 2221        let Some(workspace_id) = self
 2222            .database_id()
 2223            .map(|id| i64::from(id).to_string())
 2224            .or(self.session_id())
 2225        else {
 2226            return;
 2227        };
 2228
 2229        let kvp = db::kvp::KeyValueStore::global(cx);
 2230        let panel_key = panel_key.to_string();
 2231        cx.background_spawn(async move {
 2232            let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
 2233            scope
 2234                .write(
 2235                    format!("{workspace_id}:{panel_key}"),
 2236                    serde_json::to_string(&size_state)?,
 2237                )
 2238                .await
 2239        })
 2240        .detach_and_log_err(cx);
 2241    }
 2242
 2243    pub fn set_panel_size_state<T: Panel>(
 2244        &mut self,
 2245        size_state: dock::PanelSizeState,
 2246        window: &mut Window,
 2247        cx: &mut Context<Self>,
 2248    ) -> bool {
 2249        let Some(panel) = self.panel::<T>(cx) else {
 2250            return false;
 2251        };
 2252
 2253        let dock = self.dock_at_position(panel.position(window, cx));
 2254        let did_set = dock.update(cx, |dock, cx| {
 2255            dock.set_panel_size_state(&panel, size_state, cx)
 2256        });
 2257
 2258        if did_set {
 2259            self.persist_panel_size_state(T::panel_key(), size_state, cx);
 2260        }
 2261
 2262        did_set
 2263    }
 2264
 2265    pub fn toggle_dock_panel_flexible_size(
 2266        &self,
 2267        dock: &Entity<Dock>,
 2268        panel: &dyn PanelHandle,
 2269        window: &mut Window,
 2270        cx: &mut App,
 2271    ) {
 2272        let position = dock.read(cx).position();
 2273        let current_size = self.dock_size(&dock.read(cx), window, cx);
 2274        let current_flex =
 2275            current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
 2276        dock.update(cx, |dock, cx| {
 2277            dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
 2278        });
 2279    }
 2280
 2281    fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
 2282        let panel = dock.active_panel()?;
 2283        let size_state = dock
 2284            .stored_panel_size_state(panel.as_ref())
 2285            .unwrap_or_default();
 2286        let position = dock.position();
 2287
 2288        let use_flex = panel.has_flexible_size(window, cx);
 2289
 2290        if position.axis() == Axis::Horizontal
 2291            && use_flex
 2292            && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
 2293        {
 2294            let workspace_width = self.bounds.size.width;
 2295            if workspace_width <= Pixels::ZERO {
 2296                return None;
 2297            }
 2298            let flex = flex.max(0.001);
 2299            let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2300            if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2301                // Both docks are flex items sharing the full workspace width.
 2302                let total_flex = flex + 1.0 + opposite_flex;
 2303                return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
 2304            } else {
 2305                // Opposite dock is fixed-width; flex items share (W - fixed).
 2306                let opposite_fixed = opposite
 2307                    .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2308                    .unwrap_or_default();
 2309                let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
 2310                return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
 2311            }
 2312        }
 2313
 2314        Some(
 2315            size_state
 2316                .size
 2317                .unwrap_or_else(|| panel.default_size(window, cx)),
 2318        )
 2319    }
 2320
 2321    pub fn dock_flex_for_size(
 2322        &self,
 2323        position: DockPosition,
 2324        size: Pixels,
 2325        window: &Window,
 2326        cx: &App,
 2327    ) -> Option<f32> {
 2328        if position.axis() != Axis::Horizontal {
 2329            return None;
 2330        }
 2331
 2332        let workspace_width = self.bounds.size.width;
 2333        if workspace_width <= Pixels::ZERO {
 2334            return None;
 2335        }
 2336
 2337        let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2338        if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2339            let size = size.clamp(px(0.), workspace_width - px(1.));
 2340            Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
 2341        } else {
 2342            let opposite_width = opposite
 2343                .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2344                .unwrap_or_default();
 2345            let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
 2346            let remaining = (available - size).max(px(1.));
 2347            Some((size / remaining).max(0.0))
 2348        }
 2349    }
 2350
 2351    fn opposite_dock_panel_and_size_state(
 2352        &self,
 2353        position: DockPosition,
 2354        window: &Window,
 2355        cx: &App,
 2356    ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
 2357        let opposite_position = match position {
 2358            DockPosition::Left => DockPosition::Right,
 2359            DockPosition::Right => DockPosition::Left,
 2360            DockPosition::Bottom => return None,
 2361        };
 2362
 2363        let opposite_dock = self.dock_at_position(opposite_position).read(cx);
 2364        let panel = opposite_dock.visible_panel()?;
 2365        let mut size_state = opposite_dock
 2366            .stored_panel_size_state(panel.as_ref())
 2367            .unwrap_or_default();
 2368        if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
 2369            size_state.flex = self.default_dock_flex(opposite_position);
 2370        }
 2371        Some((panel.clone(), size_state))
 2372    }
 2373
 2374    pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
 2375        if position.axis() != Axis::Horizontal {
 2376            return None;
 2377        }
 2378
 2379        let pane = self.last_active_center_pane.clone()?.upgrade()?;
 2380        Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
 2381    }
 2382
 2383    pub fn is_edited(&self) -> bool {
 2384        self.window_edited
 2385    }
 2386
 2387    pub fn add_panel<T: Panel>(
 2388        &mut self,
 2389        panel: Entity<T>,
 2390        window: &mut Window,
 2391        cx: &mut Context<Self>,
 2392    ) {
 2393        let focus_handle = panel.panel_focus_handle(cx);
 2394        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2395            .detach();
 2396
 2397        let dock_position = panel.position(window, cx);
 2398        let dock = self.dock_at_position(dock_position);
 2399        let any_panel = panel.to_any();
 2400        let persisted_size_state =
 2401            self.persisted_panel_size_state(T::panel_key(), cx)
 2402                .or_else(|| {
 2403                    load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
 2404                        let state = dock::PanelSizeState {
 2405                            size: Some(size),
 2406                            flex: None,
 2407                        };
 2408                        self.persist_panel_size_state(T::panel_key(), state, cx);
 2409                        state
 2410                    })
 2411                });
 2412
 2413        dock.update(cx, |dock, cx| {
 2414            let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
 2415            if let Some(size_state) = persisted_size_state {
 2416                dock.set_panel_size_state(&panel, size_state, cx);
 2417            }
 2418            index
 2419        });
 2420
 2421        cx.emit(Event::PanelAdded(any_panel));
 2422    }
 2423
 2424    pub fn remove_panel<T: Panel>(
 2425        &mut self,
 2426        panel: &Entity<T>,
 2427        window: &mut Window,
 2428        cx: &mut Context<Self>,
 2429    ) {
 2430        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2431            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2432        }
 2433    }
 2434
 2435    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2436        &self.status_bar
 2437    }
 2438
 2439    pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
 2440        self.sidebar_focus_handle = handle;
 2441    }
 2442
 2443    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2444        StatusBarSettings::get_global(cx).show
 2445    }
 2446
 2447    pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
 2448        self.multi_workspace.as_ref()
 2449    }
 2450
 2451    pub fn set_multi_workspace(
 2452        &mut self,
 2453        multi_workspace: WeakEntity<MultiWorkspace>,
 2454        cx: &mut App,
 2455    ) {
 2456        self.status_bar.update(cx, |status_bar, cx| {
 2457            status_bar.set_multi_workspace(multi_workspace.clone(), cx);
 2458        });
 2459        self.multi_workspace = Some(multi_workspace);
 2460    }
 2461
 2462    pub fn app_state(&self) -> &Arc<AppState> {
 2463        &self.app_state
 2464    }
 2465
 2466    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2467        self._panels_task = Some(task);
 2468    }
 2469
 2470    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2471        self._panels_task.take()
 2472    }
 2473
 2474    pub fn user_store(&self) -> &Entity<UserStore> {
 2475        &self.app_state.user_store
 2476    }
 2477
 2478    pub fn project(&self) -> &Entity<Project> {
 2479        &self.project
 2480    }
 2481
 2482    pub fn path_style(&self, cx: &App) -> PathStyle {
 2483        self.project.read(cx).path_style(cx)
 2484    }
 2485
 2486    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2487        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2488
 2489        for pane_handle in &self.panes {
 2490            let pane = pane_handle.read(cx);
 2491
 2492            for entry in pane.activation_history() {
 2493                history.insert(
 2494                    entry.entity_id,
 2495                    history
 2496                        .get(&entry.entity_id)
 2497                        .cloned()
 2498                        .unwrap_or(0)
 2499                        .max(entry.timestamp),
 2500                );
 2501            }
 2502        }
 2503
 2504        history
 2505    }
 2506
 2507    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2508        let mut recent_item: Option<Entity<T>> = None;
 2509        let mut recent_timestamp = 0;
 2510        for pane_handle in &self.panes {
 2511            let pane = pane_handle.read(cx);
 2512            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2513                pane.items().map(|item| (item.item_id(), item)).collect();
 2514            for entry in pane.activation_history() {
 2515                if entry.timestamp > recent_timestamp
 2516                    && let Some(&item) = item_map.get(&entry.entity_id)
 2517                    && let Some(typed_item) = item.act_as::<T>(cx)
 2518                {
 2519                    recent_timestamp = entry.timestamp;
 2520                    recent_item = Some(typed_item);
 2521                }
 2522            }
 2523        }
 2524        recent_item
 2525    }
 2526
 2527    pub fn recent_navigation_history_iter(
 2528        &self,
 2529        cx: &App,
 2530    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2531        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2532        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2533
 2534        for pane in &self.panes {
 2535            let pane = pane.read(cx);
 2536
 2537            pane.nav_history()
 2538                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2539                    if let Some(fs_path) = &fs_path {
 2540                        abs_paths_opened
 2541                            .entry(fs_path.clone())
 2542                            .or_default()
 2543                            .insert(project_path.clone());
 2544                    }
 2545                    let timestamp = entry.timestamp;
 2546                    match history.entry(project_path) {
 2547                        hash_map::Entry::Occupied(mut entry) => {
 2548                            let (_, old_timestamp) = entry.get();
 2549                            if &timestamp > old_timestamp {
 2550                                entry.insert((fs_path, timestamp));
 2551                            }
 2552                        }
 2553                        hash_map::Entry::Vacant(entry) => {
 2554                            entry.insert((fs_path, timestamp));
 2555                        }
 2556                    }
 2557                });
 2558
 2559            if let Some(item) = pane.active_item()
 2560                && let Some(project_path) = item.project_path(cx)
 2561            {
 2562                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2563
 2564                if let Some(fs_path) = &fs_path {
 2565                    abs_paths_opened
 2566                        .entry(fs_path.clone())
 2567                        .or_default()
 2568                        .insert(project_path.clone());
 2569                }
 2570
 2571                history.insert(project_path, (fs_path, std::usize::MAX));
 2572            }
 2573        }
 2574
 2575        history
 2576            .into_iter()
 2577            .sorted_by_key(|(_, (_, order))| *order)
 2578            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2579            .rev()
 2580            .filter(move |(history_path, abs_path)| {
 2581                let latest_project_path_opened = abs_path
 2582                    .as_ref()
 2583                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2584                    .and_then(|project_paths| {
 2585                        project_paths
 2586                            .iter()
 2587                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2588                    });
 2589
 2590                latest_project_path_opened.is_none_or(|path| path == history_path)
 2591            })
 2592    }
 2593
 2594    pub fn recent_navigation_history(
 2595        &self,
 2596        limit: Option<usize>,
 2597        cx: &App,
 2598    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2599        self.recent_navigation_history_iter(cx)
 2600            .take(limit.unwrap_or(usize::MAX))
 2601            .collect()
 2602    }
 2603
 2604    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2605        for pane in &self.panes {
 2606            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2607        }
 2608    }
 2609
 2610    fn navigate_history(
 2611        &mut self,
 2612        pane: WeakEntity<Pane>,
 2613        mode: NavigationMode,
 2614        window: &mut Window,
 2615        cx: &mut Context<Workspace>,
 2616    ) -> Task<Result<()>> {
 2617        self.navigate_history_impl(
 2618            pane,
 2619            mode,
 2620            window,
 2621            &mut |history, cx| history.pop(mode, cx),
 2622            cx,
 2623        )
 2624    }
 2625
 2626    fn navigate_tag_history(
 2627        &mut self,
 2628        pane: WeakEntity<Pane>,
 2629        mode: TagNavigationMode,
 2630        window: &mut Window,
 2631        cx: &mut Context<Workspace>,
 2632    ) -> Task<Result<()>> {
 2633        self.navigate_history_impl(
 2634            pane,
 2635            NavigationMode::Normal,
 2636            window,
 2637            &mut |history, _cx| history.pop_tag(mode),
 2638            cx,
 2639        )
 2640    }
 2641
 2642    fn navigate_history_impl(
 2643        &mut self,
 2644        pane: WeakEntity<Pane>,
 2645        mode: NavigationMode,
 2646        window: &mut Window,
 2647        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2648        cx: &mut Context<Workspace>,
 2649    ) -> Task<Result<()>> {
 2650        let to_load = if let Some(pane) = pane.upgrade() {
 2651            pane.update(cx, |pane, cx| {
 2652                window.focus(&pane.focus_handle(cx), cx);
 2653                loop {
 2654                    // Retrieve the weak item handle from the history.
 2655                    let entry = cb(pane.nav_history_mut(), cx)?;
 2656
 2657                    // If the item is still present in this pane, then activate it.
 2658                    if let Some(index) = entry
 2659                        .item
 2660                        .upgrade()
 2661                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2662                    {
 2663                        let prev_active_item_index = pane.active_item_index();
 2664                        pane.nav_history_mut().set_mode(mode);
 2665                        pane.activate_item(index, true, true, window, cx);
 2666                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2667
 2668                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2669                        if let Some(data) = entry.data {
 2670                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2671                        }
 2672
 2673                        if navigated {
 2674                            break None;
 2675                        }
 2676                    } else {
 2677                        // If the item is no longer present in this pane, then retrieve its
 2678                        // path info in order to reopen it.
 2679                        break pane
 2680                            .nav_history()
 2681                            .path_for_item(entry.item.id())
 2682                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2683                    }
 2684                }
 2685            })
 2686        } else {
 2687            None
 2688        };
 2689
 2690        if let Some((project_path, abs_path, entry)) = to_load {
 2691            // If the item was no longer present, then load it again from its previous path, first try the local path
 2692            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2693
 2694            cx.spawn_in(window, async move  |workspace, cx| {
 2695                let open_by_project_path = open_by_project_path.await;
 2696                let mut navigated = false;
 2697                match open_by_project_path
 2698                    .with_context(|| format!("Navigating to {project_path:?}"))
 2699                {
 2700                    Ok((project_entry_id, build_item)) => {
 2701                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2702                            pane.nav_history_mut().set_mode(mode);
 2703                            pane.active_item().map(|p| p.item_id())
 2704                        })?;
 2705
 2706                        pane.update_in(cx, |pane, window, cx| {
 2707                            let item = pane.open_item(
 2708                                project_entry_id,
 2709                                project_path,
 2710                                true,
 2711                                entry.is_preview,
 2712                                true,
 2713                                None,
 2714                                window, cx,
 2715                                build_item,
 2716                            );
 2717                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2718                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2719                            if let Some(data) = entry.data {
 2720                                navigated |= item.navigate(data, window, cx);
 2721                            }
 2722                        })?;
 2723                    }
 2724                    Err(open_by_project_path_e) => {
 2725                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2726                        // and its worktree is now dropped
 2727                        if let Some(abs_path) = abs_path {
 2728                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2729                                pane.nav_history_mut().set_mode(mode);
 2730                                pane.active_item().map(|p| p.item_id())
 2731                            })?;
 2732                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2733                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2734                            })?;
 2735                            match open_by_abs_path
 2736                                .await
 2737                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2738                            {
 2739                                Ok(item) => {
 2740                                    pane.update_in(cx, |pane, window, cx| {
 2741                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2742                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2743                                        if let Some(data) = entry.data {
 2744                                            navigated |= item.navigate(data, window, cx);
 2745                                        }
 2746                                    })?;
 2747                                }
 2748                                Err(open_by_abs_path_e) => {
 2749                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2750                                }
 2751                            }
 2752                        }
 2753                    }
 2754                }
 2755
 2756                if !navigated {
 2757                    workspace
 2758                        .update_in(cx, |workspace, window, cx| {
 2759                            Self::navigate_history(workspace, pane, mode, window, cx)
 2760                        })?
 2761                        .await?;
 2762                }
 2763
 2764                Ok(())
 2765            })
 2766        } else {
 2767            Task::ready(Ok(()))
 2768        }
 2769    }
 2770
 2771    pub fn go_back(
 2772        &mut self,
 2773        pane: WeakEntity<Pane>,
 2774        window: &mut Window,
 2775        cx: &mut Context<Workspace>,
 2776    ) -> Task<Result<()>> {
 2777        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2778    }
 2779
 2780    pub fn go_forward(
 2781        &mut self,
 2782        pane: WeakEntity<Pane>,
 2783        window: &mut Window,
 2784        cx: &mut Context<Workspace>,
 2785    ) -> Task<Result<()>> {
 2786        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2787    }
 2788
 2789    pub fn reopen_closed_item(
 2790        &mut self,
 2791        window: &mut Window,
 2792        cx: &mut Context<Workspace>,
 2793    ) -> Task<Result<()>> {
 2794        self.navigate_history(
 2795            self.active_pane().downgrade(),
 2796            NavigationMode::ReopeningClosedItem,
 2797            window,
 2798            cx,
 2799        )
 2800    }
 2801
 2802    pub fn client(&self) -> &Arc<Client> {
 2803        &self.app_state.client
 2804    }
 2805
 2806    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2807        self.titlebar_item = Some(item);
 2808        cx.notify();
 2809    }
 2810
 2811    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2812        self.on_prompt_for_new_path = Some(prompt)
 2813    }
 2814
 2815    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2816        self.on_prompt_for_open_path = Some(prompt)
 2817    }
 2818
 2819    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2820        self.terminal_provider = Some(Box::new(provider));
 2821    }
 2822
 2823    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2824        self.debugger_provider = Some(Arc::new(provider));
 2825    }
 2826
 2827    pub fn set_open_in_dev_container(&mut self, value: bool) {
 2828        self.open_in_dev_container = value;
 2829    }
 2830
 2831    pub fn open_in_dev_container(&self) -> bool {
 2832        self.open_in_dev_container
 2833    }
 2834
 2835    pub fn set_dev_container_task(&mut self, task: Task<Result<()>>) {
 2836        self._dev_container_task = Some(task);
 2837    }
 2838
 2839    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2840        self.debugger_provider.clone()
 2841    }
 2842
 2843    pub fn prompt_for_open_path(
 2844        &mut self,
 2845        path_prompt_options: PathPromptOptions,
 2846        lister: DirectoryLister,
 2847        window: &mut Window,
 2848        cx: &mut Context<Self>,
 2849    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2850        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2851            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2852            let rx = prompt(self, lister, window, cx);
 2853            self.on_prompt_for_open_path = Some(prompt);
 2854            rx
 2855        } else {
 2856            let (tx, rx) = oneshot::channel();
 2857            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2858
 2859            cx.spawn_in(window, async move |workspace, cx| {
 2860                let Ok(result) = abs_path.await else {
 2861                    return Ok(());
 2862                };
 2863
 2864                match result {
 2865                    Ok(result) => {
 2866                        tx.send(result).ok();
 2867                    }
 2868                    Err(err) => {
 2869                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2870                            workspace.show_portal_error(err.to_string(), cx);
 2871                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2872                            let rx = prompt(workspace, lister, window, cx);
 2873                            workspace.on_prompt_for_open_path = Some(prompt);
 2874                            rx
 2875                        })?;
 2876                        if let Ok(path) = rx.await {
 2877                            tx.send(path).ok();
 2878                        }
 2879                    }
 2880                };
 2881                anyhow::Ok(())
 2882            })
 2883            .detach();
 2884
 2885            rx
 2886        }
 2887    }
 2888
 2889    pub fn prompt_for_new_path(
 2890        &mut self,
 2891        lister: DirectoryLister,
 2892        suggested_name: Option<String>,
 2893        window: &mut Window,
 2894        cx: &mut Context<Self>,
 2895    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2896        if self.project.read(cx).is_via_collab()
 2897            || self.project.read(cx).is_via_remote_server()
 2898            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2899        {
 2900            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2901            let rx = prompt(self, lister, suggested_name, window, cx);
 2902            self.on_prompt_for_new_path = Some(prompt);
 2903            return rx;
 2904        }
 2905
 2906        let (tx, rx) = oneshot::channel();
 2907        cx.spawn_in(window, async move |workspace, cx| {
 2908            let abs_path = workspace.update(cx, |workspace, cx| {
 2909                let relative_to = workspace
 2910                    .most_recent_active_path(cx)
 2911                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2912                    .or_else(|| {
 2913                        let project = workspace.project.read(cx);
 2914                        project.visible_worktrees(cx).find_map(|worktree| {
 2915                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2916                        })
 2917                    })
 2918                    .or_else(std::env::home_dir)
 2919                    .unwrap_or_else(|| PathBuf::from(""));
 2920                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2921            })?;
 2922            let abs_path = match abs_path.await? {
 2923                Ok(path) => path,
 2924                Err(err) => {
 2925                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2926                        workspace.show_portal_error(err.to_string(), cx);
 2927
 2928                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2929                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2930                        workspace.on_prompt_for_new_path = Some(prompt);
 2931                        rx
 2932                    })?;
 2933                    if let Ok(path) = rx.await {
 2934                        tx.send(path).ok();
 2935                    }
 2936                    return anyhow::Ok(());
 2937                }
 2938            };
 2939
 2940            tx.send(abs_path.map(|path| vec![path])).ok();
 2941            anyhow::Ok(())
 2942        })
 2943        .detach();
 2944
 2945        rx
 2946    }
 2947
 2948    pub fn titlebar_item(&self) -> Option<AnyView> {
 2949        self.titlebar_item.clone()
 2950    }
 2951
 2952    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2953    ///
 2954    /// If the given workspace has a local project, then it will be passed
 2955    /// to the callback. Otherwise, a new empty window will be created.
 2956    pub fn with_local_workspace<T, F>(
 2957        &mut self,
 2958        window: &mut Window,
 2959        cx: &mut Context<Self>,
 2960        callback: F,
 2961    ) -> Task<Result<T>>
 2962    where
 2963        T: 'static,
 2964        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2965    {
 2966        if self.project.read(cx).is_local() {
 2967            Task::ready(Ok(callback(self, window, cx)))
 2968        } else {
 2969            let env = self.project.read(cx).cli_environment(cx);
 2970            let task = Self::new_local(
 2971                Vec::new(),
 2972                self.app_state.clone(),
 2973                None,
 2974                env,
 2975                None,
 2976                OpenMode::Activate,
 2977                cx,
 2978            );
 2979            cx.spawn_in(window, async move |_vh, cx| {
 2980                let OpenResult {
 2981                    window: multi_workspace_window,
 2982                    ..
 2983                } = task.await?;
 2984                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2985                    let workspace = multi_workspace.workspace().clone();
 2986                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2987                })
 2988            })
 2989        }
 2990    }
 2991
 2992    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2993    ///
 2994    /// If the given workspace has a local project, then it will be passed
 2995    /// to the callback. Otherwise, a new empty window will be created.
 2996    pub fn with_local_or_wsl_workspace<T, F>(
 2997        &mut self,
 2998        window: &mut Window,
 2999        cx: &mut Context<Self>,
 3000        callback: F,
 3001    ) -> Task<Result<T>>
 3002    where
 3003        T: 'static,
 3004        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 3005    {
 3006        let project = self.project.read(cx);
 3007        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 3008            Task::ready(Ok(callback(self, window, cx)))
 3009        } else {
 3010            let env = self.project.read(cx).cli_environment(cx);
 3011            let task = Self::new_local(
 3012                Vec::new(),
 3013                self.app_state.clone(),
 3014                None,
 3015                env,
 3016                None,
 3017                OpenMode::Activate,
 3018                cx,
 3019            );
 3020            cx.spawn_in(window, async move |_vh, cx| {
 3021                let OpenResult {
 3022                    window: multi_workspace_window,
 3023                    ..
 3024                } = task.await?;
 3025                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 3026                    let workspace = multi_workspace.workspace().clone();
 3027                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 3028                })
 3029            })
 3030        }
 3031    }
 3032
 3033    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3034        self.project.read(cx).worktrees(cx)
 3035    }
 3036
 3037    pub fn visible_worktrees<'a>(
 3038        &self,
 3039        cx: &'a App,
 3040    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3041        self.project.read(cx).visible_worktrees(cx)
 3042    }
 3043
 3044    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 3045        let futures = self
 3046            .worktrees(cx)
 3047            .filter_map(|worktree| worktree.read(cx).as_local())
 3048            .map(|worktree| worktree.scan_complete())
 3049            .collect::<Vec<_>>();
 3050        async move {
 3051            for future in futures {
 3052                future.await;
 3053            }
 3054        }
 3055    }
 3056
 3057    pub fn close_global(cx: &mut App) {
 3058        cx.defer(|cx| {
 3059            cx.windows().iter().find(|window| {
 3060                window
 3061                    .update(cx, |_, window, _| {
 3062                        if window.is_window_active() {
 3063                            //This can only get called when the window's project connection has been lost
 3064                            //so we don't need to prompt the user for anything and instead just close the window
 3065                            window.remove_window();
 3066                            true
 3067                        } else {
 3068                            false
 3069                        }
 3070                    })
 3071                    .unwrap_or(false)
 3072            });
 3073        });
 3074    }
 3075
 3076    pub fn move_focused_panel_to_next_position(
 3077        &mut self,
 3078        _: &MoveFocusedPanelToNextPosition,
 3079        window: &mut Window,
 3080        cx: &mut Context<Self>,
 3081    ) {
 3082        let docks = self.all_docks();
 3083        let active_dock = docks
 3084            .into_iter()
 3085            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 3086
 3087        if let Some(dock) = active_dock {
 3088            dock.update(cx, |dock, cx| {
 3089                let active_panel = dock
 3090                    .active_panel()
 3091                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 3092
 3093                if let Some(panel) = active_panel {
 3094                    panel.move_to_next_position(window, cx);
 3095                }
 3096            })
 3097        }
 3098    }
 3099
 3100    pub fn prepare_to_close(
 3101        &mut self,
 3102        close_intent: CloseIntent,
 3103        window: &mut Window,
 3104        cx: &mut Context<Self>,
 3105    ) -> Task<Result<bool>> {
 3106        let active_call = self.active_global_call();
 3107
 3108        cx.spawn_in(window, async move |this, cx| {
 3109            this.update(cx, |this, _| {
 3110                if close_intent == CloseIntent::CloseWindow {
 3111                    this.removing = true;
 3112                }
 3113            })?;
 3114
 3115            let workspace_count = cx.update(|_window, cx| {
 3116                cx.windows()
 3117                    .iter()
 3118                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 3119                    .count()
 3120            })?;
 3121
 3122            #[cfg(target_os = "macos")]
 3123            let save_last_workspace = false;
 3124
 3125            // On Linux and Windows, closing the last window should restore the last workspace.
 3126            #[cfg(not(target_os = "macos"))]
 3127            let save_last_workspace = {
 3128                let remaining_workspaces = cx.update(|_window, cx| {
 3129                    cx.windows()
 3130                        .iter()
 3131                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 3132                        .filter_map(|multi_workspace| {
 3133                            multi_workspace
 3134                                .update(cx, |multi_workspace, _, cx| {
 3135                                    multi_workspace.workspace().read(cx).removing
 3136                                })
 3137                                .ok()
 3138                        })
 3139                        .filter(|removing| !removing)
 3140                        .count()
 3141                })?;
 3142
 3143                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 3144            };
 3145
 3146            if let Some(active_call) = active_call
 3147                && workspace_count == 1
 3148                && cx
 3149                    .update(|_window, cx| active_call.0.is_in_room(cx))
 3150                    .unwrap_or(false)
 3151            {
 3152                if close_intent == CloseIntent::CloseWindow {
 3153                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3154                    let answer = cx.update(|window, cx| {
 3155                        window.prompt(
 3156                            PromptLevel::Warning,
 3157                            "Do you want to leave the current call?",
 3158                            None,
 3159                            &["Close window and hang up", "Cancel"],
 3160                            cx,
 3161                        )
 3162                    })?;
 3163
 3164                    if answer.await.log_err() == Some(1) {
 3165                        return anyhow::Ok(false);
 3166                    } else {
 3167                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 3168                            task.await.log_err();
 3169                        }
 3170                    }
 3171                }
 3172                if close_intent == CloseIntent::ReplaceWindow {
 3173                    _ = cx.update(|_window, cx| {
 3174                        let multi_workspace = cx
 3175                            .windows()
 3176                            .iter()
 3177                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 3178                            .next()
 3179                            .unwrap();
 3180                        let project = multi_workspace
 3181                            .read(cx)?
 3182                            .workspace()
 3183                            .read(cx)
 3184                            .project
 3185                            .clone();
 3186                        if project.read(cx).is_shared() {
 3187                            active_call.0.unshare_project(project, cx)?;
 3188                        }
 3189                        Ok::<_, anyhow::Error>(())
 3190                    });
 3191                }
 3192            }
 3193
 3194            let save_result = this
 3195                .update_in(cx, |this, window, cx| {
 3196                    this.save_all_internal(SaveIntent::Close, window, cx)
 3197                })?
 3198                .await;
 3199
 3200            // If we're not quitting, but closing, we remove the workspace from
 3201            // the current session.
 3202            if close_intent != CloseIntent::Quit
 3203                && !save_last_workspace
 3204                && save_result.as_ref().is_ok_and(|&res| res)
 3205            {
 3206                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 3207                    .await;
 3208            }
 3209
 3210            save_result
 3211        })
 3212    }
 3213
 3214    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 3215        self.save_all_internal(
 3216            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 3217            window,
 3218            cx,
 3219        )
 3220        .detach_and_log_err(cx);
 3221    }
 3222
 3223    fn send_keystrokes(
 3224        &mut self,
 3225        action: &SendKeystrokes,
 3226        window: &mut Window,
 3227        cx: &mut Context<Self>,
 3228    ) {
 3229        let keystrokes: Vec<Keystroke> = action
 3230            .0
 3231            .split(' ')
 3232            .flat_map(|k| Keystroke::parse(k).log_err())
 3233            .map(|k| {
 3234                cx.keyboard_mapper()
 3235                    .map_key_equivalent(k, false)
 3236                    .inner()
 3237                    .clone()
 3238            })
 3239            .collect();
 3240        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 3241    }
 3242
 3243    pub fn send_keystrokes_impl(
 3244        &mut self,
 3245        keystrokes: Vec<Keystroke>,
 3246        window: &mut Window,
 3247        cx: &mut Context<Self>,
 3248    ) -> Shared<Task<()>> {
 3249        let mut state = self.dispatching_keystrokes.borrow_mut();
 3250        if !state.dispatched.insert(keystrokes.clone()) {
 3251            cx.propagate();
 3252            return state.task.clone().unwrap();
 3253        }
 3254
 3255        state.queue.extend(keystrokes);
 3256
 3257        let keystrokes = self.dispatching_keystrokes.clone();
 3258        if state.task.is_none() {
 3259            state.task = Some(
 3260                window
 3261                    .spawn(cx, async move |cx| {
 3262                        // limit to 100 keystrokes to avoid infinite recursion.
 3263                        for _ in 0..100 {
 3264                            let keystroke = {
 3265                                let mut state = keystrokes.borrow_mut();
 3266                                let Some(keystroke) = state.queue.pop_front() else {
 3267                                    state.dispatched.clear();
 3268                                    state.task.take();
 3269                                    return;
 3270                                };
 3271                                keystroke
 3272                            };
 3273                            cx.update(|window, cx| {
 3274                                let focused = window.focused(cx);
 3275                                window.dispatch_keystroke(keystroke.clone(), cx);
 3276                                if window.focused(cx) != focused {
 3277                                    // dispatch_keystroke may cause the focus to change.
 3278                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3279                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 3280                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 3281                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3282                                    // )
 3283                                    window.draw(cx).clear();
 3284                                }
 3285                            })
 3286                            .ok();
 3287
 3288                            // Yield between synthetic keystrokes so deferred focus and
 3289                            // other effects can settle before dispatching the next key.
 3290                            yield_now().await;
 3291                        }
 3292
 3293                        *keystrokes.borrow_mut() = Default::default();
 3294                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3295                    })
 3296                    .shared(),
 3297            );
 3298        }
 3299        state.task.clone().unwrap()
 3300    }
 3301
 3302    /// Prompts the user to save or discard each dirty item, returning
 3303    /// `true` if they confirmed (saved/discarded everything) or `false`
 3304    /// if they cancelled. Used before removing worktree roots during
 3305    /// thread archival.
 3306    pub fn prompt_to_save_or_discard_dirty_items(
 3307        &mut self,
 3308        window: &mut Window,
 3309        cx: &mut Context<Self>,
 3310    ) -> Task<Result<bool>> {
 3311        self.save_all_internal(SaveIntent::Close, window, cx)
 3312    }
 3313
 3314    fn save_all_internal(
 3315        &mut self,
 3316        mut save_intent: SaveIntent,
 3317        window: &mut Window,
 3318        cx: &mut Context<Self>,
 3319    ) -> Task<Result<bool>> {
 3320        if self.project.read(cx).is_disconnected(cx) {
 3321            return Task::ready(Ok(true));
 3322        }
 3323        let dirty_items = self
 3324            .panes
 3325            .iter()
 3326            .flat_map(|pane| {
 3327                pane.read(cx).items().filter_map(|item| {
 3328                    if item.is_dirty(cx) {
 3329                        item.tab_content_text(0, cx);
 3330                        Some((pane.downgrade(), item.boxed_clone()))
 3331                    } else {
 3332                        None
 3333                    }
 3334                })
 3335            })
 3336            .collect::<Vec<_>>();
 3337
 3338        let project = self.project.clone();
 3339        cx.spawn_in(window, async move |workspace, cx| {
 3340            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3341                let (serialize_tasks, remaining_dirty_items) =
 3342                    workspace.update_in(cx, |workspace, window, cx| {
 3343                        let mut remaining_dirty_items = Vec::new();
 3344                        let mut serialize_tasks = Vec::new();
 3345                        for (pane, item) in dirty_items {
 3346                            if let Some(task) = item
 3347                                .to_serializable_item_handle(cx)
 3348                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3349                            {
 3350                                serialize_tasks.push(task);
 3351                            } else {
 3352                                remaining_dirty_items.push((pane, item));
 3353                            }
 3354                        }
 3355                        (serialize_tasks, remaining_dirty_items)
 3356                    })?;
 3357
 3358                futures::future::try_join_all(serialize_tasks).await?;
 3359
 3360                if !remaining_dirty_items.is_empty() {
 3361                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3362                }
 3363
 3364                if remaining_dirty_items.len() > 1 {
 3365                    let answer = workspace.update_in(cx, |_, window, cx| {
 3366                        cx.emit(Event::Activate);
 3367                        let detail = Pane::file_names_for_prompt(
 3368                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3369                            cx,
 3370                        );
 3371                        window.prompt(
 3372                            PromptLevel::Warning,
 3373                            "Do you want to save all changes in the following files?",
 3374                            Some(&detail),
 3375                            &["Save all", "Discard all", "Cancel"],
 3376                            cx,
 3377                        )
 3378                    })?;
 3379                    match answer.await.log_err() {
 3380                        Some(0) => save_intent = SaveIntent::SaveAll,
 3381                        Some(1) => save_intent = SaveIntent::Skip,
 3382                        Some(2) => return Ok(false),
 3383                        _ => {}
 3384                    }
 3385                }
 3386
 3387                remaining_dirty_items
 3388            } else {
 3389                dirty_items
 3390            };
 3391
 3392            for (pane, item) in dirty_items {
 3393                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3394                    (
 3395                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3396                        item.project_entry_ids(cx),
 3397                    )
 3398                })?;
 3399                if (singleton || !project_entry_ids.is_empty())
 3400                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3401                {
 3402                    return Ok(false);
 3403                }
 3404            }
 3405            Ok(true)
 3406        })
 3407    }
 3408
 3409    pub fn open_workspace_for_paths(
 3410        &mut self,
 3411        // replace_current_window: bool,
 3412        mut open_mode: OpenMode,
 3413        paths: Vec<PathBuf>,
 3414        window: &mut Window,
 3415        cx: &mut Context<Self>,
 3416    ) -> Task<Result<Entity<Workspace>>> {
 3417        let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
 3418        let is_remote = self.project.read(cx).is_via_collab();
 3419        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3420        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3421
 3422        let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
 3423        if workspace_is_empty {
 3424            open_mode = OpenMode::Activate;
 3425        }
 3426
 3427        let app_state = self.app_state.clone();
 3428
 3429        cx.spawn(async move |_, cx| {
 3430            let OpenResult { workspace, .. } = cx
 3431                .update(|cx| {
 3432                    open_paths(
 3433                        &paths,
 3434                        app_state,
 3435                        OpenOptions {
 3436                            requesting_window,
 3437                            open_mode,
 3438                            ..Default::default()
 3439                        },
 3440                        cx,
 3441                    )
 3442                })
 3443                .await?;
 3444            Ok(workspace)
 3445        })
 3446    }
 3447
 3448    #[allow(clippy::type_complexity)]
 3449    pub fn open_paths(
 3450        &mut self,
 3451        mut abs_paths: Vec<PathBuf>,
 3452        options: OpenOptions,
 3453        pane: Option<WeakEntity<Pane>>,
 3454        window: &mut Window,
 3455        cx: &mut Context<Self>,
 3456    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3457        let fs = self.app_state.fs.clone();
 3458
 3459        let caller_ordered_abs_paths = abs_paths.clone();
 3460
 3461        // Sort the paths to ensure we add worktrees for parents before their children.
 3462        abs_paths.sort_unstable();
 3463        cx.spawn_in(window, async move |this, cx| {
 3464            let mut tasks = Vec::with_capacity(abs_paths.len());
 3465
 3466            for abs_path in &abs_paths {
 3467                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3468                    OpenVisible::All => Some(true),
 3469                    OpenVisible::None => Some(false),
 3470                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3471                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3472                        Some(None) => Some(true),
 3473                        None => None,
 3474                    },
 3475                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3476                        Some(Some(metadata)) => Some(metadata.is_dir),
 3477                        Some(None) => Some(false),
 3478                        None => None,
 3479                    },
 3480                };
 3481                let project_path = match visible {
 3482                    Some(visible) => match this
 3483                        .update(cx, |this, cx| {
 3484                            Workspace::project_path_for_path(
 3485                                this.project.clone(),
 3486                                abs_path,
 3487                                visible,
 3488                                cx,
 3489                            )
 3490                        })
 3491                        .log_err()
 3492                    {
 3493                        Some(project_path) => project_path.await.log_err(),
 3494                        None => None,
 3495                    },
 3496                    None => None,
 3497                };
 3498
 3499                let this = this.clone();
 3500                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3501                let fs = fs.clone();
 3502                let pane = pane.clone();
 3503                let task = cx.spawn(async move |cx| {
 3504                    let (_worktree, project_path) = project_path?;
 3505                    if fs.is_dir(&abs_path).await {
 3506                        // Opening a directory should not race to update the active entry.
 3507                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3508                        None
 3509                    } else {
 3510                        Some(
 3511                            this.update_in(cx, |this, window, cx| {
 3512                                this.open_path(
 3513                                    project_path,
 3514                                    pane,
 3515                                    options.focus.unwrap_or(true),
 3516                                    window,
 3517                                    cx,
 3518                                )
 3519                            })
 3520                            .ok()?
 3521                            .await,
 3522                        )
 3523                    }
 3524                });
 3525                tasks.push(task);
 3526            }
 3527
 3528            let results = futures::future::join_all(tasks).await;
 3529
 3530            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3531            let mut winner: Option<(PathBuf, bool)> = None;
 3532            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3533                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3534                    if !metadata.is_dir {
 3535                        winner = Some((abs_path, false));
 3536                        break;
 3537                    }
 3538                    if winner.is_none() {
 3539                        winner = Some((abs_path, true));
 3540                    }
 3541                } else if winner.is_none() {
 3542                    winner = Some((abs_path, false));
 3543                }
 3544            }
 3545
 3546            // Compute the winner entry id on the foreground thread and emit once, after all
 3547            // paths finish opening. This avoids races between concurrently-opening paths
 3548            // (directories in particular) and makes the resulting project panel selection
 3549            // deterministic.
 3550            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3551                'emit_winner: {
 3552                    let winner_abs_path: Arc<Path> =
 3553                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3554
 3555                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3556                        OpenVisible::All => true,
 3557                        OpenVisible::None => false,
 3558                        OpenVisible::OnlyFiles => !winner_is_dir,
 3559                        OpenVisible::OnlyDirectories => winner_is_dir,
 3560                    };
 3561
 3562                    let Some(worktree_task) = this
 3563                        .update(cx, |workspace, cx| {
 3564                            workspace.project.update(cx, |project, cx| {
 3565                                project.find_or_create_worktree(
 3566                                    winner_abs_path.as_ref(),
 3567                                    visible,
 3568                                    cx,
 3569                                )
 3570                            })
 3571                        })
 3572                        .ok()
 3573                    else {
 3574                        break 'emit_winner;
 3575                    };
 3576
 3577                    let Ok((worktree, _)) = worktree_task.await else {
 3578                        break 'emit_winner;
 3579                    };
 3580
 3581                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3582                        let worktree = worktree.read(cx);
 3583                        let worktree_abs_path = worktree.abs_path();
 3584                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3585                            worktree.root_entry()
 3586                        } else {
 3587                            winner_abs_path
 3588                                .strip_prefix(worktree_abs_path.as_ref())
 3589                                .ok()
 3590                                .and_then(|relative_path| {
 3591                                    let relative_path =
 3592                                        RelPath::new(relative_path, PathStyle::local())
 3593                                            .log_err()?;
 3594                                    worktree.entry_for_path(&relative_path)
 3595                                })
 3596                        }?;
 3597                        Some(entry.id)
 3598                    }) else {
 3599                        break 'emit_winner;
 3600                    };
 3601
 3602                    this.update(cx, |workspace, cx| {
 3603                        workspace.project.update(cx, |_, cx| {
 3604                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3605                        });
 3606                    })
 3607                    .ok();
 3608                }
 3609            }
 3610
 3611            results
 3612        })
 3613    }
 3614
 3615    pub fn open_resolved_path(
 3616        &mut self,
 3617        path: ResolvedPath,
 3618        window: &mut Window,
 3619        cx: &mut Context<Self>,
 3620    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3621        match path {
 3622            ResolvedPath::ProjectPath { project_path, .. } => {
 3623                self.open_path(project_path, None, true, window, cx)
 3624            }
 3625            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3626                PathBuf::from(path),
 3627                OpenOptions {
 3628                    visible: Some(OpenVisible::None),
 3629                    ..Default::default()
 3630                },
 3631                window,
 3632                cx,
 3633            ),
 3634        }
 3635    }
 3636
 3637    pub fn absolute_path_of_worktree(
 3638        &self,
 3639        worktree_id: WorktreeId,
 3640        cx: &mut Context<Self>,
 3641    ) -> Option<PathBuf> {
 3642        self.project
 3643            .read(cx)
 3644            .worktree_for_id(worktree_id, cx)
 3645            // TODO: use `abs_path` or `root_dir`
 3646            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3647    }
 3648
 3649    pub fn add_folder_to_project(
 3650        &mut self,
 3651        _: &AddFolderToProject,
 3652        window: &mut Window,
 3653        cx: &mut Context<Self>,
 3654    ) {
 3655        let project = self.project.read(cx);
 3656        if project.is_via_collab() {
 3657            self.show_error(
 3658                &anyhow!("You cannot add folders to someone else's project"),
 3659                cx,
 3660            );
 3661            return;
 3662        }
 3663        let paths = self.prompt_for_open_path(
 3664            PathPromptOptions {
 3665                files: false,
 3666                directories: true,
 3667                multiple: true,
 3668                prompt: None,
 3669            },
 3670            DirectoryLister::Project(self.project.clone()),
 3671            window,
 3672            cx,
 3673        );
 3674        cx.spawn_in(window, async move |this, cx| {
 3675            if let Some(paths) = paths.await.log_err().flatten() {
 3676                let results = this
 3677                    .update_in(cx, |this, window, cx| {
 3678                        this.open_paths(
 3679                            paths,
 3680                            OpenOptions {
 3681                                visible: Some(OpenVisible::All),
 3682                                ..Default::default()
 3683                            },
 3684                            None,
 3685                            window,
 3686                            cx,
 3687                        )
 3688                    })?
 3689                    .await;
 3690                for result in results.into_iter().flatten() {
 3691                    result.log_err();
 3692                }
 3693            }
 3694            anyhow::Ok(())
 3695        })
 3696        .detach_and_log_err(cx);
 3697    }
 3698
 3699    pub fn project_path_for_path(
 3700        project: Entity<Project>,
 3701        abs_path: &Path,
 3702        visible: bool,
 3703        cx: &mut App,
 3704    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3705        let entry = project.update(cx, |project, cx| {
 3706            project.find_or_create_worktree(abs_path, visible, cx)
 3707        });
 3708        cx.spawn(async move |cx| {
 3709            let (worktree, path) = entry.await?;
 3710            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3711            Ok((worktree, ProjectPath { worktree_id, path }))
 3712        })
 3713    }
 3714
 3715    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3716        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3717    }
 3718
 3719    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3720        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3721    }
 3722
 3723    pub fn items_of_type<'a, T: Item>(
 3724        &'a self,
 3725        cx: &'a App,
 3726    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3727        self.panes
 3728            .iter()
 3729            .flat_map(|pane| pane.read(cx).items_of_type())
 3730    }
 3731
 3732    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3733        self.active_pane().read(cx).active_item()
 3734    }
 3735
 3736    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3737        let item = self.active_item(cx)?;
 3738        item.to_any_view().downcast::<I>().ok()
 3739    }
 3740
 3741    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3742        self.active_item(cx).and_then(|item| item.project_path(cx))
 3743    }
 3744
 3745    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3746        self.recent_navigation_history_iter(cx)
 3747            .filter_map(|(path, abs_path)| {
 3748                let worktree = self
 3749                    .project
 3750                    .read(cx)
 3751                    .worktree_for_id(path.worktree_id, cx)?;
 3752                if worktree.read(cx).is_visible() {
 3753                    abs_path
 3754                } else {
 3755                    None
 3756                }
 3757            })
 3758            .next()
 3759    }
 3760
 3761    pub fn save_active_item(
 3762        &mut self,
 3763        save_intent: SaveIntent,
 3764        window: &mut Window,
 3765        cx: &mut App,
 3766    ) -> Task<Result<()>> {
 3767        let project = self.project.clone();
 3768        let pane = self.active_pane();
 3769        let item = pane.read(cx).active_item();
 3770        let pane = pane.downgrade();
 3771
 3772        window.spawn(cx, async move |cx| {
 3773            if let Some(item) = item {
 3774                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3775                    .await
 3776                    .map(|_| ())
 3777            } else {
 3778                Ok(())
 3779            }
 3780        })
 3781    }
 3782
 3783    pub fn close_inactive_items_and_panes(
 3784        &mut self,
 3785        action: &CloseInactiveTabsAndPanes,
 3786        window: &mut Window,
 3787        cx: &mut Context<Self>,
 3788    ) {
 3789        if let Some(task) = self.close_all_internal(
 3790            true,
 3791            action.save_intent.unwrap_or(SaveIntent::Close),
 3792            window,
 3793            cx,
 3794        ) {
 3795            task.detach_and_log_err(cx)
 3796        }
 3797    }
 3798
 3799    pub fn close_all_items_and_panes(
 3800        &mut self,
 3801        action: &CloseAllItemsAndPanes,
 3802        window: &mut Window,
 3803        cx: &mut Context<Self>,
 3804    ) {
 3805        if let Some(task) = self.close_all_internal(
 3806            false,
 3807            action.save_intent.unwrap_or(SaveIntent::Close),
 3808            window,
 3809            cx,
 3810        ) {
 3811            task.detach_and_log_err(cx)
 3812        }
 3813    }
 3814
 3815    /// Closes the active item across all panes.
 3816    pub fn close_item_in_all_panes(
 3817        &mut self,
 3818        action: &CloseItemInAllPanes,
 3819        window: &mut Window,
 3820        cx: &mut Context<Self>,
 3821    ) {
 3822        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3823            return;
 3824        };
 3825
 3826        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3827        let close_pinned = action.close_pinned;
 3828
 3829        if let Some(project_path) = active_item.project_path(cx) {
 3830            self.close_items_with_project_path(
 3831                &project_path,
 3832                save_intent,
 3833                close_pinned,
 3834                window,
 3835                cx,
 3836            );
 3837        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3838            let item_id = active_item.item_id();
 3839            self.active_pane().update(cx, |pane, cx| {
 3840                pane.close_item_by_id(item_id, save_intent, window, cx)
 3841                    .detach_and_log_err(cx);
 3842            });
 3843        }
 3844    }
 3845
 3846    /// Closes all items with the given project path across all panes.
 3847    pub fn close_items_with_project_path(
 3848        &mut self,
 3849        project_path: &ProjectPath,
 3850        save_intent: SaveIntent,
 3851        close_pinned: bool,
 3852        window: &mut Window,
 3853        cx: &mut Context<Self>,
 3854    ) {
 3855        let panes = self.panes().to_vec();
 3856        for pane in panes {
 3857            pane.update(cx, |pane, cx| {
 3858                pane.close_items_for_project_path(
 3859                    project_path,
 3860                    save_intent,
 3861                    close_pinned,
 3862                    window,
 3863                    cx,
 3864                )
 3865                .detach_and_log_err(cx);
 3866            });
 3867        }
 3868    }
 3869
 3870    fn close_all_internal(
 3871        &mut self,
 3872        retain_active_pane: bool,
 3873        save_intent: SaveIntent,
 3874        window: &mut Window,
 3875        cx: &mut Context<Self>,
 3876    ) -> Option<Task<Result<()>>> {
 3877        let current_pane = self.active_pane();
 3878
 3879        let mut tasks = Vec::new();
 3880
 3881        if retain_active_pane {
 3882            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3883                pane.close_other_items(
 3884                    &CloseOtherItems {
 3885                        save_intent: None,
 3886                        close_pinned: false,
 3887                    },
 3888                    None,
 3889                    window,
 3890                    cx,
 3891                )
 3892            });
 3893
 3894            tasks.push(current_pane_close);
 3895        }
 3896
 3897        for pane in self.panes() {
 3898            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3899                continue;
 3900            }
 3901
 3902            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3903                pane.close_all_items(
 3904                    &CloseAllItems {
 3905                        save_intent: Some(save_intent),
 3906                        close_pinned: false,
 3907                    },
 3908                    window,
 3909                    cx,
 3910                )
 3911            });
 3912
 3913            tasks.push(close_pane_items)
 3914        }
 3915
 3916        if tasks.is_empty() {
 3917            None
 3918        } else {
 3919            Some(cx.spawn_in(window, async move |_, _| {
 3920                for task in tasks {
 3921                    task.await?
 3922                }
 3923                Ok(())
 3924            }))
 3925        }
 3926    }
 3927
 3928    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3929        self.dock_at_position(position).read(cx).is_open()
 3930    }
 3931
 3932    pub fn toggle_dock(
 3933        &mut self,
 3934        dock_side: DockPosition,
 3935        window: &mut Window,
 3936        cx: &mut Context<Self>,
 3937    ) {
 3938        let mut focus_center = false;
 3939        let mut reveal_dock = false;
 3940
 3941        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3942        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3943
 3944        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3945            telemetry::event!(
 3946                "Panel Button Clicked",
 3947                name = panel.persistent_name(),
 3948                toggle_state = !was_visible
 3949            );
 3950        }
 3951        if was_visible {
 3952            self.save_open_dock_positions(cx);
 3953        }
 3954
 3955        let dock = self.dock_at_position(dock_side);
 3956        dock.update(cx, |dock, cx| {
 3957            dock.set_open(!was_visible, window, cx);
 3958
 3959            if dock.active_panel().is_none() {
 3960                let Some(panel_ix) = dock
 3961                    .first_enabled_panel_idx(cx)
 3962                    .log_with_level(log::Level::Info)
 3963                else {
 3964                    return;
 3965                };
 3966                dock.activate_panel(panel_ix, window, cx);
 3967            }
 3968
 3969            if let Some(active_panel) = dock.active_panel() {
 3970                if was_visible {
 3971                    if active_panel
 3972                        .panel_focus_handle(cx)
 3973                        .contains_focused(window, cx)
 3974                    {
 3975                        focus_center = true;
 3976                    }
 3977                } else {
 3978                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3979                    window.focus(focus_handle, cx);
 3980                    reveal_dock = true;
 3981                }
 3982            }
 3983        });
 3984
 3985        if reveal_dock {
 3986            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3987        }
 3988
 3989        if focus_center {
 3990            self.active_pane
 3991                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3992        }
 3993
 3994        cx.notify();
 3995        self.serialize_workspace(window, cx);
 3996    }
 3997
 3998    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3999        self.all_docks().into_iter().find(|&dock| {
 4000            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 4001        })
 4002    }
 4003
 4004    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 4005        if let Some(dock) = self.active_dock(window, cx).cloned() {
 4006            self.save_open_dock_positions(cx);
 4007            dock.update(cx, |dock, cx| {
 4008                dock.set_open(false, window, cx);
 4009            });
 4010            return true;
 4011        }
 4012        false
 4013    }
 4014
 4015    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4016        self.save_open_dock_positions(cx);
 4017        for dock in self.all_docks() {
 4018            dock.update(cx, |dock, cx| {
 4019                dock.set_open(false, window, cx);
 4020            });
 4021        }
 4022
 4023        cx.focus_self(window);
 4024        cx.notify();
 4025        self.serialize_workspace(window, cx);
 4026    }
 4027
 4028    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 4029        self.all_docks()
 4030            .into_iter()
 4031            .filter_map(|dock| {
 4032                let dock_ref = dock.read(cx);
 4033                if dock_ref.is_open() {
 4034                    Some(dock_ref.position())
 4035                } else {
 4036                    None
 4037                }
 4038            })
 4039            .collect()
 4040    }
 4041
 4042    /// Saves the positions of currently open docks.
 4043    ///
 4044    /// Updates `last_open_dock_positions` with positions of all currently open
 4045    /// docks, to later be restored by the 'Toggle All Docks' action.
 4046    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 4047        let open_dock_positions = self.get_open_dock_positions(cx);
 4048        if !open_dock_positions.is_empty() {
 4049            self.last_open_dock_positions = open_dock_positions;
 4050        }
 4051    }
 4052
 4053    /// Toggles all docks between open and closed states.
 4054    ///
 4055    /// If any docks are open, closes all and remembers their positions. If all
 4056    /// docks are closed, restores the last remembered dock configuration.
 4057    fn toggle_all_docks(
 4058        &mut self,
 4059        _: &ToggleAllDocks,
 4060        window: &mut Window,
 4061        cx: &mut Context<Self>,
 4062    ) {
 4063        let open_dock_positions = self.get_open_dock_positions(cx);
 4064
 4065        if !open_dock_positions.is_empty() {
 4066            self.close_all_docks(window, cx);
 4067        } else if !self.last_open_dock_positions.is_empty() {
 4068            self.restore_last_open_docks(window, cx);
 4069        }
 4070    }
 4071
 4072    /// Reopens docks from the most recently remembered configuration.
 4073    ///
 4074    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 4075    /// and clears the stored positions.
 4076    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4077        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 4078
 4079        for position in positions_to_open {
 4080            let dock = self.dock_at_position(position);
 4081            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 4082        }
 4083
 4084        cx.focus_self(window);
 4085        cx.notify();
 4086        self.serialize_workspace(window, cx);
 4087    }
 4088
 4089    /// Transfer focus to the panel of the given type.
 4090    pub fn focus_panel<T: Panel>(
 4091        &mut self,
 4092        window: &mut Window,
 4093        cx: &mut Context<Self>,
 4094    ) -> Option<Entity<T>> {
 4095        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 4096        panel.to_any().downcast().ok()
 4097    }
 4098
 4099    /// Focus the panel of the given type if it isn't already focused. If it is
 4100    /// already focused, then transfer focus back to the workspace center.
 4101    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 4102    /// panel when transferring focus back to the center.
 4103    pub fn toggle_panel_focus<T: Panel>(
 4104        &mut self,
 4105        window: &mut Window,
 4106        cx: &mut Context<Self>,
 4107    ) -> bool {
 4108        let mut did_focus_panel = false;
 4109        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 4110            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 4111            did_focus_panel
 4112        });
 4113
 4114        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 4115            self.close_panel::<T>(window, cx);
 4116        }
 4117
 4118        telemetry::event!(
 4119            "Panel Button Clicked",
 4120            name = T::persistent_name(),
 4121            toggle_state = did_focus_panel
 4122        );
 4123
 4124        did_focus_panel
 4125    }
 4126
 4127    pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4128        if let Some(item) = self.active_item(cx) {
 4129            item.item_focus_handle(cx).focus(window, cx);
 4130        } else {
 4131            log::error!("Could not find a focus target when switching focus to the center panes",);
 4132        }
 4133    }
 4134
 4135    pub fn activate_panel_for_proto_id(
 4136        &mut self,
 4137        panel_id: PanelId,
 4138        window: &mut Window,
 4139        cx: &mut Context<Self>,
 4140    ) -> Option<Arc<dyn PanelHandle>> {
 4141        let mut panel = None;
 4142        for dock in self.all_docks() {
 4143            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 4144                panel = dock.update(cx, |dock, cx| {
 4145                    dock.activate_panel(panel_index, window, cx);
 4146                    dock.set_open(true, window, cx);
 4147                    dock.active_panel().cloned()
 4148                });
 4149                break;
 4150            }
 4151        }
 4152
 4153        if panel.is_some() {
 4154            cx.notify();
 4155            self.serialize_workspace(window, cx);
 4156        }
 4157
 4158        panel
 4159    }
 4160
 4161    /// Focus or unfocus the given panel type, depending on the given callback.
 4162    fn focus_or_unfocus_panel<T: Panel>(
 4163        &mut self,
 4164        window: &mut Window,
 4165        cx: &mut Context<Self>,
 4166        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 4167    ) -> Option<Arc<dyn PanelHandle>> {
 4168        let mut result_panel = None;
 4169        let mut serialize = false;
 4170        for dock in self.all_docks() {
 4171            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4172                let mut focus_center = false;
 4173                let panel = dock.update(cx, |dock, cx| {
 4174                    dock.activate_panel(panel_index, window, cx);
 4175
 4176                    let panel = dock.active_panel().cloned();
 4177                    if let Some(panel) = panel.as_ref() {
 4178                        if should_focus(&**panel, window, cx) {
 4179                            dock.set_open(true, window, cx);
 4180                            panel.panel_focus_handle(cx).focus(window, cx);
 4181                        } else {
 4182                            focus_center = true;
 4183                        }
 4184                    }
 4185                    panel
 4186                });
 4187
 4188                if focus_center {
 4189                    self.active_pane
 4190                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4191                }
 4192
 4193                result_panel = panel;
 4194                serialize = true;
 4195                break;
 4196            }
 4197        }
 4198
 4199        if serialize {
 4200            self.serialize_workspace(window, cx);
 4201        }
 4202
 4203        cx.notify();
 4204        result_panel
 4205    }
 4206
 4207    /// Open the panel of the given type
 4208    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4209        for dock in self.all_docks() {
 4210            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4211                dock.update(cx, |dock, cx| {
 4212                    dock.activate_panel(panel_index, window, cx);
 4213                    dock.set_open(true, window, cx);
 4214                });
 4215            }
 4216        }
 4217    }
 4218
 4219    /// Open the panel of the given type, dismissing any zoomed items that
 4220    /// would obscure it (e.g. a zoomed terminal).
 4221    pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4222        let dock_position = self.all_docks().iter().find_map(|dock| {
 4223            let dock = dock.read(cx);
 4224            dock.panel_index_for_type::<T>().map(|_| dock.position())
 4225        });
 4226        self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
 4227        self.open_panel::<T>(window, cx);
 4228    }
 4229
 4230    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 4231        for dock in self.all_docks().iter() {
 4232            dock.update(cx, |dock, cx| {
 4233                if dock.panel::<T>().is_some() {
 4234                    dock.set_open(false, window, cx)
 4235                }
 4236            })
 4237        }
 4238    }
 4239
 4240    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 4241        self.all_docks()
 4242            .iter()
 4243            .find_map(|dock| dock.read(cx).panel::<T>())
 4244    }
 4245
 4246    fn dismiss_zoomed_items_to_reveal(
 4247        &mut self,
 4248        dock_to_reveal: Option<DockPosition>,
 4249        window: &mut Window,
 4250        cx: &mut Context<Self>,
 4251    ) {
 4252        // If a center pane is zoomed, unzoom it.
 4253        for pane in &self.panes {
 4254            if pane != &self.active_pane || dock_to_reveal.is_some() {
 4255                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4256            }
 4257        }
 4258
 4259        // If another dock is zoomed, hide it.
 4260        let mut focus_center = false;
 4261        for dock in self.all_docks() {
 4262            dock.update(cx, |dock, cx| {
 4263                if Some(dock.position()) != dock_to_reveal
 4264                    && let Some(panel) = dock.active_panel()
 4265                    && panel.is_zoomed(window, cx)
 4266                {
 4267                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 4268                    dock.set_open(false, window, cx);
 4269                }
 4270            });
 4271        }
 4272
 4273        if focus_center {
 4274            self.active_pane
 4275                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4276        }
 4277
 4278        if self.zoomed_position != dock_to_reveal {
 4279            self.zoomed = None;
 4280            self.zoomed_position = None;
 4281            cx.emit(Event::ZoomChanged);
 4282        }
 4283
 4284        cx.notify();
 4285    }
 4286
 4287    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4288        let pane = cx.new(|cx| {
 4289            let mut pane = Pane::new(
 4290                self.weak_handle(),
 4291                self.project.clone(),
 4292                self.pane_history_timestamp.clone(),
 4293                None,
 4294                NewFile.boxed_clone(),
 4295                true,
 4296                window,
 4297                cx,
 4298            );
 4299            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4300            pane
 4301        });
 4302        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4303            .detach();
 4304        self.panes.push(pane.clone());
 4305
 4306        window.focus(&pane.focus_handle(cx), cx);
 4307
 4308        cx.emit(Event::PaneAdded(pane.clone()));
 4309        pane
 4310    }
 4311
 4312    pub fn add_item_to_center(
 4313        &mut self,
 4314        item: Box<dyn ItemHandle>,
 4315        window: &mut Window,
 4316        cx: &mut Context<Self>,
 4317    ) -> bool {
 4318        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4319            if let Some(center_pane) = center_pane.upgrade() {
 4320                center_pane.update(cx, |pane, cx| {
 4321                    pane.add_item(item, true, true, None, window, cx)
 4322                });
 4323                true
 4324            } else {
 4325                false
 4326            }
 4327        } else {
 4328            false
 4329        }
 4330    }
 4331
 4332    pub fn add_item_to_active_pane(
 4333        &mut self,
 4334        item: Box<dyn ItemHandle>,
 4335        destination_index: Option<usize>,
 4336        focus_item: bool,
 4337        window: &mut Window,
 4338        cx: &mut App,
 4339    ) {
 4340        self.add_item(
 4341            self.active_pane.clone(),
 4342            item,
 4343            destination_index,
 4344            false,
 4345            focus_item,
 4346            window,
 4347            cx,
 4348        )
 4349    }
 4350
 4351    pub fn add_item(
 4352        &mut self,
 4353        pane: Entity<Pane>,
 4354        item: Box<dyn ItemHandle>,
 4355        destination_index: Option<usize>,
 4356        activate_pane: bool,
 4357        focus_item: bool,
 4358        window: &mut Window,
 4359        cx: &mut App,
 4360    ) {
 4361        pane.update(cx, |pane, cx| {
 4362            pane.add_item(
 4363                item,
 4364                activate_pane,
 4365                focus_item,
 4366                destination_index,
 4367                window,
 4368                cx,
 4369            )
 4370        });
 4371    }
 4372
 4373    pub fn split_item(
 4374        &mut self,
 4375        split_direction: SplitDirection,
 4376        item: Box<dyn ItemHandle>,
 4377        window: &mut Window,
 4378        cx: &mut Context<Self>,
 4379    ) {
 4380        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4381        self.add_item(new_pane, item, None, true, true, window, cx);
 4382    }
 4383
 4384    pub fn open_abs_path(
 4385        &mut self,
 4386        abs_path: PathBuf,
 4387        options: OpenOptions,
 4388        window: &mut Window,
 4389        cx: &mut Context<Self>,
 4390    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4391        cx.spawn_in(window, async move |workspace, cx| {
 4392            let open_paths_task_result = workspace
 4393                .update_in(cx, |workspace, window, cx| {
 4394                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4395                })
 4396                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4397                .await;
 4398            anyhow::ensure!(
 4399                open_paths_task_result.len() == 1,
 4400                "open abs path {abs_path:?} task returned incorrect number of results"
 4401            );
 4402            match open_paths_task_result
 4403                .into_iter()
 4404                .next()
 4405                .expect("ensured single task result")
 4406            {
 4407                Some(open_result) => {
 4408                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4409                }
 4410                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4411            }
 4412        })
 4413    }
 4414
 4415    pub fn split_abs_path(
 4416        &mut self,
 4417        abs_path: PathBuf,
 4418        visible: bool,
 4419        window: &mut Window,
 4420        cx: &mut Context<Self>,
 4421    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4422        let project_path_task =
 4423            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4424        cx.spawn_in(window, async move |this, cx| {
 4425            let (_, path) = project_path_task.await?;
 4426            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4427                .await
 4428        })
 4429    }
 4430
 4431    pub fn open_path(
 4432        &mut self,
 4433        path: impl Into<ProjectPath>,
 4434        pane: Option<WeakEntity<Pane>>,
 4435        focus_item: bool,
 4436        window: &mut Window,
 4437        cx: &mut App,
 4438    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4439        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4440    }
 4441
 4442    pub fn open_path_preview(
 4443        &mut self,
 4444        path: impl Into<ProjectPath>,
 4445        pane: Option<WeakEntity<Pane>>,
 4446        focus_item: bool,
 4447        allow_preview: bool,
 4448        activate: bool,
 4449        window: &mut Window,
 4450        cx: &mut App,
 4451    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4452        let pane = pane.unwrap_or_else(|| {
 4453            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4454                self.panes
 4455                    .first()
 4456                    .expect("There must be an active pane")
 4457                    .downgrade()
 4458            })
 4459        });
 4460
 4461        let project_path = path.into();
 4462        let task = self.load_path(project_path.clone(), window, cx);
 4463        window.spawn(cx, async move |cx| {
 4464            let (project_entry_id, build_item) = task.await?;
 4465
 4466            pane.update_in(cx, |pane, window, cx| {
 4467                pane.open_item(
 4468                    project_entry_id,
 4469                    project_path,
 4470                    focus_item,
 4471                    allow_preview,
 4472                    activate,
 4473                    None,
 4474                    window,
 4475                    cx,
 4476                    build_item,
 4477                )
 4478            })
 4479        })
 4480    }
 4481
 4482    pub fn split_path(
 4483        &mut self,
 4484        path: impl Into<ProjectPath>,
 4485        window: &mut Window,
 4486        cx: &mut Context<Self>,
 4487    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4488        self.split_path_preview(path, false, None, window, cx)
 4489    }
 4490
 4491    pub fn split_path_preview(
 4492        &mut self,
 4493        path: impl Into<ProjectPath>,
 4494        allow_preview: bool,
 4495        split_direction: Option<SplitDirection>,
 4496        window: &mut Window,
 4497        cx: &mut Context<Self>,
 4498    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4499        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4500            self.panes
 4501                .first()
 4502                .expect("There must be an active pane")
 4503                .downgrade()
 4504        });
 4505
 4506        if let Member::Pane(center_pane) = &self.center.root
 4507            && center_pane.read(cx).items_len() == 0
 4508        {
 4509            return self.open_path(path, Some(pane), true, window, cx);
 4510        }
 4511
 4512        let project_path = path.into();
 4513        let task = self.load_path(project_path.clone(), window, cx);
 4514        cx.spawn_in(window, async move |this, cx| {
 4515            let (project_entry_id, build_item) = task.await?;
 4516            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4517                let pane = pane.upgrade()?;
 4518                let new_pane = this.split_pane(
 4519                    pane,
 4520                    split_direction.unwrap_or(SplitDirection::Right),
 4521                    window,
 4522                    cx,
 4523                );
 4524                new_pane.update(cx, |new_pane, cx| {
 4525                    Some(new_pane.open_item(
 4526                        project_entry_id,
 4527                        project_path,
 4528                        true,
 4529                        allow_preview,
 4530                        true,
 4531                        None,
 4532                        window,
 4533                        cx,
 4534                        build_item,
 4535                    ))
 4536                })
 4537            })
 4538            .map(|option| option.context("pane was dropped"))?
 4539        })
 4540    }
 4541
 4542    fn load_path(
 4543        &mut self,
 4544        path: ProjectPath,
 4545        window: &mut Window,
 4546        cx: &mut App,
 4547    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4548        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4549        registry.open_path(self.project(), &path, window, cx)
 4550    }
 4551
 4552    pub fn find_project_item<T>(
 4553        &self,
 4554        pane: &Entity<Pane>,
 4555        project_item: &Entity<T::Item>,
 4556        cx: &App,
 4557    ) -> Option<Entity<T>>
 4558    where
 4559        T: ProjectItem,
 4560    {
 4561        use project::ProjectItem as _;
 4562        let project_item = project_item.read(cx);
 4563        let entry_id = project_item.entry_id(cx);
 4564        let project_path = project_item.project_path(cx);
 4565
 4566        let mut item = None;
 4567        if let Some(entry_id) = entry_id {
 4568            item = pane.read(cx).item_for_entry(entry_id, cx);
 4569        }
 4570        if item.is_none()
 4571            && let Some(project_path) = project_path
 4572        {
 4573            item = pane.read(cx).item_for_path(project_path, cx);
 4574        }
 4575
 4576        item.and_then(|item| item.downcast::<T>())
 4577    }
 4578
 4579    pub fn is_project_item_open<T>(
 4580        &self,
 4581        pane: &Entity<Pane>,
 4582        project_item: &Entity<T::Item>,
 4583        cx: &App,
 4584    ) -> bool
 4585    where
 4586        T: ProjectItem,
 4587    {
 4588        self.find_project_item::<T>(pane, project_item, cx)
 4589            .is_some()
 4590    }
 4591
 4592    pub fn open_project_item<T>(
 4593        &mut self,
 4594        pane: Entity<Pane>,
 4595        project_item: Entity<T::Item>,
 4596        activate_pane: bool,
 4597        focus_item: bool,
 4598        keep_old_preview: bool,
 4599        allow_new_preview: bool,
 4600        window: &mut Window,
 4601        cx: &mut Context<Self>,
 4602    ) -> Entity<T>
 4603    where
 4604        T: ProjectItem,
 4605    {
 4606        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4607
 4608        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4609            if !keep_old_preview
 4610                && let Some(old_id) = old_item_id
 4611                && old_id != item.item_id()
 4612            {
 4613                // switching to a different item, so unpreview old active item
 4614                pane.update(cx, |pane, _| {
 4615                    pane.unpreview_item_if_preview(old_id);
 4616                });
 4617            }
 4618
 4619            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4620            if !allow_new_preview {
 4621                pane.update(cx, |pane, _| {
 4622                    pane.unpreview_item_if_preview(item.item_id());
 4623                });
 4624            }
 4625            return item;
 4626        }
 4627
 4628        let item = pane.update(cx, |pane, cx| {
 4629            cx.new(|cx| {
 4630                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4631            })
 4632        });
 4633        let mut destination_index = None;
 4634        pane.update(cx, |pane, cx| {
 4635            if !keep_old_preview && let Some(old_id) = old_item_id {
 4636                pane.unpreview_item_if_preview(old_id);
 4637            }
 4638            if allow_new_preview {
 4639                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4640            }
 4641        });
 4642
 4643        self.add_item(
 4644            pane,
 4645            Box::new(item.clone()),
 4646            destination_index,
 4647            activate_pane,
 4648            focus_item,
 4649            window,
 4650            cx,
 4651        );
 4652        item
 4653    }
 4654
 4655    pub fn open_shared_screen(
 4656        &mut self,
 4657        peer_id: PeerId,
 4658        window: &mut Window,
 4659        cx: &mut Context<Self>,
 4660    ) {
 4661        if let Some(shared_screen) =
 4662            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4663        {
 4664            self.active_pane.update(cx, |pane, cx| {
 4665                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4666            });
 4667        }
 4668    }
 4669
 4670    pub fn activate_item(
 4671        &mut self,
 4672        item: &dyn ItemHandle,
 4673        activate_pane: bool,
 4674        focus_item: bool,
 4675        window: &mut Window,
 4676        cx: &mut App,
 4677    ) -> bool {
 4678        let result = self.panes.iter().find_map(|pane| {
 4679            pane.read(cx)
 4680                .index_for_item(item)
 4681                .map(|ix| (pane.clone(), ix))
 4682        });
 4683        if let Some((pane, ix)) = result {
 4684            pane.update(cx, |pane, cx| {
 4685                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4686            });
 4687            true
 4688        } else {
 4689            false
 4690        }
 4691    }
 4692
 4693    fn activate_pane_at_index(
 4694        &mut self,
 4695        action: &ActivatePane,
 4696        window: &mut Window,
 4697        cx: &mut Context<Self>,
 4698    ) {
 4699        let panes = self.center.panes();
 4700        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4701            window.focus(&pane.focus_handle(cx), cx);
 4702        } else {
 4703            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4704                .detach();
 4705        }
 4706    }
 4707
 4708    fn move_item_to_pane_at_index(
 4709        &mut self,
 4710        action: &MoveItemToPane,
 4711        window: &mut Window,
 4712        cx: &mut Context<Self>,
 4713    ) {
 4714        let panes = self.center.panes();
 4715        let destination = match panes.get(action.destination) {
 4716            Some(&destination) => destination.clone(),
 4717            None => {
 4718                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4719                    return;
 4720                }
 4721                let direction = SplitDirection::Right;
 4722                let split_off_pane = self
 4723                    .find_pane_in_direction(direction, cx)
 4724                    .unwrap_or_else(|| self.active_pane.clone());
 4725                let new_pane = self.add_pane(window, cx);
 4726                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4727                new_pane
 4728            }
 4729        };
 4730
 4731        if action.clone {
 4732            if self
 4733                .active_pane
 4734                .read(cx)
 4735                .active_item()
 4736                .is_some_and(|item| item.can_split(cx))
 4737            {
 4738                clone_active_item(
 4739                    self.database_id(),
 4740                    &self.active_pane,
 4741                    &destination,
 4742                    action.focus,
 4743                    window,
 4744                    cx,
 4745                );
 4746                return;
 4747            }
 4748        }
 4749        move_active_item(
 4750            &self.active_pane,
 4751            &destination,
 4752            action.focus,
 4753            true,
 4754            window,
 4755            cx,
 4756        )
 4757    }
 4758
 4759    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4760        let panes = self.center.panes();
 4761        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4762            let next_ix = (ix + 1) % panes.len();
 4763            let next_pane = panes[next_ix].clone();
 4764            window.focus(&next_pane.focus_handle(cx), cx);
 4765        }
 4766    }
 4767
 4768    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4769        let panes = self.center.panes();
 4770        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4771            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4772            let prev_pane = panes[prev_ix].clone();
 4773            window.focus(&prev_pane.focus_handle(cx), cx);
 4774        }
 4775    }
 4776
 4777    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4778        let last_pane = self.center.last_pane();
 4779        window.focus(&last_pane.focus_handle(cx), cx);
 4780    }
 4781
 4782    pub fn activate_pane_in_direction(
 4783        &mut self,
 4784        direction: SplitDirection,
 4785        window: &mut Window,
 4786        cx: &mut App,
 4787    ) {
 4788        use ActivateInDirectionTarget as Target;
 4789        enum Origin {
 4790            Sidebar,
 4791            LeftDock,
 4792            RightDock,
 4793            BottomDock,
 4794            Center,
 4795        }
 4796
 4797        let origin: Origin = if self
 4798            .sidebar_focus_handle
 4799            .as_ref()
 4800            .is_some_and(|h| h.contains_focused(window, cx))
 4801        {
 4802            Origin::Sidebar
 4803        } else {
 4804            [
 4805                (&self.left_dock, Origin::LeftDock),
 4806                (&self.right_dock, Origin::RightDock),
 4807                (&self.bottom_dock, Origin::BottomDock),
 4808            ]
 4809            .into_iter()
 4810            .find_map(|(dock, origin)| {
 4811                if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4812                    Some(origin)
 4813                } else {
 4814                    None
 4815                }
 4816            })
 4817            .unwrap_or(Origin::Center)
 4818        };
 4819
 4820        let get_last_active_pane = || {
 4821            let pane = self
 4822                .last_active_center_pane
 4823                .clone()
 4824                .unwrap_or_else(|| {
 4825                    self.panes
 4826                        .first()
 4827                        .expect("There must be an active pane")
 4828                        .downgrade()
 4829                })
 4830                .upgrade()?;
 4831            (pane.read(cx).items_len() != 0).then_some(pane)
 4832        };
 4833
 4834        let try_dock =
 4835            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4836
 4837        let sidebar_target = self
 4838            .sidebar_focus_handle
 4839            .as_ref()
 4840            .map(|h| Target::Sidebar(h.clone()));
 4841
 4842        let sidebar_on_right = self
 4843            .multi_workspace
 4844            .as_ref()
 4845            .and_then(|mw| mw.upgrade())
 4846            .map_or(false, |mw| {
 4847                mw.read(cx).sidebar_side(cx) == SidebarSide::Right
 4848            });
 4849
 4850        let away_from_sidebar = if sidebar_on_right {
 4851            SplitDirection::Left
 4852        } else {
 4853            SplitDirection::Right
 4854        };
 4855
 4856        let (near_dock, far_dock) = if sidebar_on_right {
 4857            (&self.right_dock, &self.left_dock)
 4858        } else {
 4859            (&self.left_dock, &self.right_dock)
 4860        };
 4861
 4862        let target = match (origin, direction) {
 4863            (Origin::Sidebar, dir) if dir == away_from_sidebar => try_dock(near_dock)
 4864                .or_else(|| get_last_active_pane().map(Target::Pane))
 4865                .or_else(|| try_dock(&self.bottom_dock))
 4866                .or_else(|| try_dock(far_dock)),
 4867
 4868            (Origin::Sidebar, _) => None,
 4869
 4870            // We're in the center, so we first try to go to a different pane,
 4871            // otherwise try to go to a dock.
 4872            (Origin::Center, direction) => {
 4873                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4874                    Some(Target::Pane(pane))
 4875                } else {
 4876                    match direction {
 4877                        SplitDirection::Up => None,
 4878                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4879                        SplitDirection::Left => {
 4880                            let dock_target = try_dock(&self.left_dock);
 4881                            if sidebar_on_right {
 4882                                dock_target
 4883                            } else {
 4884                                dock_target.or(sidebar_target)
 4885                            }
 4886                        }
 4887                        SplitDirection::Right => {
 4888                            let dock_target = try_dock(&self.right_dock);
 4889                            if sidebar_on_right {
 4890                                dock_target.or(sidebar_target)
 4891                            } else {
 4892                                dock_target
 4893                            }
 4894                        }
 4895                    }
 4896                }
 4897            }
 4898
 4899            (Origin::LeftDock, SplitDirection::Right) => {
 4900                if let Some(last_active_pane) = get_last_active_pane() {
 4901                    Some(Target::Pane(last_active_pane))
 4902                } else {
 4903                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4904                }
 4905            }
 4906
 4907            (Origin::LeftDock, SplitDirection::Left) => {
 4908                if sidebar_on_right {
 4909                    None
 4910                } else {
 4911                    sidebar_target
 4912                }
 4913            }
 4914
 4915            (Origin::LeftDock, SplitDirection::Down)
 4916            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4917
 4918            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4919            (Origin::BottomDock, SplitDirection::Left) => {
 4920                let dock_target = try_dock(&self.left_dock);
 4921                if sidebar_on_right {
 4922                    dock_target
 4923                } else {
 4924                    dock_target.or(sidebar_target)
 4925                }
 4926            }
 4927            (Origin::BottomDock, SplitDirection::Right) => {
 4928                let dock_target = try_dock(&self.right_dock);
 4929                if sidebar_on_right {
 4930                    dock_target.or(sidebar_target)
 4931                } else {
 4932                    dock_target
 4933                }
 4934            }
 4935
 4936            (Origin::RightDock, SplitDirection::Left) => {
 4937                if let Some(last_active_pane) = get_last_active_pane() {
 4938                    Some(Target::Pane(last_active_pane))
 4939                } else {
 4940                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 4941                }
 4942            }
 4943
 4944            (Origin::RightDock, SplitDirection::Right) => {
 4945                if sidebar_on_right {
 4946                    sidebar_target
 4947                } else {
 4948                    None
 4949                }
 4950            }
 4951
 4952            _ => None,
 4953        };
 4954
 4955        match target {
 4956            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4957                let pane = pane.read(cx);
 4958                if let Some(item) = pane.active_item() {
 4959                    item.item_focus_handle(cx).focus(window, cx);
 4960                } else {
 4961                    log::error!(
 4962                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4963                    );
 4964                }
 4965            }
 4966            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4967                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4968                window.defer(cx, move |window, cx| {
 4969                    let dock = dock.read(cx);
 4970                    if let Some(panel) = dock.active_panel() {
 4971                        panel.panel_focus_handle(cx).focus(window, cx);
 4972                    } else {
 4973                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4974                    }
 4975                })
 4976            }
 4977            Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
 4978                focus_handle.focus(window, cx);
 4979            }
 4980            None => {}
 4981        }
 4982    }
 4983
 4984    pub fn move_item_to_pane_in_direction(
 4985        &mut self,
 4986        action: &MoveItemToPaneInDirection,
 4987        window: &mut Window,
 4988        cx: &mut Context<Self>,
 4989    ) {
 4990        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4991            Some(destination) => destination,
 4992            None => {
 4993                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4994                    return;
 4995                }
 4996                let new_pane = self.add_pane(window, cx);
 4997                self.center
 4998                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4999                new_pane
 5000            }
 5001        };
 5002
 5003        if action.clone {
 5004            if self
 5005                .active_pane
 5006                .read(cx)
 5007                .active_item()
 5008                .is_some_and(|item| item.can_split(cx))
 5009            {
 5010                clone_active_item(
 5011                    self.database_id(),
 5012                    &self.active_pane,
 5013                    &destination,
 5014                    action.focus,
 5015                    window,
 5016                    cx,
 5017                );
 5018                return;
 5019            }
 5020        }
 5021        move_active_item(
 5022            &self.active_pane,
 5023            &destination,
 5024            action.focus,
 5025            true,
 5026            window,
 5027            cx,
 5028        );
 5029    }
 5030
 5031    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 5032        self.center.bounding_box_for_pane(pane)
 5033    }
 5034
 5035    pub fn find_pane_in_direction(
 5036        &mut self,
 5037        direction: SplitDirection,
 5038        cx: &App,
 5039    ) -> Option<Entity<Pane>> {
 5040        self.center
 5041            .find_pane_in_direction(&self.active_pane, direction, cx)
 5042            .cloned()
 5043    }
 5044
 5045    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 5046        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 5047            self.center.swap(&self.active_pane, &to, cx);
 5048            cx.notify();
 5049        }
 5050    }
 5051
 5052    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 5053        if self
 5054            .center
 5055            .move_to_border(&self.active_pane, direction, cx)
 5056            .unwrap()
 5057        {
 5058            cx.notify();
 5059        }
 5060    }
 5061
 5062    pub fn resize_pane(
 5063        &mut self,
 5064        axis: gpui::Axis,
 5065        amount: Pixels,
 5066        window: &mut Window,
 5067        cx: &mut Context<Self>,
 5068    ) {
 5069        let docks = self.all_docks();
 5070        let active_dock = docks
 5071            .into_iter()
 5072            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 5073
 5074        if let Some(dock_entity) = active_dock {
 5075            let dock = dock_entity.read(cx);
 5076            let Some(panel_size) = self.dock_size(&dock, window, cx) else {
 5077                return;
 5078            };
 5079            match dock.position() {
 5080                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 5081                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 5082                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 5083            }
 5084        } else {
 5085            self.center
 5086                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 5087        }
 5088        cx.notify();
 5089    }
 5090
 5091    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 5092        self.center.reset_pane_sizes(cx);
 5093        cx.notify();
 5094    }
 5095
 5096    fn handle_pane_focused(
 5097        &mut self,
 5098        pane: Entity<Pane>,
 5099        window: &mut Window,
 5100        cx: &mut Context<Self>,
 5101    ) {
 5102        // This is explicitly hoisted out of the following check for pane identity as
 5103        // terminal panel panes are not registered as a center panes.
 5104        self.status_bar.update(cx, |status_bar, cx| {
 5105            status_bar.set_active_pane(&pane, window, cx);
 5106        });
 5107        if self.active_pane != pane {
 5108            self.set_active_pane(&pane, window, cx);
 5109        }
 5110
 5111        if self.last_active_center_pane.is_none() {
 5112            self.last_active_center_pane = Some(pane.downgrade());
 5113        }
 5114
 5115        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 5116        // This prevents the dock from closing when focus events fire during window activation.
 5117        // We also preserve any dock whose active panel itself has focus — this covers
 5118        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 5119        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 5120            let dock_read = dock.read(cx);
 5121            if let Some(panel) = dock_read.active_panel() {
 5122                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 5123                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 5124                {
 5125                    return Some(dock_read.position());
 5126                }
 5127            }
 5128            None
 5129        });
 5130
 5131        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 5132        if pane.read(cx).is_zoomed() {
 5133            self.zoomed = Some(pane.downgrade().into());
 5134        } else {
 5135            self.zoomed = None;
 5136        }
 5137        self.zoomed_position = None;
 5138        cx.emit(Event::ZoomChanged);
 5139        self.update_active_view_for_followers(window, cx);
 5140        pane.update(cx, |pane, _| {
 5141            pane.track_alternate_file_items();
 5142        });
 5143
 5144        cx.notify();
 5145    }
 5146
 5147    fn set_active_pane(
 5148        &mut self,
 5149        pane: &Entity<Pane>,
 5150        window: &mut Window,
 5151        cx: &mut Context<Self>,
 5152    ) {
 5153        self.active_pane = pane.clone();
 5154        self.active_item_path_changed(true, window, cx);
 5155        self.last_active_center_pane = Some(pane.downgrade());
 5156    }
 5157
 5158    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5159        self.update_active_view_for_followers(window, cx);
 5160    }
 5161
 5162    fn handle_pane_event(
 5163        &mut self,
 5164        pane: &Entity<Pane>,
 5165        event: &pane::Event,
 5166        window: &mut Window,
 5167        cx: &mut Context<Self>,
 5168    ) {
 5169        let mut serialize_workspace = true;
 5170        match event {
 5171            pane::Event::AddItem { item } => {
 5172                item.added_to_pane(self, pane.clone(), window, cx);
 5173                cx.emit(Event::ItemAdded {
 5174                    item: item.boxed_clone(),
 5175                });
 5176            }
 5177            pane::Event::Split { direction, mode } => {
 5178                match mode {
 5179                    SplitMode::ClonePane => {
 5180                        self.split_and_clone(pane.clone(), *direction, window, cx)
 5181                            .detach();
 5182                    }
 5183                    SplitMode::EmptyPane => {
 5184                        self.split_pane(pane.clone(), *direction, window, cx);
 5185                    }
 5186                    SplitMode::MovePane => {
 5187                        self.split_and_move(pane.clone(), *direction, window, cx);
 5188                    }
 5189                };
 5190            }
 5191            pane::Event::JoinIntoNext => {
 5192                self.join_pane_into_next(pane.clone(), window, cx);
 5193            }
 5194            pane::Event::JoinAll => {
 5195                self.join_all_panes(window, cx);
 5196            }
 5197            pane::Event::Remove { focus_on_pane } => {
 5198                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 5199            }
 5200            pane::Event::ActivateItem {
 5201                local,
 5202                focus_changed,
 5203            } => {
 5204                window.invalidate_character_coordinates();
 5205
 5206                pane.update(cx, |pane, _| {
 5207                    pane.track_alternate_file_items();
 5208                });
 5209                if *local {
 5210                    self.unfollow_in_pane(pane, window, cx);
 5211                }
 5212                serialize_workspace = *focus_changed || pane != self.active_pane();
 5213                if pane == self.active_pane() {
 5214                    self.active_item_path_changed(*focus_changed, window, cx);
 5215                    self.update_active_view_for_followers(window, cx);
 5216                } else if *local {
 5217                    self.set_active_pane(pane, window, cx);
 5218                }
 5219            }
 5220            pane::Event::UserSavedItem { item, save_intent } => {
 5221                cx.emit(Event::UserSavedItem {
 5222                    pane: pane.downgrade(),
 5223                    item: item.boxed_clone(),
 5224                    save_intent: *save_intent,
 5225                });
 5226                serialize_workspace = false;
 5227            }
 5228            pane::Event::ChangeItemTitle => {
 5229                if *pane == self.active_pane {
 5230                    self.active_item_path_changed(false, window, cx);
 5231                }
 5232                serialize_workspace = false;
 5233            }
 5234            pane::Event::RemovedItem { item } => {
 5235                cx.emit(Event::ActiveItemChanged);
 5236                self.update_window_edited(window, cx);
 5237                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 5238                    && entry.get().entity_id() == pane.entity_id()
 5239                {
 5240                    entry.remove();
 5241                }
 5242                cx.emit(Event::ItemRemoved {
 5243                    item_id: item.item_id(),
 5244                });
 5245            }
 5246            pane::Event::Focus => {
 5247                window.invalidate_character_coordinates();
 5248                self.handle_pane_focused(pane.clone(), window, cx);
 5249            }
 5250            pane::Event::ZoomIn => {
 5251                if *pane == self.active_pane {
 5252                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 5253                    if pane.read(cx).has_focus(window, cx) {
 5254                        self.zoomed = Some(pane.downgrade().into());
 5255                        self.zoomed_position = None;
 5256                        cx.emit(Event::ZoomChanged);
 5257                    }
 5258                    cx.notify();
 5259                }
 5260            }
 5261            pane::Event::ZoomOut => {
 5262                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 5263                if self.zoomed_position.is_none() {
 5264                    self.zoomed = None;
 5265                    cx.emit(Event::ZoomChanged);
 5266                }
 5267                cx.notify();
 5268            }
 5269            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 5270        }
 5271
 5272        if serialize_workspace {
 5273            self.serialize_workspace(window, cx);
 5274        }
 5275    }
 5276
 5277    pub fn unfollow_in_pane(
 5278        &mut self,
 5279        pane: &Entity<Pane>,
 5280        window: &mut Window,
 5281        cx: &mut Context<Workspace>,
 5282    ) -> Option<CollaboratorId> {
 5283        let leader_id = self.leader_for_pane(pane)?;
 5284        self.unfollow(leader_id, window, cx);
 5285        Some(leader_id)
 5286    }
 5287
 5288    pub fn split_pane(
 5289        &mut self,
 5290        pane_to_split: Entity<Pane>,
 5291        split_direction: SplitDirection,
 5292        window: &mut Window,
 5293        cx: &mut Context<Self>,
 5294    ) -> Entity<Pane> {
 5295        let new_pane = self.add_pane(window, cx);
 5296        self.center
 5297            .split(&pane_to_split, &new_pane, split_direction, cx);
 5298        cx.notify();
 5299        new_pane
 5300    }
 5301
 5302    pub fn split_and_move(
 5303        &mut self,
 5304        pane: Entity<Pane>,
 5305        direction: SplitDirection,
 5306        window: &mut Window,
 5307        cx: &mut Context<Self>,
 5308    ) {
 5309        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 5310            return;
 5311        };
 5312        let new_pane = self.add_pane(window, cx);
 5313        new_pane.update(cx, |pane, cx| {
 5314            pane.add_item(item, true, true, None, window, cx)
 5315        });
 5316        self.center.split(&pane, &new_pane, direction, cx);
 5317        cx.notify();
 5318    }
 5319
 5320    pub fn split_and_clone(
 5321        &mut self,
 5322        pane: Entity<Pane>,
 5323        direction: SplitDirection,
 5324        window: &mut Window,
 5325        cx: &mut Context<Self>,
 5326    ) -> Task<Option<Entity<Pane>>> {
 5327        let Some(item) = pane.read(cx).active_item() else {
 5328            return Task::ready(None);
 5329        };
 5330        if !item.can_split(cx) {
 5331            return Task::ready(None);
 5332        }
 5333        let task = item.clone_on_split(self.database_id(), window, cx);
 5334        cx.spawn_in(window, async move |this, cx| {
 5335            if let Some(clone) = task.await {
 5336                this.update_in(cx, |this, window, cx| {
 5337                    let new_pane = this.add_pane(window, cx);
 5338                    let nav_history = pane.read(cx).fork_nav_history();
 5339                    new_pane.update(cx, |pane, cx| {
 5340                        pane.set_nav_history(nav_history, cx);
 5341                        pane.add_item(clone, true, true, None, window, cx)
 5342                    });
 5343                    this.center.split(&pane, &new_pane, direction, cx);
 5344                    cx.notify();
 5345                    new_pane
 5346                })
 5347                .ok()
 5348            } else {
 5349                None
 5350            }
 5351        })
 5352    }
 5353
 5354    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5355        let active_item = self.active_pane.read(cx).active_item();
 5356        for pane in &self.panes {
 5357            join_pane_into_active(&self.active_pane, pane, window, cx);
 5358        }
 5359        if let Some(active_item) = active_item {
 5360            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5361        }
 5362        cx.notify();
 5363    }
 5364
 5365    pub fn join_pane_into_next(
 5366        &mut self,
 5367        pane: Entity<Pane>,
 5368        window: &mut Window,
 5369        cx: &mut Context<Self>,
 5370    ) {
 5371        let next_pane = self
 5372            .find_pane_in_direction(SplitDirection::Right, cx)
 5373            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5374            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5375            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5376        let Some(next_pane) = next_pane else {
 5377            return;
 5378        };
 5379        move_all_items(&pane, &next_pane, window, cx);
 5380        cx.notify();
 5381    }
 5382
 5383    fn remove_pane(
 5384        &mut self,
 5385        pane: Entity<Pane>,
 5386        focus_on: Option<Entity<Pane>>,
 5387        window: &mut Window,
 5388        cx: &mut Context<Self>,
 5389    ) {
 5390        if self.center.remove(&pane, cx).unwrap() {
 5391            self.force_remove_pane(&pane, &focus_on, window, cx);
 5392            self.unfollow_in_pane(&pane, window, cx);
 5393            self.last_leaders_by_pane.remove(&pane.downgrade());
 5394            for removed_item in pane.read(cx).items() {
 5395                self.panes_by_item.remove(&removed_item.item_id());
 5396            }
 5397
 5398            cx.notify();
 5399        } else {
 5400            self.active_item_path_changed(true, window, cx);
 5401        }
 5402        cx.emit(Event::PaneRemoved);
 5403    }
 5404
 5405    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5406        &mut self.panes
 5407    }
 5408
 5409    pub fn panes(&self) -> &[Entity<Pane>] {
 5410        &self.panes
 5411    }
 5412
 5413    pub fn active_pane(&self) -> &Entity<Pane> {
 5414        &self.active_pane
 5415    }
 5416
 5417    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5418        for dock in self.all_docks() {
 5419            if dock.focus_handle(cx).contains_focused(window, cx)
 5420                && let Some(pane) = dock
 5421                    .read(cx)
 5422                    .active_panel()
 5423                    .and_then(|panel| panel.pane(cx))
 5424            {
 5425                return pane;
 5426            }
 5427        }
 5428        self.active_pane().clone()
 5429    }
 5430
 5431    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5432        self.find_pane_in_direction(SplitDirection::Right, cx)
 5433            .unwrap_or_else(|| {
 5434                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5435            })
 5436    }
 5437
 5438    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5439        self.pane_for_item_id(handle.item_id())
 5440    }
 5441
 5442    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5443        let weak_pane = self.panes_by_item.get(&item_id)?;
 5444        weak_pane.upgrade()
 5445    }
 5446
 5447    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5448        self.panes
 5449            .iter()
 5450            .find(|pane| pane.entity_id() == entity_id)
 5451            .cloned()
 5452    }
 5453
 5454    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5455        self.follower_states.retain(|leader_id, state| {
 5456            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5457                for item in state.items_by_leader_view_id.values() {
 5458                    item.view.set_leader_id(None, window, cx);
 5459                }
 5460                false
 5461            } else {
 5462                true
 5463            }
 5464        });
 5465        cx.notify();
 5466    }
 5467
 5468    pub fn start_following(
 5469        &mut self,
 5470        leader_id: impl Into<CollaboratorId>,
 5471        window: &mut Window,
 5472        cx: &mut Context<Self>,
 5473    ) -> Option<Task<Result<()>>> {
 5474        let leader_id = leader_id.into();
 5475        let pane = self.active_pane().clone();
 5476
 5477        self.last_leaders_by_pane
 5478            .insert(pane.downgrade(), leader_id);
 5479        self.unfollow(leader_id, window, cx);
 5480        self.unfollow_in_pane(&pane, window, cx);
 5481        self.follower_states.insert(
 5482            leader_id,
 5483            FollowerState {
 5484                center_pane: pane.clone(),
 5485                dock_pane: None,
 5486                active_view_id: None,
 5487                items_by_leader_view_id: Default::default(),
 5488            },
 5489        );
 5490        cx.notify();
 5491
 5492        match leader_id {
 5493            CollaboratorId::PeerId(leader_peer_id) => {
 5494                let room_id = self.active_call()?.room_id(cx)?;
 5495                let project_id = self.project.read(cx).remote_id();
 5496                let request = self.app_state.client.request(proto::Follow {
 5497                    room_id,
 5498                    project_id,
 5499                    leader_id: Some(leader_peer_id),
 5500                });
 5501
 5502                Some(cx.spawn_in(window, async move |this, cx| {
 5503                    let response = request.await?;
 5504                    this.update(cx, |this, _| {
 5505                        let state = this
 5506                            .follower_states
 5507                            .get_mut(&leader_id)
 5508                            .context("following interrupted")?;
 5509                        state.active_view_id = response
 5510                            .active_view
 5511                            .as_ref()
 5512                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5513                        anyhow::Ok(())
 5514                    })??;
 5515                    if let Some(view) = response.active_view {
 5516                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5517                    }
 5518                    this.update_in(cx, |this, window, cx| {
 5519                        this.leader_updated(leader_id, window, cx)
 5520                    })?;
 5521                    Ok(())
 5522                }))
 5523            }
 5524            CollaboratorId::Agent => {
 5525                self.leader_updated(leader_id, window, cx)?;
 5526                Some(Task::ready(Ok(())))
 5527            }
 5528        }
 5529    }
 5530
 5531    pub fn follow_next_collaborator(
 5532        &mut self,
 5533        _: &FollowNextCollaborator,
 5534        window: &mut Window,
 5535        cx: &mut Context<Self>,
 5536    ) {
 5537        let collaborators = self.project.read(cx).collaborators();
 5538        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5539            let mut collaborators = collaborators.keys().copied();
 5540            for peer_id in collaborators.by_ref() {
 5541                if CollaboratorId::PeerId(peer_id) == leader_id {
 5542                    break;
 5543                }
 5544            }
 5545            collaborators.next().map(CollaboratorId::PeerId)
 5546        } else if let Some(last_leader_id) =
 5547            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5548        {
 5549            match last_leader_id {
 5550                CollaboratorId::PeerId(peer_id) => {
 5551                    if collaborators.contains_key(peer_id) {
 5552                        Some(*last_leader_id)
 5553                    } else {
 5554                        None
 5555                    }
 5556                }
 5557                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5558            }
 5559        } else {
 5560            None
 5561        };
 5562
 5563        let pane = self.active_pane.clone();
 5564        let Some(leader_id) = next_leader_id.or_else(|| {
 5565            Some(CollaboratorId::PeerId(
 5566                collaborators.keys().copied().next()?,
 5567            ))
 5568        }) else {
 5569            return;
 5570        };
 5571        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5572            return;
 5573        }
 5574        if let Some(task) = self.start_following(leader_id, window, cx) {
 5575            task.detach_and_log_err(cx)
 5576        }
 5577    }
 5578
 5579    pub fn follow(
 5580        &mut self,
 5581        leader_id: impl Into<CollaboratorId>,
 5582        window: &mut Window,
 5583        cx: &mut Context<Self>,
 5584    ) {
 5585        let leader_id = leader_id.into();
 5586
 5587        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5588            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5589                return;
 5590            };
 5591            let Some(remote_participant) =
 5592                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5593            else {
 5594                return;
 5595            };
 5596
 5597            let project = self.project.read(cx);
 5598
 5599            let other_project_id = match remote_participant.location {
 5600                ParticipantLocation::External => None,
 5601                ParticipantLocation::UnsharedProject => None,
 5602                ParticipantLocation::SharedProject { project_id } => {
 5603                    if Some(project_id) == project.remote_id() {
 5604                        None
 5605                    } else {
 5606                        Some(project_id)
 5607                    }
 5608                }
 5609            };
 5610
 5611            // if they are active in another project, follow there.
 5612            if let Some(project_id) = other_project_id {
 5613                let app_state = self.app_state.clone();
 5614                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5615                    .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
 5616                        Some(format!("{error:#}"))
 5617                    });
 5618            }
 5619        }
 5620
 5621        // if you're already following, find the right pane and focus it.
 5622        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5623            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5624
 5625            return;
 5626        }
 5627
 5628        // Otherwise, follow.
 5629        if let Some(task) = self.start_following(leader_id, window, cx) {
 5630            task.detach_and_log_err(cx)
 5631        }
 5632    }
 5633
 5634    pub fn unfollow(
 5635        &mut self,
 5636        leader_id: impl Into<CollaboratorId>,
 5637        window: &mut Window,
 5638        cx: &mut Context<Self>,
 5639    ) -> Option<()> {
 5640        cx.notify();
 5641
 5642        let leader_id = leader_id.into();
 5643        let state = self.follower_states.remove(&leader_id)?;
 5644        for (_, item) in state.items_by_leader_view_id {
 5645            item.view.set_leader_id(None, window, cx);
 5646        }
 5647
 5648        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5649            let project_id = self.project.read(cx).remote_id();
 5650            let room_id = self.active_call()?.room_id(cx)?;
 5651            self.app_state
 5652                .client
 5653                .send(proto::Unfollow {
 5654                    room_id,
 5655                    project_id,
 5656                    leader_id: Some(leader_peer_id),
 5657                })
 5658                .log_err();
 5659        }
 5660
 5661        Some(())
 5662    }
 5663
 5664    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5665        self.follower_states.contains_key(&id.into())
 5666    }
 5667
 5668    fn active_item_path_changed(
 5669        &mut self,
 5670        focus_changed: bool,
 5671        window: &mut Window,
 5672        cx: &mut Context<Self>,
 5673    ) {
 5674        cx.emit(Event::ActiveItemChanged);
 5675        let active_entry = self.active_project_path(cx);
 5676        self.project.update(cx, |project, cx| {
 5677            project.set_active_path(active_entry.clone(), cx)
 5678        });
 5679
 5680        if focus_changed && let Some(project_path) = &active_entry {
 5681            let git_store_entity = self.project.read(cx).git_store().clone();
 5682            git_store_entity.update(cx, |git_store, cx| {
 5683                git_store.set_active_repo_for_path(project_path, cx);
 5684            });
 5685        }
 5686
 5687        self.update_window_title(window, cx);
 5688    }
 5689
 5690    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5691        let project = self.project().read(cx);
 5692        let mut title = String::new();
 5693
 5694        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5695            let name = {
 5696                let settings_location = SettingsLocation {
 5697                    worktree_id: worktree.read(cx).id(),
 5698                    path: RelPath::empty(),
 5699                };
 5700
 5701                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5702                match &settings.project_name {
 5703                    Some(name) => name.as_str(),
 5704                    None => worktree.read(cx).root_name_str(),
 5705                }
 5706            };
 5707            if i > 0 {
 5708                title.push_str(", ");
 5709            }
 5710            title.push_str(name);
 5711        }
 5712
 5713        if title.is_empty() {
 5714            title = "empty project".to_string();
 5715        }
 5716
 5717        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5718            let filename = path.path.file_name().or_else(|| {
 5719                Some(
 5720                    project
 5721                        .worktree_for_id(path.worktree_id, cx)?
 5722                        .read(cx)
 5723                        .root_name_str(),
 5724                )
 5725            });
 5726
 5727            if let Some(filename) = filename {
 5728                title.push_str("");
 5729                title.push_str(filename.as_ref());
 5730            }
 5731        }
 5732
 5733        if project.is_via_collab() {
 5734            title.push_str("");
 5735        } else if project.is_shared() {
 5736            title.push_str("");
 5737        }
 5738
 5739        if let Some(last_title) = self.last_window_title.as_ref()
 5740            && &title == last_title
 5741        {
 5742            return;
 5743        }
 5744        window.set_window_title(&title);
 5745        SystemWindowTabController::update_tab_title(
 5746            cx,
 5747            window.window_handle().window_id(),
 5748            SharedString::from(&title),
 5749        );
 5750        self.last_window_title = Some(title);
 5751    }
 5752
 5753    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5754        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5755        if is_edited != self.window_edited {
 5756            self.window_edited = is_edited;
 5757            window.set_window_edited(self.window_edited)
 5758        }
 5759    }
 5760
 5761    fn update_item_dirty_state(
 5762        &mut self,
 5763        item: &dyn ItemHandle,
 5764        window: &mut Window,
 5765        cx: &mut App,
 5766    ) {
 5767        let is_dirty = item.is_dirty(cx);
 5768        let item_id = item.item_id();
 5769        let was_dirty = self.dirty_items.contains_key(&item_id);
 5770        if is_dirty == was_dirty {
 5771            return;
 5772        }
 5773        if was_dirty {
 5774            self.dirty_items.remove(&item_id);
 5775            self.update_window_edited(window, cx);
 5776            return;
 5777        }
 5778
 5779        let workspace = self.weak_handle();
 5780        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5781            return;
 5782        };
 5783        let on_release_callback = Box::new(move |cx: &mut App| {
 5784            window_handle
 5785                .update(cx, |_, window, cx| {
 5786                    workspace
 5787                        .update(cx, |workspace, cx| {
 5788                            workspace.dirty_items.remove(&item_id);
 5789                            workspace.update_window_edited(window, cx)
 5790                        })
 5791                        .ok();
 5792                })
 5793                .ok();
 5794        });
 5795
 5796        let s = item.on_release(cx, on_release_callback);
 5797        self.dirty_items.insert(item_id, s);
 5798        self.update_window_edited(window, cx);
 5799    }
 5800
 5801    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5802        if self.notifications.is_empty() {
 5803            None
 5804        } else {
 5805            Some(
 5806                div()
 5807                    .absolute()
 5808                    .right_3()
 5809                    .bottom_3()
 5810                    .w_112()
 5811                    .h_full()
 5812                    .flex()
 5813                    .flex_col()
 5814                    .justify_end()
 5815                    .gap_2()
 5816                    .children(
 5817                        self.notifications
 5818                            .iter()
 5819                            .map(|(_, notification)| notification.clone().into_any()),
 5820                    ),
 5821            )
 5822        }
 5823    }
 5824
 5825    // RPC handlers
 5826
 5827    fn active_view_for_follower(
 5828        &self,
 5829        follower_project_id: Option<u64>,
 5830        window: &mut Window,
 5831        cx: &mut Context<Self>,
 5832    ) -> Option<proto::View> {
 5833        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5834        let item = item?;
 5835        let leader_id = self
 5836            .pane_for(&*item)
 5837            .and_then(|pane| self.leader_for_pane(&pane));
 5838        let leader_peer_id = match leader_id {
 5839            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5840            Some(CollaboratorId::Agent) | None => None,
 5841        };
 5842
 5843        let item_handle = item.to_followable_item_handle(cx)?;
 5844        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5845        let variant = item_handle.to_state_proto(window, cx)?;
 5846
 5847        if item_handle.is_project_item(window, cx)
 5848            && (follower_project_id.is_none()
 5849                || follower_project_id != self.project.read(cx).remote_id())
 5850        {
 5851            return None;
 5852        }
 5853
 5854        Some(proto::View {
 5855            id: id.to_proto(),
 5856            leader_id: leader_peer_id,
 5857            variant: Some(variant),
 5858            panel_id: panel_id.map(|id| id as i32),
 5859        })
 5860    }
 5861
 5862    fn handle_follow(
 5863        &mut self,
 5864        follower_project_id: Option<u64>,
 5865        window: &mut Window,
 5866        cx: &mut Context<Self>,
 5867    ) -> proto::FollowResponse {
 5868        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5869
 5870        cx.notify();
 5871        proto::FollowResponse {
 5872            views: active_view.iter().cloned().collect(),
 5873            active_view,
 5874        }
 5875    }
 5876
 5877    fn handle_update_followers(
 5878        &mut self,
 5879        leader_id: PeerId,
 5880        message: proto::UpdateFollowers,
 5881        _window: &mut Window,
 5882        _cx: &mut Context<Self>,
 5883    ) {
 5884        self.leader_updates_tx
 5885            .unbounded_send((leader_id, message))
 5886            .ok();
 5887    }
 5888
 5889    async fn process_leader_update(
 5890        this: &WeakEntity<Self>,
 5891        leader_id: PeerId,
 5892        update: proto::UpdateFollowers,
 5893        cx: &mut AsyncWindowContext,
 5894    ) -> Result<()> {
 5895        match update.variant.context("invalid update")? {
 5896            proto::update_followers::Variant::CreateView(view) => {
 5897                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5898                let should_add_view = this.update(cx, |this, _| {
 5899                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5900                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5901                    } else {
 5902                        anyhow::Ok(false)
 5903                    }
 5904                })??;
 5905
 5906                if should_add_view {
 5907                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5908                }
 5909            }
 5910            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5911                let should_add_view = this.update(cx, |this, _| {
 5912                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5913                        state.active_view_id = update_active_view
 5914                            .view
 5915                            .as_ref()
 5916                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5917
 5918                        if state.active_view_id.is_some_and(|view_id| {
 5919                            !state.items_by_leader_view_id.contains_key(&view_id)
 5920                        }) {
 5921                            anyhow::Ok(true)
 5922                        } else {
 5923                            anyhow::Ok(false)
 5924                        }
 5925                    } else {
 5926                        anyhow::Ok(false)
 5927                    }
 5928                })??;
 5929
 5930                if should_add_view && let Some(view) = update_active_view.view {
 5931                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5932                }
 5933            }
 5934            proto::update_followers::Variant::UpdateView(update_view) => {
 5935                let variant = update_view.variant.context("missing update view variant")?;
 5936                let id = update_view.id.context("missing update view id")?;
 5937                let mut tasks = Vec::new();
 5938                this.update_in(cx, |this, window, cx| {
 5939                    let project = this.project.clone();
 5940                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5941                        let view_id = ViewId::from_proto(id.clone())?;
 5942                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5943                            tasks.push(item.view.apply_update_proto(
 5944                                &project,
 5945                                variant.clone(),
 5946                                window,
 5947                                cx,
 5948                            ));
 5949                        }
 5950                    }
 5951                    anyhow::Ok(())
 5952                })??;
 5953                try_join_all(tasks).await.log_err();
 5954            }
 5955        }
 5956        this.update_in(cx, |this, window, cx| {
 5957            this.leader_updated(leader_id, window, cx)
 5958        })?;
 5959        Ok(())
 5960    }
 5961
 5962    async fn add_view_from_leader(
 5963        this: WeakEntity<Self>,
 5964        leader_id: PeerId,
 5965        view: &proto::View,
 5966        cx: &mut AsyncWindowContext,
 5967    ) -> Result<()> {
 5968        let this = this.upgrade().context("workspace dropped")?;
 5969
 5970        let Some(id) = view.id.clone() else {
 5971            anyhow::bail!("no id for view");
 5972        };
 5973        let id = ViewId::from_proto(id)?;
 5974        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5975
 5976        let pane = this.update(cx, |this, _cx| {
 5977            let state = this
 5978                .follower_states
 5979                .get(&leader_id.into())
 5980                .context("stopped following")?;
 5981            anyhow::Ok(state.pane().clone())
 5982        })?;
 5983        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5984            let client = this.read(cx).client().clone();
 5985            pane.items().find_map(|item| {
 5986                let item = item.to_followable_item_handle(cx)?;
 5987                if item.remote_id(&client, window, cx) == Some(id) {
 5988                    Some(item)
 5989                } else {
 5990                    None
 5991                }
 5992            })
 5993        })?;
 5994        let item = if let Some(existing_item) = existing_item {
 5995            existing_item
 5996        } else {
 5997            let variant = view.variant.clone();
 5998            anyhow::ensure!(variant.is_some(), "missing view variant");
 5999
 6000            let task = cx.update(|window, cx| {
 6001                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 6002            })?;
 6003
 6004            let Some(task) = task else {
 6005                anyhow::bail!(
 6006                    "failed to construct view from leader (maybe from a different version of zed?)"
 6007                );
 6008            };
 6009
 6010            let mut new_item = task.await?;
 6011            pane.update_in(cx, |pane, window, cx| {
 6012                let mut item_to_remove = None;
 6013                for (ix, item) in pane.items().enumerate() {
 6014                    if let Some(item) = item.to_followable_item_handle(cx) {
 6015                        match new_item.dedup(item.as_ref(), window, cx) {
 6016                            Some(item::Dedup::KeepExisting) => {
 6017                                new_item =
 6018                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 6019                                break;
 6020                            }
 6021                            Some(item::Dedup::ReplaceExisting) => {
 6022                                item_to_remove = Some((ix, item.item_id()));
 6023                                break;
 6024                            }
 6025                            None => {}
 6026                        }
 6027                    }
 6028                }
 6029
 6030                if let Some((ix, id)) = item_to_remove {
 6031                    pane.remove_item(id, false, false, window, cx);
 6032                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 6033                }
 6034            })?;
 6035
 6036            new_item
 6037        };
 6038
 6039        this.update_in(cx, |this, window, cx| {
 6040            let state = this.follower_states.get_mut(&leader_id.into())?;
 6041            item.set_leader_id(Some(leader_id.into()), window, cx);
 6042            state.items_by_leader_view_id.insert(
 6043                id,
 6044                FollowerView {
 6045                    view: item,
 6046                    location: panel_id,
 6047                },
 6048            );
 6049
 6050            Some(())
 6051        })
 6052        .context("no follower state")?;
 6053
 6054        Ok(())
 6055    }
 6056
 6057    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6058        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 6059            return;
 6060        };
 6061
 6062        if let Some(agent_location) = self.project.read(cx).agent_location() {
 6063            let buffer_entity_id = agent_location.buffer.entity_id();
 6064            let view_id = ViewId {
 6065                creator: CollaboratorId::Agent,
 6066                id: buffer_entity_id.as_u64(),
 6067            };
 6068            follower_state.active_view_id = Some(view_id);
 6069
 6070            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 6071                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 6072                hash_map::Entry::Vacant(entry) => {
 6073                    let existing_view =
 6074                        follower_state
 6075                            .center_pane
 6076                            .read(cx)
 6077                            .items()
 6078                            .find_map(|item| {
 6079                                let item = item.to_followable_item_handle(cx)?;
 6080                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 6081                                    && item.project_item_model_ids(cx).as_slice()
 6082                                        == [buffer_entity_id]
 6083                                {
 6084                                    Some(item)
 6085                                } else {
 6086                                    None
 6087                                }
 6088                            });
 6089                    let view = existing_view.or_else(|| {
 6090                        agent_location.buffer.upgrade().and_then(|buffer| {
 6091                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 6092                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 6093                            })?
 6094                            .to_followable_item_handle(cx)
 6095                        })
 6096                    });
 6097
 6098                    view.map(|view| {
 6099                        entry.insert(FollowerView {
 6100                            view,
 6101                            location: None,
 6102                        })
 6103                    })
 6104                }
 6105            };
 6106
 6107            if let Some(item) = item {
 6108                item.view
 6109                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 6110                item.view
 6111                    .update_agent_location(agent_location.position, window, cx);
 6112            }
 6113        } else {
 6114            follower_state.active_view_id = None;
 6115        }
 6116
 6117        self.leader_updated(CollaboratorId::Agent, window, cx);
 6118    }
 6119
 6120    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 6121        let mut is_project_item = true;
 6122        let mut update = proto::UpdateActiveView::default();
 6123        if window.is_window_active() {
 6124            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 6125
 6126            if let Some(item) = active_item
 6127                && item.item_focus_handle(cx).contains_focused(window, cx)
 6128            {
 6129                let leader_id = self
 6130                    .pane_for(&*item)
 6131                    .and_then(|pane| self.leader_for_pane(&pane));
 6132                let leader_peer_id = match leader_id {
 6133                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 6134                    Some(CollaboratorId::Agent) | None => None,
 6135                };
 6136
 6137                if let Some(item) = item.to_followable_item_handle(cx) {
 6138                    let id = item
 6139                        .remote_id(&self.app_state.client, window, cx)
 6140                        .map(|id| id.to_proto());
 6141
 6142                    if let Some(id) = id
 6143                        && let Some(variant) = item.to_state_proto(window, cx)
 6144                    {
 6145                        let view = Some(proto::View {
 6146                            id,
 6147                            leader_id: leader_peer_id,
 6148                            variant: Some(variant),
 6149                            panel_id: panel_id.map(|id| id as i32),
 6150                        });
 6151
 6152                        is_project_item = item.is_project_item(window, cx);
 6153                        update = proto::UpdateActiveView { view };
 6154                    };
 6155                }
 6156            }
 6157        }
 6158
 6159        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 6160        if active_view_id != self.last_active_view_id.as_ref() {
 6161            self.last_active_view_id = active_view_id.cloned();
 6162            self.update_followers(
 6163                is_project_item,
 6164                proto::update_followers::Variant::UpdateActiveView(update),
 6165                window,
 6166                cx,
 6167            );
 6168        }
 6169    }
 6170
 6171    fn active_item_for_followers(
 6172        &self,
 6173        window: &mut Window,
 6174        cx: &mut App,
 6175    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 6176        let mut active_item = None;
 6177        let mut panel_id = None;
 6178        for dock in self.all_docks() {
 6179            if dock.focus_handle(cx).contains_focused(window, cx)
 6180                && let Some(panel) = dock.read(cx).active_panel()
 6181                && let Some(pane) = panel.pane(cx)
 6182                && let Some(item) = pane.read(cx).active_item()
 6183            {
 6184                active_item = Some(item);
 6185                panel_id = panel.remote_id();
 6186                break;
 6187            }
 6188        }
 6189
 6190        if active_item.is_none() {
 6191            active_item = self.active_pane().read(cx).active_item();
 6192        }
 6193        (active_item, panel_id)
 6194    }
 6195
 6196    fn update_followers(
 6197        &self,
 6198        project_only: bool,
 6199        update: proto::update_followers::Variant,
 6200        _: &mut Window,
 6201        cx: &mut App,
 6202    ) -> Option<()> {
 6203        // If this update only applies to for followers in the current project,
 6204        // then skip it unless this project is shared. If it applies to all
 6205        // followers, regardless of project, then set `project_id` to none,
 6206        // indicating that it goes to all followers.
 6207        let project_id = if project_only {
 6208            Some(self.project.read(cx).remote_id()?)
 6209        } else {
 6210            None
 6211        };
 6212        self.app_state().workspace_store.update(cx, |store, cx| {
 6213            store.update_followers(project_id, update, cx)
 6214        })
 6215    }
 6216
 6217    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 6218        self.follower_states.iter().find_map(|(leader_id, state)| {
 6219            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 6220                Some(*leader_id)
 6221            } else {
 6222                None
 6223            }
 6224        })
 6225    }
 6226
 6227    fn leader_updated(
 6228        &mut self,
 6229        leader_id: impl Into<CollaboratorId>,
 6230        window: &mut Window,
 6231        cx: &mut Context<Self>,
 6232    ) -> Option<Box<dyn ItemHandle>> {
 6233        cx.notify();
 6234
 6235        let leader_id = leader_id.into();
 6236        let (panel_id, item) = match leader_id {
 6237            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 6238            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 6239        };
 6240
 6241        let state = self.follower_states.get(&leader_id)?;
 6242        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 6243        let pane;
 6244        if let Some(panel_id) = panel_id {
 6245            pane = self
 6246                .activate_panel_for_proto_id(panel_id, window, cx)?
 6247                .pane(cx)?;
 6248            let state = self.follower_states.get_mut(&leader_id)?;
 6249            state.dock_pane = Some(pane.clone());
 6250        } else {
 6251            pane = state.center_pane.clone();
 6252            let state = self.follower_states.get_mut(&leader_id)?;
 6253            if let Some(dock_pane) = state.dock_pane.take() {
 6254                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 6255            }
 6256        }
 6257
 6258        pane.update(cx, |pane, cx| {
 6259            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 6260            if let Some(index) = pane.index_for_item(item.as_ref()) {
 6261                pane.activate_item(index, false, false, window, cx);
 6262            } else {
 6263                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 6264            }
 6265
 6266            if focus_active_item {
 6267                pane.focus_active_item(window, cx)
 6268            }
 6269        });
 6270
 6271        Some(item)
 6272    }
 6273
 6274    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 6275        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 6276        let active_view_id = state.active_view_id?;
 6277        Some(
 6278            state
 6279                .items_by_leader_view_id
 6280                .get(&active_view_id)?
 6281                .view
 6282                .boxed_clone(),
 6283        )
 6284    }
 6285
 6286    fn active_item_for_peer(
 6287        &self,
 6288        peer_id: PeerId,
 6289        window: &mut Window,
 6290        cx: &mut Context<Self>,
 6291    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 6292        let call = self.active_call()?;
 6293        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 6294        let leader_in_this_app;
 6295        let leader_in_this_project;
 6296        match participant.location {
 6297            ParticipantLocation::SharedProject { project_id } => {
 6298                leader_in_this_app = true;
 6299                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 6300            }
 6301            ParticipantLocation::UnsharedProject => {
 6302                leader_in_this_app = true;
 6303                leader_in_this_project = false;
 6304            }
 6305            ParticipantLocation::External => {
 6306                leader_in_this_app = false;
 6307                leader_in_this_project = false;
 6308            }
 6309        };
 6310        let state = self.follower_states.get(&peer_id.into())?;
 6311        let mut item_to_activate = None;
 6312        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 6313            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 6314                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 6315            {
 6316                item_to_activate = Some((item.location, item.view.boxed_clone()));
 6317            }
 6318        } else if let Some(shared_screen) =
 6319            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 6320        {
 6321            item_to_activate = Some((None, Box::new(shared_screen)));
 6322        }
 6323        item_to_activate
 6324    }
 6325
 6326    fn shared_screen_for_peer(
 6327        &self,
 6328        peer_id: PeerId,
 6329        pane: &Entity<Pane>,
 6330        window: &mut Window,
 6331        cx: &mut App,
 6332    ) -> Option<Entity<SharedScreen>> {
 6333        self.active_call()?
 6334            .create_shared_screen(peer_id, pane, window, cx)
 6335    }
 6336
 6337    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6338        if window.is_window_active() {
 6339            self.update_active_view_for_followers(window, cx);
 6340
 6341            if let Some(database_id) = self.database_id {
 6342                let db = WorkspaceDb::global(cx);
 6343                cx.background_spawn(async move { db.update_timestamp(database_id).await })
 6344                    .detach();
 6345            }
 6346        } else {
 6347            for pane in &self.panes {
 6348                pane.update(cx, |pane, cx| {
 6349                    if let Some(item) = pane.active_item() {
 6350                        item.workspace_deactivated(window, cx);
 6351                    }
 6352                    for item in pane.items() {
 6353                        if matches!(
 6354                            item.workspace_settings(cx).autosave,
 6355                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6356                        ) {
 6357                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6358                                .detach_and_log_err(cx);
 6359                        }
 6360                    }
 6361                });
 6362            }
 6363        }
 6364    }
 6365
 6366    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6367        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6368    }
 6369
 6370    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6371        self.active_call.as_ref().map(|(call, _)| call.clone())
 6372    }
 6373
 6374    fn on_active_call_event(
 6375        &mut self,
 6376        event: &ActiveCallEvent,
 6377        window: &mut Window,
 6378        cx: &mut Context<Self>,
 6379    ) {
 6380        match event {
 6381            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6382            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6383                self.leader_updated(participant_id, window, cx);
 6384            }
 6385        }
 6386    }
 6387
 6388    pub fn database_id(&self) -> Option<WorkspaceId> {
 6389        self.database_id
 6390    }
 6391
 6392    #[cfg(any(test, feature = "test-support"))]
 6393    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6394        self.database_id = Some(id);
 6395    }
 6396
 6397    pub fn session_id(&self) -> Option<String> {
 6398        self.session_id.clone()
 6399    }
 6400
 6401    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6402        let Some(display) = window.display(cx) else {
 6403            return Task::ready(());
 6404        };
 6405        let Ok(display_uuid) = display.uuid() else {
 6406            return Task::ready(());
 6407        };
 6408
 6409        let window_bounds = window.inner_window_bounds();
 6410        let database_id = self.database_id;
 6411        let has_paths = !self.root_paths(cx).is_empty();
 6412        let db = WorkspaceDb::global(cx);
 6413        let kvp = db::kvp::KeyValueStore::global(cx);
 6414
 6415        cx.background_executor().spawn(async move {
 6416            if !has_paths {
 6417                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6418                    .await
 6419                    .log_err();
 6420            }
 6421            if let Some(database_id) = database_id {
 6422                db.set_window_open_status(
 6423                    database_id,
 6424                    SerializedWindowBounds(window_bounds),
 6425                    display_uuid,
 6426                )
 6427                .await
 6428                .log_err();
 6429            } else {
 6430                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6431                    .await
 6432                    .log_err();
 6433            }
 6434        })
 6435    }
 6436
 6437    /// Bypass the 200ms serialization throttle and write workspace state to
 6438    /// the DB immediately. Returns a task the caller can await to ensure the
 6439    /// write completes. Used by the quit handler so the most recent state
 6440    /// isn't lost to a pending throttle timer when the process exits.
 6441    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6442        self._schedule_serialize_workspace.take();
 6443        self._serialize_workspace_task.take();
 6444        self.bounds_save_task_queued.take();
 6445
 6446        let bounds_task = self.save_window_bounds(window, cx);
 6447        let serialize_task = self.serialize_workspace_internal(window, cx);
 6448        cx.spawn(async move |_| {
 6449            bounds_task.await;
 6450            serialize_task.await;
 6451        })
 6452    }
 6453
 6454    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6455        let project = self.project().read(cx);
 6456        project
 6457            .visible_worktrees(cx)
 6458            .map(|worktree| worktree.read(cx).abs_path())
 6459            .collect::<Vec<_>>()
 6460    }
 6461
 6462    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6463        match member {
 6464            Member::Axis(PaneAxis { members, .. }) => {
 6465                for child in members.iter() {
 6466                    self.remove_panes(child.clone(), window, cx)
 6467                }
 6468            }
 6469            Member::Pane(pane) => {
 6470                self.force_remove_pane(&pane, &None, window, cx);
 6471            }
 6472        }
 6473    }
 6474
 6475    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6476        self.session_id.take();
 6477        self.serialize_workspace_internal(window, cx)
 6478    }
 6479
 6480    fn force_remove_pane(
 6481        &mut self,
 6482        pane: &Entity<Pane>,
 6483        focus_on: &Option<Entity<Pane>>,
 6484        window: &mut Window,
 6485        cx: &mut Context<Workspace>,
 6486    ) {
 6487        self.panes.retain(|p| p != pane);
 6488        if let Some(focus_on) = focus_on {
 6489            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6490        } else if self.active_pane() == pane {
 6491            self.panes
 6492                .last()
 6493                .unwrap()
 6494                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6495        }
 6496        if self.last_active_center_pane == Some(pane.downgrade()) {
 6497            self.last_active_center_pane = None;
 6498        }
 6499        cx.notify();
 6500    }
 6501
 6502    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6503        if self._schedule_serialize_workspace.is_none() {
 6504            self._schedule_serialize_workspace =
 6505                Some(cx.spawn_in(window, async move |this, cx| {
 6506                    cx.background_executor()
 6507                        .timer(SERIALIZATION_THROTTLE_TIME)
 6508                        .await;
 6509                    this.update_in(cx, |this, window, cx| {
 6510                        this._serialize_workspace_task =
 6511                            Some(this.serialize_workspace_internal(window, cx));
 6512                        this._schedule_serialize_workspace.take();
 6513                    })
 6514                    .log_err();
 6515                }));
 6516        }
 6517    }
 6518
 6519    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6520        let Some(database_id) = self.database_id() else {
 6521            return Task::ready(());
 6522        };
 6523
 6524        fn serialize_pane_handle(
 6525            pane_handle: &Entity<Pane>,
 6526            window: &mut Window,
 6527            cx: &mut App,
 6528        ) -> SerializedPane {
 6529            let (items, active, pinned_count) = {
 6530                let pane = pane_handle.read(cx);
 6531                let active_item_id = pane.active_item().map(|item| item.item_id());
 6532                (
 6533                    pane.items()
 6534                        .filter_map(|handle| {
 6535                            let handle = handle.to_serializable_item_handle(cx)?;
 6536
 6537                            Some(SerializedItem {
 6538                                kind: Arc::from(handle.serialized_item_kind()),
 6539                                item_id: handle.item_id().as_u64(),
 6540                                active: Some(handle.item_id()) == active_item_id,
 6541                                preview: pane.is_active_preview_item(handle.item_id()),
 6542                            })
 6543                        })
 6544                        .collect::<Vec<_>>(),
 6545                    pane.has_focus(window, cx),
 6546                    pane.pinned_count(),
 6547                )
 6548            };
 6549
 6550            SerializedPane::new(items, active, pinned_count)
 6551        }
 6552
 6553        fn build_serialized_pane_group(
 6554            pane_group: &Member,
 6555            window: &mut Window,
 6556            cx: &mut App,
 6557        ) -> SerializedPaneGroup {
 6558            match pane_group {
 6559                Member::Axis(PaneAxis {
 6560                    axis,
 6561                    members,
 6562                    flexes,
 6563                    bounding_boxes: _,
 6564                }) => SerializedPaneGroup::Group {
 6565                    axis: SerializedAxis(*axis),
 6566                    children: members
 6567                        .iter()
 6568                        .map(|member| build_serialized_pane_group(member, window, cx))
 6569                        .collect::<Vec<_>>(),
 6570                    flexes: Some(flexes.lock().clone()),
 6571                },
 6572                Member::Pane(pane_handle) => {
 6573                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6574                }
 6575            }
 6576        }
 6577
 6578        fn build_serialized_docks(
 6579            this: &Workspace,
 6580            window: &mut Window,
 6581            cx: &mut App,
 6582        ) -> DockStructure {
 6583            this.capture_dock_state(window, cx)
 6584        }
 6585
 6586        match self.workspace_location(cx) {
 6587            WorkspaceLocation::Location(location, paths) => {
 6588                let breakpoints = self.project.update(cx, |project, cx| {
 6589                    project
 6590                        .breakpoint_store()
 6591                        .read(cx)
 6592                        .all_source_breakpoints(cx)
 6593                });
 6594                let user_toolchains = self
 6595                    .project
 6596                    .read(cx)
 6597                    .user_toolchains(cx)
 6598                    .unwrap_or_default();
 6599
 6600                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6601                let docks = build_serialized_docks(self, window, cx);
 6602                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6603
 6604                let serialized_workspace = SerializedWorkspace {
 6605                    id: database_id,
 6606                    location,
 6607                    paths,
 6608                    center_group,
 6609                    window_bounds,
 6610                    display: Default::default(),
 6611                    docks,
 6612                    centered_layout: self.centered_layout,
 6613                    session_id: self.session_id.clone(),
 6614                    breakpoints,
 6615                    window_id: Some(window.window_handle().window_id().as_u64()),
 6616                    user_toolchains,
 6617                };
 6618
 6619                let db = WorkspaceDb::global(cx);
 6620                window.spawn(cx, async move |_| {
 6621                    db.save_workspace(serialized_workspace).await;
 6622                })
 6623            }
 6624            WorkspaceLocation::DetachFromSession => {
 6625                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6626                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6627                // Save dock state for empty local workspaces
 6628                let docks = build_serialized_docks(self, window, cx);
 6629                let db = WorkspaceDb::global(cx);
 6630                let kvp = db::kvp::KeyValueStore::global(cx);
 6631                window.spawn(cx, async move |_| {
 6632                    db.set_window_open_status(
 6633                        database_id,
 6634                        window_bounds,
 6635                        display.unwrap_or_default(),
 6636                    )
 6637                    .await
 6638                    .log_err();
 6639                    db.set_session_id(database_id, None).await.log_err();
 6640                    persistence::write_default_dock_state(&kvp, docks)
 6641                        .await
 6642                        .log_err();
 6643                })
 6644            }
 6645            WorkspaceLocation::None => {
 6646                // Save dock state for empty non-local workspaces
 6647                let docks = build_serialized_docks(self, window, cx);
 6648                let kvp = db::kvp::KeyValueStore::global(cx);
 6649                window.spawn(cx, async move |_| {
 6650                    persistence::write_default_dock_state(&kvp, docks)
 6651                        .await
 6652                        .log_err();
 6653                })
 6654            }
 6655        }
 6656    }
 6657
 6658    fn has_any_items_open(&self, cx: &App) -> bool {
 6659        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6660    }
 6661
 6662    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6663        let paths = PathList::new(&self.root_paths(cx));
 6664        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6665            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6666        } else if self.project.read(cx).is_local() {
 6667            if !paths.is_empty() || self.has_any_items_open(cx) {
 6668                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6669            } else {
 6670                WorkspaceLocation::DetachFromSession
 6671            }
 6672        } else {
 6673            WorkspaceLocation::None
 6674        }
 6675    }
 6676
 6677    fn update_history(&self, cx: &mut App) {
 6678        let Some(id) = self.database_id() else {
 6679            return;
 6680        };
 6681        if !self.project.read(cx).is_local() {
 6682            return;
 6683        }
 6684        if let Some(manager) = HistoryManager::global(cx) {
 6685            let paths = PathList::new(&self.root_paths(cx));
 6686            manager.update(cx, |this, cx| {
 6687                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6688            });
 6689        }
 6690    }
 6691
 6692    async fn serialize_items(
 6693        this: &WeakEntity<Self>,
 6694        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6695        cx: &mut AsyncWindowContext,
 6696    ) -> Result<()> {
 6697        const CHUNK_SIZE: usize = 200;
 6698
 6699        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6700
 6701        while let Some(items_received) = serializable_items.next().await {
 6702            let unique_items =
 6703                items_received
 6704                    .into_iter()
 6705                    .fold(HashMap::default(), |mut acc, item| {
 6706                        acc.entry(item.item_id()).or_insert(item);
 6707                        acc
 6708                    });
 6709
 6710            // We use into_iter() here so that the references to the items are moved into
 6711            // the tasks and not kept alive while we're sleeping.
 6712            for (_, item) in unique_items.into_iter() {
 6713                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6714                    item.serialize(workspace, false, window, cx)
 6715                }) {
 6716                    cx.background_spawn(async move { task.await.log_err() })
 6717                        .detach();
 6718                }
 6719            }
 6720
 6721            cx.background_executor()
 6722                .timer(SERIALIZATION_THROTTLE_TIME)
 6723                .await;
 6724        }
 6725
 6726        Ok(())
 6727    }
 6728
 6729    pub(crate) fn enqueue_item_serialization(
 6730        &mut self,
 6731        item: Box<dyn SerializableItemHandle>,
 6732    ) -> Result<()> {
 6733        self.serializable_items_tx
 6734            .unbounded_send(item)
 6735            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6736    }
 6737
 6738    pub(crate) fn load_workspace(
 6739        serialized_workspace: SerializedWorkspace,
 6740        paths_to_open: Vec<Option<ProjectPath>>,
 6741        window: &mut Window,
 6742        cx: &mut Context<Workspace>,
 6743    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6744        cx.spawn_in(window, async move |workspace, cx| {
 6745            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6746
 6747            let mut center_group = None;
 6748            let mut center_items = None;
 6749
 6750            // Traverse the splits tree and add to things
 6751            if let Some((group, active_pane, items)) = serialized_workspace
 6752                .center_group
 6753                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6754                .await
 6755            {
 6756                center_items = Some(items);
 6757                center_group = Some((group, active_pane))
 6758            }
 6759
 6760            let mut items_by_project_path = HashMap::default();
 6761            let mut item_ids_by_kind = HashMap::default();
 6762            let mut all_deserialized_items = Vec::default();
 6763            cx.update(|_, cx| {
 6764                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6765                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6766                        item_ids_by_kind
 6767                            .entry(serializable_item_handle.serialized_item_kind())
 6768                            .or_insert(Vec::new())
 6769                            .push(item.item_id().as_u64() as ItemId);
 6770                    }
 6771
 6772                    if let Some(project_path) = item.project_path(cx) {
 6773                        items_by_project_path.insert(project_path, item.clone());
 6774                    }
 6775                    all_deserialized_items.push(item);
 6776                }
 6777            })?;
 6778
 6779            let opened_items = paths_to_open
 6780                .into_iter()
 6781                .map(|path_to_open| {
 6782                    path_to_open
 6783                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6784                })
 6785                .collect::<Vec<_>>();
 6786
 6787            // Remove old panes from workspace panes list
 6788            workspace.update_in(cx, |workspace, window, cx| {
 6789                if let Some((center_group, active_pane)) = center_group {
 6790                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6791
 6792                    // Swap workspace center group
 6793                    workspace.center = PaneGroup::with_root(center_group);
 6794                    workspace.center.set_is_center(true);
 6795                    workspace.center.mark_positions(cx);
 6796
 6797                    if let Some(active_pane) = active_pane {
 6798                        workspace.set_active_pane(&active_pane, window, cx);
 6799                        cx.focus_self(window);
 6800                    } else {
 6801                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6802                    }
 6803                }
 6804
 6805                let docks = serialized_workspace.docks;
 6806
 6807                for (dock, serialized_dock) in [
 6808                    (&mut workspace.right_dock, docks.right),
 6809                    (&mut workspace.left_dock, docks.left),
 6810                    (&mut workspace.bottom_dock, docks.bottom),
 6811                ]
 6812                .iter_mut()
 6813                {
 6814                    dock.update(cx, |dock, cx| {
 6815                        dock.serialized_dock = Some(serialized_dock.clone());
 6816                        dock.restore_state(window, cx);
 6817                    });
 6818                }
 6819
 6820                cx.notify();
 6821            })?;
 6822
 6823            let _ = project
 6824                .update(cx, |project, cx| {
 6825                    project
 6826                        .breakpoint_store()
 6827                        .update(cx, |breakpoint_store, cx| {
 6828                            breakpoint_store
 6829                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6830                        })
 6831                })
 6832                .await;
 6833
 6834            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6835            // after loading the items, we might have different items and in order to avoid
 6836            // the database filling up, we delete items that haven't been loaded now.
 6837            //
 6838            // The items that have been loaded, have been saved after they've been added to the workspace.
 6839            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6840                item_ids_by_kind
 6841                    .into_iter()
 6842                    .map(|(item_kind, loaded_items)| {
 6843                        SerializableItemRegistry::cleanup(
 6844                            item_kind,
 6845                            serialized_workspace.id,
 6846                            loaded_items,
 6847                            window,
 6848                            cx,
 6849                        )
 6850                        .log_err()
 6851                    })
 6852                    .collect::<Vec<_>>()
 6853            })?;
 6854
 6855            futures::future::join_all(clean_up_tasks).await;
 6856
 6857            workspace
 6858                .update_in(cx, |workspace, window, cx| {
 6859                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6860                    workspace.serialize_workspace_internal(window, cx).detach();
 6861
 6862                    // Ensure that we mark the window as edited if we did load dirty items
 6863                    workspace.update_window_edited(window, cx);
 6864                })
 6865                .ok();
 6866
 6867            Ok(opened_items)
 6868        })
 6869    }
 6870
 6871    pub fn key_context(&self, cx: &App) -> KeyContext {
 6872        let mut context = KeyContext::new_with_defaults();
 6873        context.add("Workspace");
 6874        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6875        if let Some(status) = self
 6876            .debugger_provider
 6877            .as_ref()
 6878            .and_then(|provider| provider.active_thread_state(cx))
 6879        {
 6880            match status {
 6881                ThreadStatus::Running | ThreadStatus::Stepping => {
 6882                    context.add("debugger_running");
 6883                }
 6884                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6885                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6886            }
 6887        }
 6888
 6889        if self.left_dock.read(cx).is_open() {
 6890            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6891                context.set("left_dock", active_panel.panel_key());
 6892            }
 6893        }
 6894
 6895        if self.right_dock.read(cx).is_open() {
 6896            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6897                context.set("right_dock", active_panel.panel_key());
 6898            }
 6899        }
 6900
 6901        if self.bottom_dock.read(cx).is_open() {
 6902            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6903                context.set("bottom_dock", active_panel.panel_key());
 6904            }
 6905        }
 6906
 6907        context
 6908    }
 6909
 6910    /// Multiworkspace uses this to add workspace action handling to itself
 6911    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6912        self.add_workspace_actions_listeners(div, window, cx)
 6913            .on_action(cx.listener(
 6914                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6915                    for action in &action_sequence.0 {
 6916                        window.dispatch_action(action.boxed_clone(), cx);
 6917                    }
 6918                },
 6919            ))
 6920            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6921            .on_action(cx.listener(Self::close_all_items_and_panes))
 6922            .on_action(cx.listener(Self::close_item_in_all_panes))
 6923            .on_action(cx.listener(Self::save_all))
 6924            .on_action(cx.listener(Self::send_keystrokes))
 6925            .on_action(cx.listener(Self::add_folder_to_project))
 6926            .on_action(cx.listener(Self::follow_next_collaborator))
 6927            .on_action(cx.listener(Self::activate_pane_at_index))
 6928            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6929            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6930            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6931            .on_action(cx.listener(Self::toggle_theme_mode))
 6932            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6933                let pane = workspace.active_pane().clone();
 6934                workspace.unfollow_in_pane(&pane, window, cx);
 6935            }))
 6936            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6937                workspace
 6938                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6939                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6940            }))
 6941            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6942                workspace
 6943                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6944                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6945            }))
 6946            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6947                workspace
 6948                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6949                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6950            }))
 6951            .on_action(
 6952                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6953                    workspace.activate_previous_pane(window, cx)
 6954                }),
 6955            )
 6956            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6957                workspace.activate_next_pane(window, cx)
 6958            }))
 6959            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6960                workspace.activate_last_pane(window, cx)
 6961            }))
 6962            .on_action(
 6963                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6964                    workspace.activate_next_window(cx)
 6965                }),
 6966            )
 6967            .on_action(
 6968                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6969                    workspace.activate_previous_window(cx)
 6970                }),
 6971            )
 6972            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6973                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6974            }))
 6975            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6976                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6977            }))
 6978            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6979                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6980            }))
 6981            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6982                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6983            }))
 6984            .on_action(cx.listener(
 6985                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6986                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6987                },
 6988            ))
 6989            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6990                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6991            }))
 6992            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6993                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6994            }))
 6995            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6996                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6997            }))
 6998            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6999                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 7000            }))
 7001            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 7002                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 7003                    SplitDirection::Down,
 7004                    SplitDirection::Up,
 7005                    SplitDirection::Right,
 7006                    SplitDirection::Left,
 7007                ];
 7008                for dir in DIRECTION_PRIORITY {
 7009                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 7010                        workspace.swap_pane_in_direction(dir, cx);
 7011                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 7012                        break;
 7013                    }
 7014                }
 7015            }))
 7016            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 7017                workspace.move_pane_to_border(SplitDirection::Left, cx)
 7018            }))
 7019            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 7020                workspace.move_pane_to_border(SplitDirection::Right, cx)
 7021            }))
 7022            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 7023                workspace.move_pane_to_border(SplitDirection::Up, cx)
 7024            }))
 7025            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 7026                workspace.move_pane_to_border(SplitDirection::Down, cx)
 7027            }))
 7028            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 7029                this.toggle_dock(DockPosition::Left, window, cx);
 7030            }))
 7031            .on_action(cx.listener(
 7032                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 7033                    workspace.toggle_dock(DockPosition::Right, window, cx);
 7034                },
 7035            ))
 7036            .on_action(cx.listener(
 7037                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 7038                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 7039                },
 7040            ))
 7041            .on_action(cx.listener(
 7042                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 7043                    if !workspace.close_active_dock(window, cx) {
 7044                        cx.propagate();
 7045                    }
 7046                },
 7047            ))
 7048            .on_action(
 7049                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 7050                    workspace.close_all_docks(window, cx);
 7051                }),
 7052            )
 7053            .on_action(cx.listener(Self::toggle_all_docks))
 7054            .on_action(cx.listener(
 7055                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 7056                    workspace.clear_all_notifications(cx);
 7057                },
 7058            ))
 7059            .on_action(cx.listener(
 7060                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 7061                    workspace.clear_navigation_history(window, cx);
 7062                },
 7063            ))
 7064            .on_action(cx.listener(
 7065                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 7066                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 7067                        workspace.suppress_notification(&notification_id, cx);
 7068                    }
 7069                },
 7070            ))
 7071            .on_action(cx.listener(
 7072                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 7073                    workspace.show_worktree_trust_security_modal(true, window, cx);
 7074                },
 7075            ))
 7076            .on_action(
 7077                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 7078                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 7079                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 7080                            trusted_worktrees.clear_trusted_paths()
 7081                        });
 7082                        let db = WorkspaceDb::global(cx);
 7083                        cx.spawn(async move |_, cx| {
 7084                            if db.clear_trusted_worktrees().await.log_err().is_some() {
 7085                                cx.update(|cx| reload(cx));
 7086                            }
 7087                        })
 7088                        .detach();
 7089                    }
 7090                }),
 7091            )
 7092            .on_action(cx.listener(
 7093                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 7094                    workspace.reopen_closed_item(window, cx).detach();
 7095                },
 7096            ))
 7097            .on_action(cx.listener(
 7098                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 7099                    for dock in workspace.all_docks() {
 7100                        if dock.focus_handle(cx).contains_focused(window, cx) {
 7101                            let panel = dock.read(cx).active_panel().cloned();
 7102                            if let Some(panel) = panel {
 7103                                dock.update(cx, |dock, cx| {
 7104                                    dock.set_panel_size_state(
 7105                                        panel.as_ref(),
 7106                                        dock::PanelSizeState::default(),
 7107                                        cx,
 7108                                    );
 7109                                });
 7110                            }
 7111                            return;
 7112                        }
 7113                    }
 7114                },
 7115            ))
 7116            .on_action(cx.listener(
 7117                |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
 7118                    for dock in workspace.all_docks() {
 7119                        let panel = dock.read(cx).visible_panel().cloned();
 7120                        if let Some(panel) = panel {
 7121                            dock.update(cx, |dock, cx| {
 7122                                dock.set_panel_size_state(
 7123                                    panel.as_ref(),
 7124                                    dock::PanelSizeState::default(),
 7125                                    cx,
 7126                                );
 7127                            });
 7128                        }
 7129                    }
 7130                },
 7131            ))
 7132            .on_action(cx.listener(
 7133                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 7134                    adjust_active_dock_size_by_px(
 7135                        px_with_ui_font_fallback(act.px, cx),
 7136                        workspace,
 7137                        window,
 7138                        cx,
 7139                    );
 7140                },
 7141            ))
 7142            .on_action(cx.listener(
 7143                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 7144                    adjust_active_dock_size_by_px(
 7145                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7146                        workspace,
 7147                        window,
 7148                        cx,
 7149                    );
 7150                },
 7151            ))
 7152            .on_action(cx.listener(
 7153                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 7154                    adjust_open_docks_size_by_px(
 7155                        px_with_ui_font_fallback(act.px, cx),
 7156                        workspace,
 7157                        window,
 7158                        cx,
 7159                    );
 7160                },
 7161            ))
 7162            .on_action(cx.listener(
 7163                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 7164                    adjust_open_docks_size_by_px(
 7165                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7166                        workspace,
 7167                        window,
 7168                        cx,
 7169                    );
 7170                },
 7171            ))
 7172            .on_action(cx.listener(Workspace::toggle_centered_layout))
 7173            .on_action(cx.listener(
 7174                |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
 7175                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7176                        let dock = active_dock.read(cx);
 7177                        if let Some(active_panel) = dock.active_panel() {
 7178                            if active_panel.pane(cx).is_none() {
 7179                                let mut recent_pane: Option<Entity<Pane>> = None;
 7180                                let mut recent_timestamp = 0;
 7181                                for pane_handle in workspace.panes() {
 7182                                    let pane = pane_handle.read(cx);
 7183                                    for entry in pane.activation_history() {
 7184                                        if entry.timestamp > recent_timestamp {
 7185                                            recent_timestamp = entry.timestamp;
 7186                                            recent_pane = Some(pane_handle.clone());
 7187                                        }
 7188                                    }
 7189                                }
 7190
 7191                                if let Some(pane) = recent_pane {
 7192                                    let wrap_around = action.wrap_around;
 7193                                    pane.update(cx, |pane, cx| {
 7194                                        let current_index = pane.active_item_index();
 7195                                        let items_len = pane.items_len();
 7196                                        if items_len > 0 {
 7197                                            let next_index = if current_index + 1 < items_len {
 7198                                                current_index + 1
 7199                                            } else if wrap_around {
 7200                                                0
 7201                                            } else {
 7202                                                return;
 7203                                            };
 7204                                            pane.activate_item(
 7205                                                next_index, false, false, window, cx,
 7206                                            );
 7207                                        }
 7208                                    });
 7209                                    return;
 7210                                }
 7211                            }
 7212                        }
 7213                    }
 7214                    cx.propagate();
 7215                },
 7216            ))
 7217            .on_action(cx.listener(
 7218                |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
 7219                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7220                        let dock = active_dock.read(cx);
 7221                        if let Some(active_panel) = dock.active_panel() {
 7222                            if active_panel.pane(cx).is_none() {
 7223                                let mut recent_pane: Option<Entity<Pane>> = None;
 7224                                let mut recent_timestamp = 0;
 7225                                for pane_handle in workspace.panes() {
 7226                                    let pane = pane_handle.read(cx);
 7227                                    for entry in pane.activation_history() {
 7228                                        if entry.timestamp > recent_timestamp {
 7229                                            recent_timestamp = entry.timestamp;
 7230                                            recent_pane = Some(pane_handle.clone());
 7231                                        }
 7232                                    }
 7233                                }
 7234
 7235                                if let Some(pane) = recent_pane {
 7236                                    let wrap_around = action.wrap_around;
 7237                                    pane.update(cx, |pane, cx| {
 7238                                        let current_index = pane.active_item_index();
 7239                                        let items_len = pane.items_len();
 7240                                        if items_len > 0 {
 7241                                            let prev_index = if current_index > 0 {
 7242                                                current_index - 1
 7243                                            } else if wrap_around {
 7244                                                items_len.saturating_sub(1)
 7245                                            } else {
 7246                                                return;
 7247                                            };
 7248                                            pane.activate_item(
 7249                                                prev_index, false, false, window, cx,
 7250                                            );
 7251                                        }
 7252                                    });
 7253                                    return;
 7254                                }
 7255                            }
 7256                        }
 7257                    }
 7258                    cx.propagate();
 7259                },
 7260            ))
 7261            .on_action(cx.listener(
 7262                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 7263                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7264                        let dock = active_dock.read(cx);
 7265                        if let Some(active_panel) = dock.active_panel() {
 7266                            if active_panel.pane(cx).is_none() {
 7267                                let active_pane = workspace.active_pane().clone();
 7268                                active_pane.update(cx, |pane, cx| {
 7269                                    pane.close_active_item(action, window, cx)
 7270                                        .detach_and_log_err(cx);
 7271                                });
 7272                                return;
 7273                            }
 7274                        }
 7275                    }
 7276                    cx.propagate();
 7277                },
 7278            ))
 7279            .on_action(
 7280                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 7281                    let pane = workspace.active_pane().clone();
 7282                    if let Some(item) = pane.read(cx).active_item() {
 7283                        item.toggle_read_only(window, cx);
 7284                    }
 7285                }),
 7286            )
 7287            .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
 7288                workspace.focus_center_pane(window, cx);
 7289            }))
 7290            .on_action(cx.listener(Workspace::cancel))
 7291    }
 7292
 7293    #[cfg(any(test, feature = "test-support"))]
 7294    pub fn set_random_database_id(&mut self) {
 7295        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 7296    }
 7297
 7298    #[cfg(any(test, feature = "test-support"))]
 7299    pub(crate) fn test_new(
 7300        project: Entity<Project>,
 7301        window: &mut Window,
 7302        cx: &mut Context<Self>,
 7303    ) -> Self {
 7304        use node_runtime::NodeRuntime;
 7305        use session::Session;
 7306
 7307        let client = project.read(cx).client();
 7308        let user_store = project.read(cx).user_store();
 7309        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 7310        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 7311        window.activate_window();
 7312        let app_state = Arc::new(AppState {
 7313            languages: project.read(cx).languages().clone(),
 7314            workspace_store,
 7315            client,
 7316            user_store,
 7317            fs: project.read(cx).fs().clone(),
 7318            build_window_options: |_, _| Default::default(),
 7319            node_runtime: NodeRuntime::unavailable(),
 7320            session,
 7321        });
 7322        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 7323        workspace
 7324            .active_pane
 7325            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 7326        workspace
 7327    }
 7328
 7329    pub fn register_action<A: Action>(
 7330        &mut self,
 7331        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 7332    ) -> &mut Self {
 7333        let callback = Arc::new(callback);
 7334
 7335        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 7336            let callback = callback.clone();
 7337            div.on_action(cx.listener(move |workspace, event, window, cx| {
 7338                (callback)(workspace, event, window, cx)
 7339            }))
 7340        }));
 7341        self
 7342    }
 7343    pub fn register_action_renderer(
 7344        &mut self,
 7345        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 7346    ) -> &mut Self {
 7347        self.workspace_actions.push(Box::new(callback));
 7348        self
 7349    }
 7350
 7351    fn add_workspace_actions_listeners(
 7352        &self,
 7353        mut div: Div,
 7354        window: &mut Window,
 7355        cx: &mut Context<Self>,
 7356    ) -> Div {
 7357        for action in self.workspace_actions.iter() {
 7358            div = (action)(div, self, window, cx)
 7359        }
 7360        div
 7361    }
 7362
 7363    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 7364        self.modal_layer.read(cx).has_active_modal()
 7365    }
 7366
 7367    pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
 7368        self.modal_layer
 7369            .read(cx)
 7370            .is_active_modal_command_palette(cx)
 7371    }
 7372
 7373    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7374        self.modal_layer.read(cx).active_modal()
 7375    }
 7376
 7377    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7378    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7379    /// If no modal is active, the new modal will be shown.
 7380    ///
 7381    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7382    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7383    /// will not be shown.
 7384    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7385    where
 7386        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7387    {
 7388        self.modal_layer.update(cx, |modal_layer, cx| {
 7389            modal_layer.toggle_modal(window, cx, build)
 7390        })
 7391    }
 7392
 7393    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7394        self.modal_layer
 7395            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7396    }
 7397
 7398    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7399        self.toast_layer
 7400            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7401    }
 7402
 7403    pub fn toggle_centered_layout(
 7404        &mut self,
 7405        _: &ToggleCenteredLayout,
 7406        _: &mut Window,
 7407        cx: &mut Context<Self>,
 7408    ) {
 7409        self.centered_layout = !self.centered_layout;
 7410        if let Some(database_id) = self.database_id() {
 7411            let db = WorkspaceDb::global(cx);
 7412            let centered_layout = self.centered_layout;
 7413            cx.background_spawn(async move {
 7414                db.set_centered_layout(database_id, centered_layout).await
 7415            })
 7416            .detach_and_log_err(cx);
 7417        }
 7418        cx.notify();
 7419    }
 7420
 7421    fn adjust_padding(padding: Option<f32>) -> f32 {
 7422        padding
 7423            .unwrap_or(CenteredPaddingSettings::default().0)
 7424            .clamp(
 7425                CenteredPaddingSettings::MIN_PADDING,
 7426                CenteredPaddingSettings::MAX_PADDING,
 7427            )
 7428    }
 7429
 7430    fn render_dock(
 7431        &self,
 7432        position: DockPosition,
 7433        dock: &Entity<Dock>,
 7434        window: &mut Window,
 7435        cx: &mut App,
 7436    ) -> Option<Div> {
 7437        if self.zoomed_position == Some(position) {
 7438            return None;
 7439        }
 7440
 7441        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7442            let pane = panel.pane(cx)?;
 7443            let follower_states = &self.follower_states;
 7444            leader_border_for_pane(follower_states, &pane, window, cx)
 7445        });
 7446
 7447        let mut container = div()
 7448            .flex()
 7449            .overflow_hidden()
 7450            .flex_none()
 7451            .child(dock.clone())
 7452            .children(leader_border);
 7453
 7454        // Apply sizing only when the dock is open. When closed the dock is still
 7455        // included in the element tree so its focus handle remains mounted — without
 7456        // this, toggle_panel_focus cannot focus the panel when the dock is closed.
 7457        let dock = dock.read(cx);
 7458        if let Some(panel) = dock.visible_panel() {
 7459            let size_state = dock.stored_panel_size_state(panel.as_ref());
 7460            let min_size = panel.min_size(window, cx);
 7461            if position.axis() == Axis::Horizontal {
 7462                let use_flexible = panel.has_flexible_size(window, cx);
 7463                let flex_grow = if use_flexible {
 7464                    size_state
 7465                        .and_then(|state| state.flex)
 7466                        .or_else(|| self.default_dock_flex(position))
 7467                } else {
 7468                    None
 7469                };
 7470                if let Some(grow) = flex_grow {
 7471                    let grow = grow.max(0.001);
 7472                    let style = container.style();
 7473                    style.flex_grow = Some(grow);
 7474                    style.flex_shrink = Some(1.0);
 7475                    style.flex_basis = Some(relative(0.).into());
 7476                } else {
 7477                    let size = size_state
 7478                        .and_then(|state| state.size)
 7479                        .unwrap_or_else(|| panel.default_size(window, cx));
 7480                    container = container.w(size);
 7481                }
 7482                if let Some(min) = min_size {
 7483                    container = container.min_w(min);
 7484                }
 7485            } else {
 7486                let size = size_state
 7487                    .and_then(|state| state.size)
 7488                    .unwrap_or_else(|| panel.default_size(window, cx));
 7489                container = container.h(size);
 7490            }
 7491        }
 7492
 7493        Some(container)
 7494    }
 7495
 7496    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7497        window
 7498            .root::<MultiWorkspace>()
 7499            .flatten()
 7500            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7501    }
 7502
 7503    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7504        self.zoomed.as_ref()
 7505    }
 7506
 7507    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7508        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7509            return;
 7510        };
 7511        let windows = cx.windows();
 7512        let next_window =
 7513            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7514                || {
 7515                    windows
 7516                        .iter()
 7517                        .cycle()
 7518                        .skip_while(|window| window.window_id() != current_window_id)
 7519                        .nth(1)
 7520                },
 7521            );
 7522
 7523        if let Some(window) = next_window {
 7524            window
 7525                .update(cx, |_, window, _| window.activate_window())
 7526                .ok();
 7527        }
 7528    }
 7529
 7530    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7531        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7532            return;
 7533        };
 7534        let windows = cx.windows();
 7535        let prev_window =
 7536            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7537                || {
 7538                    windows
 7539                        .iter()
 7540                        .rev()
 7541                        .cycle()
 7542                        .skip_while(|window| window.window_id() != current_window_id)
 7543                        .nth(1)
 7544                },
 7545            );
 7546
 7547        if let Some(window) = prev_window {
 7548            window
 7549                .update(cx, |_, window, _| window.activate_window())
 7550                .ok();
 7551        }
 7552    }
 7553
 7554    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7555        if cx.stop_active_drag(window) {
 7556        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7557            dismiss_app_notification(&notification_id, cx);
 7558        } else {
 7559            cx.propagate();
 7560        }
 7561    }
 7562
 7563    fn resize_dock(
 7564        &mut self,
 7565        dock_pos: DockPosition,
 7566        new_size: Pixels,
 7567        window: &mut Window,
 7568        cx: &mut Context<Self>,
 7569    ) {
 7570        match dock_pos {
 7571            DockPosition::Left => self.resize_left_dock(new_size, window, cx),
 7572            DockPosition::Right => self.resize_right_dock(new_size, window, cx),
 7573            DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
 7574        }
 7575    }
 7576
 7577    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7578        let workspace_width = self.bounds.size.width;
 7579        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7580
 7581        self.right_dock.read_with(cx, |right_dock, cx| {
 7582            let right_dock_size = right_dock
 7583                .stored_active_panel_size(window, cx)
 7584                .unwrap_or(Pixels::ZERO);
 7585            if right_dock_size + size > workspace_width {
 7586                size = workspace_width - right_dock_size
 7587            }
 7588        });
 7589
 7590        let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
 7591        self.left_dock.update(cx, |left_dock, cx| {
 7592            if WorkspaceSettings::get_global(cx)
 7593                .resize_all_panels_in_dock
 7594                .contains(&DockPosition::Left)
 7595            {
 7596                left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7597            } else {
 7598                left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7599            }
 7600        });
 7601    }
 7602
 7603    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7604        let workspace_width = self.bounds.size.width;
 7605        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7606        self.left_dock.read_with(cx, |left_dock, cx| {
 7607            let left_dock_size = left_dock
 7608                .stored_active_panel_size(window, cx)
 7609                .unwrap_or(Pixels::ZERO);
 7610            if left_dock_size + size > workspace_width {
 7611                size = workspace_width - left_dock_size
 7612            }
 7613        });
 7614        let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
 7615        self.right_dock.update(cx, |right_dock, cx| {
 7616            if WorkspaceSettings::get_global(cx)
 7617                .resize_all_panels_in_dock
 7618                .contains(&DockPosition::Right)
 7619            {
 7620                right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7621            } else {
 7622                right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7623            }
 7624        });
 7625    }
 7626
 7627    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7628        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7629        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7630            if WorkspaceSettings::get_global(cx)
 7631                .resize_all_panels_in_dock
 7632                .contains(&DockPosition::Bottom)
 7633            {
 7634                bottom_dock.resize_all_panels(Some(size), None, window, cx);
 7635            } else {
 7636                bottom_dock.resize_active_panel(Some(size), None, window, cx);
 7637            }
 7638        });
 7639    }
 7640
 7641    fn toggle_edit_predictions_all_files(
 7642        &mut self,
 7643        _: &ToggleEditPrediction,
 7644        _window: &mut Window,
 7645        cx: &mut Context<Self>,
 7646    ) {
 7647        let fs = self.project().read(cx).fs().clone();
 7648        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7649        update_settings_file(fs, cx, move |file, _| {
 7650            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7651        });
 7652    }
 7653
 7654    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7655        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7656        let next_mode = match current_mode {
 7657            Some(theme_settings::ThemeAppearanceMode::Light) => {
 7658                theme_settings::ThemeAppearanceMode::Dark
 7659            }
 7660            Some(theme_settings::ThemeAppearanceMode::Dark) => {
 7661                theme_settings::ThemeAppearanceMode::Light
 7662            }
 7663            Some(theme_settings::ThemeAppearanceMode::System) | None => {
 7664                match cx.theme().appearance() {
 7665                    theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
 7666                    theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
 7667                }
 7668            }
 7669        };
 7670
 7671        let fs = self.project().read(cx).fs().clone();
 7672        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7673            theme_settings::set_mode(settings, next_mode);
 7674        });
 7675    }
 7676
 7677    pub fn show_worktree_trust_security_modal(
 7678        &mut self,
 7679        toggle: bool,
 7680        window: &mut Window,
 7681        cx: &mut Context<Self>,
 7682    ) {
 7683        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7684            if toggle {
 7685                security_modal.update(cx, |security_modal, cx| {
 7686                    security_modal.dismiss(cx);
 7687                })
 7688            } else {
 7689                security_modal.update(cx, |security_modal, cx| {
 7690                    security_modal.refresh_restricted_paths(cx);
 7691                });
 7692            }
 7693        } else {
 7694            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7695                .map(|trusted_worktrees| {
 7696                    trusted_worktrees
 7697                        .read(cx)
 7698                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7699                })
 7700                .unwrap_or(false);
 7701            if has_restricted_worktrees {
 7702                let project = self.project().read(cx);
 7703                let remote_host = project
 7704                    .remote_connection_options(cx)
 7705                    .map(RemoteHostLocation::from);
 7706                let worktree_store = project.worktree_store().downgrade();
 7707                self.toggle_modal(window, cx, |_, cx| {
 7708                    SecurityModal::new(worktree_store, remote_host, cx)
 7709                });
 7710            }
 7711        }
 7712    }
 7713}
 7714
 7715pub trait AnyActiveCall {
 7716    fn entity(&self) -> AnyEntity;
 7717    fn is_in_room(&self, _: &App) -> bool;
 7718    fn room_id(&self, _: &App) -> Option<u64>;
 7719    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7720    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7721    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7722    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7723    fn is_sharing_project(&self, _: &App) -> bool;
 7724    fn has_remote_participants(&self, _: &App) -> bool;
 7725    fn local_participant_is_guest(&self, _: &App) -> bool;
 7726    fn client(&self, _: &App) -> Arc<Client>;
 7727    fn share_on_join(&self, _: &App) -> bool;
 7728    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7729    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7730    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7731    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7732    fn join_project(
 7733        &self,
 7734        _: u64,
 7735        _: Arc<LanguageRegistry>,
 7736        _: Arc<dyn Fs>,
 7737        _: &mut App,
 7738    ) -> Task<Result<Entity<Project>>>;
 7739    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7740    fn subscribe(
 7741        &self,
 7742        _: &mut Window,
 7743        _: &mut Context<Workspace>,
 7744        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7745    ) -> Subscription;
 7746    fn create_shared_screen(
 7747        &self,
 7748        _: PeerId,
 7749        _: &Entity<Pane>,
 7750        _: &mut Window,
 7751        _: &mut App,
 7752    ) -> Option<Entity<SharedScreen>>;
 7753}
 7754
 7755#[derive(Clone)]
 7756pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7757impl Global for GlobalAnyActiveCall {}
 7758
 7759impl GlobalAnyActiveCall {
 7760    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7761        cx.try_global()
 7762    }
 7763
 7764    pub(crate) fn global(cx: &App) -> &Self {
 7765        cx.global()
 7766    }
 7767}
 7768
 7769/// Workspace-local view of a remote participant's location.
 7770#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7771pub enum ParticipantLocation {
 7772    SharedProject { project_id: u64 },
 7773    UnsharedProject,
 7774    External,
 7775}
 7776
 7777impl ParticipantLocation {
 7778    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7779        match location
 7780            .and_then(|l| l.variant)
 7781            .context("participant location was not provided")?
 7782        {
 7783            proto::participant_location::Variant::SharedProject(project) => {
 7784                Ok(Self::SharedProject {
 7785                    project_id: project.id,
 7786                })
 7787            }
 7788            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7789            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7790        }
 7791    }
 7792}
 7793/// Workspace-local view of a remote collaborator's state.
 7794/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7795#[derive(Clone)]
 7796pub struct RemoteCollaborator {
 7797    pub user: Arc<User>,
 7798    pub peer_id: PeerId,
 7799    pub location: ParticipantLocation,
 7800    pub participant_index: ParticipantIndex,
 7801}
 7802
 7803pub enum ActiveCallEvent {
 7804    ParticipantLocationChanged { participant_id: PeerId },
 7805    RemoteVideoTracksChanged { participant_id: PeerId },
 7806}
 7807
 7808fn leader_border_for_pane(
 7809    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7810    pane: &Entity<Pane>,
 7811    _: &Window,
 7812    cx: &App,
 7813) -> Option<Div> {
 7814    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7815        if state.pane() == pane {
 7816            Some((*leader_id, state))
 7817        } else {
 7818            None
 7819        }
 7820    })?;
 7821
 7822    let mut leader_color = match leader_id {
 7823        CollaboratorId::PeerId(leader_peer_id) => {
 7824            let leader = GlobalAnyActiveCall::try_global(cx)?
 7825                .0
 7826                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7827
 7828            cx.theme()
 7829                .players()
 7830                .color_for_participant(leader.participant_index.0)
 7831                .cursor
 7832        }
 7833        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7834    };
 7835    leader_color.fade_out(0.3);
 7836    Some(
 7837        div()
 7838            .absolute()
 7839            .size_full()
 7840            .left_0()
 7841            .top_0()
 7842            .border_2()
 7843            .border_color(leader_color),
 7844    )
 7845}
 7846
 7847fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7848    ZED_WINDOW_POSITION
 7849        .zip(*ZED_WINDOW_SIZE)
 7850        .map(|(position, size)| Bounds {
 7851            origin: position,
 7852            size,
 7853        })
 7854}
 7855
 7856fn open_items(
 7857    serialized_workspace: Option<SerializedWorkspace>,
 7858    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7859    window: &mut Window,
 7860    cx: &mut Context<Workspace>,
 7861) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7862    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7863        Workspace::load_workspace(
 7864            serialized_workspace,
 7865            project_paths_to_open
 7866                .iter()
 7867                .map(|(_, project_path)| project_path)
 7868                .cloned()
 7869                .collect(),
 7870            window,
 7871            cx,
 7872        )
 7873    });
 7874
 7875    cx.spawn_in(window, async move |workspace, cx| {
 7876        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7877
 7878        if let Some(restored_items) = restored_items {
 7879            let restored_items = restored_items.await?;
 7880
 7881            let restored_project_paths = restored_items
 7882                .iter()
 7883                .filter_map(|item| {
 7884                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7885                        .ok()
 7886                        .flatten()
 7887                })
 7888                .collect::<HashSet<_>>();
 7889
 7890            for restored_item in restored_items {
 7891                opened_items.push(restored_item.map(Ok));
 7892            }
 7893
 7894            project_paths_to_open
 7895                .iter_mut()
 7896                .for_each(|(_, project_path)| {
 7897                    if let Some(project_path_to_open) = project_path
 7898                        && restored_project_paths.contains(project_path_to_open)
 7899                    {
 7900                        *project_path = None;
 7901                    }
 7902                });
 7903        } else {
 7904            for _ in 0..project_paths_to_open.len() {
 7905                opened_items.push(None);
 7906            }
 7907        }
 7908        assert!(opened_items.len() == project_paths_to_open.len());
 7909
 7910        let tasks =
 7911            project_paths_to_open
 7912                .into_iter()
 7913                .enumerate()
 7914                .map(|(ix, (abs_path, project_path))| {
 7915                    let workspace = workspace.clone();
 7916                    cx.spawn(async move |cx| {
 7917                        let file_project_path = project_path?;
 7918                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7919                            workspace.project().update(cx, |project, cx| {
 7920                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7921                            })
 7922                        });
 7923
 7924                        // We only want to open file paths here. If one of the items
 7925                        // here is a directory, it was already opened further above
 7926                        // with a `find_or_create_worktree`.
 7927                        if let Ok(task) = abs_path_task
 7928                            && task.await.is_none_or(|p| p.is_file())
 7929                        {
 7930                            return Some((
 7931                                ix,
 7932                                workspace
 7933                                    .update_in(cx, |workspace, window, cx| {
 7934                                        workspace.open_path(
 7935                                            file_project_path,
 7936                                            None,
 7937                                            true,
 7938                                            window,
 7939                                            cx,
 7940                                        )
 7941                                    })
 7942                                    .log_err()?
 7943                                    .await,
 7944                            ));
 7945                        }
 7946                        None
 7947                    })
 7948                });
 7949
 7950        let tasks = tasks.collect::<Vec<_>>();
 7951
 7952        let tasks = futures::future::join_all(tasks);
 7953        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7954            opened_items[ix] = Some(path_open_result);
 7955        }
 7956
 7957        Ok(opened_items)
 7958    })
 7959}
 7960
 7961#[derive(Clone)]
 7962enum ActivateInDirectionTarget {
 7963    Pane(Entity<Pane>),
 7964    Dock(Entity<Dock>),
 7965    Sidebar(FocusHandle),
 7966}
 7967
 7968fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7969    window
 7970        .update(cx, |multi_workspace, _, cx| {
 7971            let workspace = multi_workspace.workspace().clone();
 7972            workspace.update(cx, |workspace, cx| {
 7973                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7974                    struct DatabaseFailedNotification;
 7975
 7976                    workspace.show_notification(
 7977                        NotificationId::unique::<DatabaseFailedNotification>(),
 7978                        cx,
 7979                        |cx| {
 7980                            cx.new(|cx| {
 7981                                MessageNotification::new("Failed to load the database file.", cx)
 7982                                    .primary_message("File an Issue")
 7983                                    .primary_icon(IconName::Plus)
 7984                                    .primary_on_click(|window, cx| {
 7985                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7986                                    })
 7987                            })
 7988                        },
 7989                    );
 7990                }
 7991            });
 7992        })
 7993        .log_err();
 7994}
 7995
 7996fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7997    if val == 0 {
 7998        ThemeSettings::get_global(cx).ui_font_size(cx)
 7999    } else {
 8000        px(val as f32)
 8001    }
 8002}
 8003
 8004fn adjust_active_dock_size_by_px(
 8005    px: Pixels,
 8006    workspace: &mut Workspace,
 8007    window: &mut Window,
 8008    cx: &mut Context<Workspace>,
 8009) {
 8010    let Some(active_dock) = workspace
 8011        .all_docks()
 8012        .into_iter()
 8013        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 8014    else {
 8015        return;
 8016    };
 8017    let dock = active_dock.read(cx);
 8018    let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
 8019        return;
 8020    };
 8021    workspace.resize_dock(dock.position(), panel_size + px, window, cx);
 8022}
 8023
 8024fn adjust_open_docks_size_by_px(
 8025    px: Pixels,
 8026    workspace: &mut Workspace,
 8027    window: &mut Window,
 8028    cx: &mut Context<Workspace>,
 8029) {
 8030    let docks = workspace
 8031        .all_docks()
 8032        .into_iter()
 8033        .filter_map(|dock_entity| {
 8034            let dock = dock_entity.read(cx);
 8035            if dock.is_open() {
 8036                let dock_pos = dock.position();
 8037                let panel_size = workspace.dock_size(&dock, window, cx)?;
 8038                Some((dock_pos, panel_size + px))
 8039            } else {
 8040                None
 8041            }
 8042        })
 8043        .collect::<Vec<_>>();
 8044
 8045    for (position, new_size) in docks {
 8046        workspace.resize_dock(position, new_size, window, cx);
 8047    }
 8048}
 8049
 8050impl Focusable for Workspace {
 8051    fn focus_handle(&self, cx: &App) -> FocusHandle {
 8052        self.active_pane.focus_handle(cx)
 8053    }
 8054}
 8055
 8056#[derive(Clone)]
 8057struct DraggedDock(DockPosition);
 8058
 8059impl Render for DraggedDock {
 8060    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 8061        gpui::Empty
 8062    }
 8063}
 8064
 8065impl Render for Workspace {
 8066    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 8067        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 8068        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 8069            log::info!("Rendered first frame");
 8070        }
 8071
 8072        let centered_layout = self.centered_layout
 8073            && self.center.panes().len() == 1
 8074            && self.active_item(cx).is_some();
 8075        let render_padding = |size| {
 8076            (size > 0.0).then(|| {
 8077                div()
 8078                    .h_full()
 8079                    .w(relative(size))
 8080                    .bg(cx.theme().colors().editor_background)
 8081                    .border_color(cx.theme().colors().pane_group_border)
 8082            })
 8083        };
 8084        let paddings = if centered_layout {
 8085            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 8086            (
 8087                render_padding(Self::adjust_padding(
 8088                    settings.left_padding.map(|padding| padding.0),
 8089                )),
 8090                render_padding(Self::adjust_padding(
 8091                    settings.right_padding.map(|padding| padding.0),
 8092                )),
 8093            )
 8094        } else {
 8095            (None, None)
 8096        };
 8097        let ui_font = theme_settings::setup_ui_font(window, cx);
 8098
 8099        let theme = cx.theme().clone();
 8100        let colors = theme.colors();
 8101        let notification_entities = self
 8102            .notifications
 8103            .iter()
 8104            .map(|(_, notification)| notification.entity_id())
 8105            .collect::<Vec<_>>();
 8106        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 8107
 8108        div()
 8109            .relative()
 8110            .size_full()
 8111            .flex()
 8112            .flex_col()
 8113            .font(ui_font)
 8114            .gap_0()
 8115                .justify_start()
 8116                .items_start()
 8117                .text_color(colors.text)
 8118                .overflow_hidden()
 8119                .children(self.titlebar_item.clone())
 8120                .on_modifiers_changed(move |_, _, cx| {
 8121                    for &id in &notification_entities {
 8122                        cx.notify(id);
 8123                    }
 8124                })
 8125                .child(
 8126                    div()
 8127                        .size_full()
 8128                        .relative()
 8129                        .flex_1()
 8130                        .flex()
 8131                        .flex_col()
 8132                        .child(
 8133                            div()
 8134                                .id("workspace")
 8135                                .bg(colors.background)
 8136                                .relative()
 8137                                .flex_1()
 8138                                .w_full()
 8139                                .flex()
 8140                                .flex_col()
 8141                                .overflow_hidden()
 8142                                .border_t_1()
 8143                                .border_b_1()
 8144                                .border_color(colors.border)
 8145                                .child({
 8146                                    let this = cx.entity();
 8147                                    canvas(
 8148                                        move |bounds, window, cx| {
 8149                                            this.update(cx, |this, cx| {
 8150                                                let bounds_changed = this.bounds != bounds;
 8151                                                this.bounds = bounds;
 8152
 8153                                                if bounds_changed {
 8154                                                    this.left_dock.update(cx, |dock, cx| {
 8155                                                        dock.clamp_panel_size(
 8156                                                            bounds.size.width,
 8157                                                            window,
 8158                                                            cx,
 8159                                                        )
 8160                                                    });
 8161
 8162                                                    this.right_dock.update(cx, |dock, cx| {
 8163                                                        dock.clamp_panel_size(
 8164                                                            bounds.size.width,
 8165                                                            window,
 8166                                                            cx,
 8167                                                        )
 8168                                                    });
 8169
 8170                                                    this.bottom_dock.update(cx, |dock, cx| {
 8171                                                        dock.clamp_panel_size(
 8172                                                            bounds.size.height,
 8173                                                            window,
 8174                                                            cx,
 8175                                                        )
 8176                                                    });
 8177                                                }
 8178                                            })
 8179                                        },
 8180                                        |_, _, _, _| {},
 8181                                    )
 8182                                    .absolute()
 8183                                    .size_full()
 8184                                })
 8185                                .when(self.zoomed.is_none(), |this| {
 8186                                    this.on_drag_move(cx.listener(
 8187                                        move |workspace,
 8188                                              e: &DragMoveEvent<DraggedDock>,
 8189                                              window,
 8190                                              cx| {
 8191                                            if workspace.previous_dock_drag_coordinates
 8192                                                != Some(e.event.position)
 8193                                            {
 8194                                                workspace.previous_dock_drag_coordinates =
 8195                                                    Some(e.event.position);
 8196
 8197                                                match e.drag(cx).0 {
 8198                                                    DockPosition::Left => {
 8199                                                        workspace.resize_left_dock(
 8200                                                            e.event.position.x
 8201                                                                - workspace.bounds.left(),
 8202                                                            window,
 8203                                                            cx,
 8204                                                        );
 8205                                                    }
 8206                                                    DockPosition::Right => {
 8207                                                        workspace.resize_right_dock(
 8208                                                            workspace.bounds.right()
 8209                                                                - e.event.position.x,
 8210                                                            window,
 8211                                                            cx,
 8212                                                        );
 8213                                                    }
 8214                                                    DockPosition::Bottom => {
 8215                                                        workspace.resize_bottom_dock(
 8216                                                            workspace.bounds.bottom()
 8217                                                                - e.event.position.y,
 8218                                                            window,
 8219                                                            cx,
 8220                                                        );
 8221                                                    }
 8222                                                };
 8223                                                workspace.serialize_workspace(window, cx);
 8224                                            }
 8225                                        },
 8226                                    ))
 8227
 8228                                })
 8229                                .child({
 8230                                    match bottom_dock_layout {
 8231                                        BottomDockLayout::Full => div()
 8232                                            .flex()
 8233                                            .flex_col()
 8234                                            .h_full()
 8235                                            .child(
 8236                                                div()
 8237                                                    .flex()
 8238                                                    .flex_row()
 8239                                                    .flex_1()
 8240                                                    .overflow_hidden()
 8241                                                    .children(self.render_dock(
 8242                                                        DockPosition::Left,
 8243                                                        &self.left_dock,
 8244                                                        window,
 8245                                                        cx,
 8246                                                    ))
 8247
 8248                                                    .child(
 8249                                                        div()
 8250                                                            .flex()
 8251                                                            .flex_col()
 8252                                                            .flex_1()
 8253                                                            .overflow_hidden()
 8254                                                            .child(
 8255                                                                h_flex()
 8256                                                                    .flex_1()
 8257                                                                    .when_some(
 8258                                                                        paddings.0,
 8259                                                                        |this, p| {
 8260                                                                            this.child(
 8261                                                                                p.border_r_1(),
 8262                                                                            )
 8263                                                                        },
 8264                                                                    )
 8265                                                                    .child(self.center.render(
 8266                                                                        self.zoomed.as_ref(),
 8267                                                                        &PaneRenderContext {
 8268                                                                            follower_states:
 8269                                                                                &self.follower_states,
 8270                                                                            active_call: self.active_call(),
 8271                                                                            active_pane: &self.active_pane,
 8272                                                                            app_state: &self.app_state,
 8273                                                                            project: &self.project,
 8274                                                                            workspace: &self.weak_self,
 8275                                                                        },
 8276                                                                        window,
 8277                                                                        cx,
 8278                                                                    ))
 8279                                                                    .when_some(
 8280                                                                        paddings.1,
 8281                                                                        |this, p| {
 8282                                                                            this.child(
 8283                                                                                p.border_l_1(),
 8284                                                                            )
 8285                                                                        },
 8286                                                                    ),
 8287                                                            ),
 8288                                                    )
 8289
 8290                                                    .children(self.render_dock(
 8291                                                        DockPosition::Right,
 8292                                                        &self.right_dock,
 8293                                                        window,
 8294                                                        cx,
 8295                                                    )),
 8296                                            )
 8297                                            .child(div().w_full().children(self.render_dock(
 8298                                                DockPosition::Bottom,
 8299                                                &self.bottom_dock,
 8300                                                window,
 8301                                                cx
 8302                                            ))),
 8303
 8304                                        BottomDockLayout::LeftAligned => div()
 8305                                            .flex()
 8306                                            .flex_row()
 8307                                            .h_full()
 8308                                            .child(
 8309                                                div()
 8310                                                    .flex()
 8311                                                    .flex_col()
 8312                                                    .flex_1()
 8313                                                    .h_full()
 8314                                                    .child(
 8315                                                        div()
 8316                                                            .flex()
 8317                                                            .flex_row()
 8318                                                            .flex_1()
 8319                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 8320
 8321                                                            .child(
 8322                                                                div()
 8323                                                                    .flex()
 8324                                                                    .flex_col()
 8325                                                                    .flex_1()
 8326                                                                    .overflow_hidden()
 8327                                                                    .child(
 8328                                                                        h_flex()
 8329                                                                            .flex_1()
 8330                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8331                                                                            .child(self.center.render(
 8332                                                                                self.zoomed.as_ref(),
 8333                                                                                &PaneRenderContext {
 8334                                                                                    follower_states:
 8335                                                                                        &self.follower_states,
 8336                                                                                    active_call: self.active_call(),
 8337                                                                                    active_pane: &self.active_pane,
 8338                                                                                    app_state: &self.app_state,
 8339                                                                                    project: &self.project,
 8340                                                                                    workspace: &self.weak_self,
 8341                                                                                },
 8342                                                                                window,
 8343                                                                                cx,
 8344                                                                            ))
 8345                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8346                                                                    )
 8347                                                            )
 8348
 8349                                                    )
 8350                                                    .child(
 8351                                                        div()
 8352                                                            .w_full()
 8353                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8354                                                    ),
 8355                                            )
 8356                                            .children(self.render_dock(
 8357                                                DockPosition::Right,
 8358                                                &self.right_dock,
 8359                                                window,
 8360                                                cx,
 8361                                            )),
 8362                                        BottomDockLayout::RightAligned => div()
 8363                                            .flex()
 8364                                            .flex_row()
 8365                                            .h_full()
 8366                                            .children(self.render_dock(
 8367                                                DockPosition::Left,
 8368                                                &self.left_dock,
 8369                                                window,
 8370                                                cx,
 8371                                            ))
 8372
 8373                                            .child(
 8374                                                div()
 8375                                                    .flex()
 8376                                                    .flex_col()
 8377                                                    .flex_1()
 8378                                                    .h_full()
 8379                                                    .child(
 8380                                                        div()
 8381                                                            .flex()
 8382                                                            .flex_row()
 8383                                                            .flex_1()
 8384                                                            .child(
 8385                                                                div()
 8386                                                                    .flex()
 8387                                                                    .flex_col()
 8388                                                                    .flex_1()
 8389                                                                    .overflow_hidden()
 8390                                                                    .child(
 8391                                                                        h_flex()
 8392                                                                            .flex_1()
 8393                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8394                                                                            .child(self.center.render(
 8395                                                                                self.zoomed.as_ref(),
 8396                                                                                &PaneRenderContext {
 8397                                                                                    follower_states:
 8398                                                                                        &self.follower_states,
 8399                                                                                    active_call: self.active_call(),
 8400                                                                                    active_pane: &self.active_pane,
 8401                                                                                    app_state: &self.app_state,
 8402                                                                                    project: &self.project,
 8403                                                                                    workspace: &self.weak_self,
 8404                                                                                },
 8405                                                                                window,
 8406                                                                                cx,
 8407                                                                            ))
 8408                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8409                                                                    )
 8410                                                            )
 8411
 8412                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 8413                                                    )
 8414                                                    .child(
 8415                                                        div()
 8416                                                            .w_full()
 8417                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8418                                                    ),
 8419                                            ),
 8420                                        BottomDockLayout::Contained => div()
 8421                                            .flex()
 8422                                            .flex_row()
 8423                                            .h_full()
 8424                                            .children(self.render_dock(
 8425                                                DockPosition::Left,
 8426                                                &self.left_dock,
 8427                                                window,
 8428                                                cx,
 8429                                            ))
 8430
 8431                                            .child(
 8432                                                div()
 8433                                                    .flex()
 8434                                                    .flex_col()
 8435                                                    .flex_1()
 8436                                                    .overflow_hidden()
 8437                                                    .child(
 8438                                                        h_flex()
 8439                                                            .flex_1()
 8440                                                            .when_some(paddings.0, |this, p| {
 8441                                                                this.child(p.border_r_1())
 8442                                                            })
 8443                                                            .child(self.center.render(
 8444                                                                self.zoomed.as_ref(),
 8445                                                                &PaneRenderContext {
 8446                                                                    follower_states:
 8447                                                                        &self.follower_states,
 8448                                                                    active_call: self.active_call(),
 8449                                                                    active_pane: &self.active_pane,
 8450                                                                    app_state: &self.app_state,
 8451                                                                    project: &self.project,
 8452                                                                    workspace: &self.weak_self,
 8453                                                                },
 8454                                                                window,
 8455                                                                cx,
 8456                                                            ))
 8457                                                            .when_some(paddings.1, |this, p| {
 8458                                                                this.child(p.border_l_1())
 8459                                                            }),
 8460                                                    )
 8461                                                    .children(self.render_dock(
 8462                                                        DockPosition::Bottom,
 8463                                                        &self.bottom_dock,
 8464                                                        window,
 8465                                                        cx,
 8466                                                    )),
 8467                                            )
 8468
 8469                                            .children(self.render_dock(
 8470                                                DockPosition::Right,
 8471                                                &self.right_dock,
 8472                                                window,
 8473                                                cx,
 8474                                            )),
 8475                                    }
 8476                                })
 8477                                .children(self.zoomed.as_ref().and_then(|view| {
 8478                                    let zoomed_view = view.upgrade()?;
 8479                                    let div = div()
 8480                                        .occlude()
 8481                                        .absolute()
 8482                                        .overflow_hidden()
 8483                                        .border_color(colors.border)
 8484                                        .bg(colors.background)
 8485                                        .child(zoomed_view)
 8486                                        .inset_0()
 8487                                        .shadow_lg();
 8488
 8489                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8490                                       return Some(div);
 8491                                    }
 8492
 8493                                    Some(match self.zoomed_position {
 8494                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8495                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8496                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8497                                        None => {
 8498                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8499                                        }
 8500                                    })
 8501                                }))
 8502                                .children(self.render_notifications(window, cx)),
 8503                        )
 8504                        .when(self.status_bar_visible(cx), |parent| {
 8505                            parent.child(self.status_bar.clone())
 8506                        })
 8507                        .child(self.toast_layer.clone()),
 8508                )
 8509    }
 8510}
 8511
 8512impl WorkspaceStore {
 8513    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8514        Self {
 8515            workspaces: Default::default(),
 8516            _subscriptions: vec![
 8517                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8518                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8519            ],
 8520            client,
 8521        }
 8522    }
 8523
 8524    pub fn update_followers(
 8525        &self,
 8526        project_id: Option<u64>,
 8527        update: proto::update_followers::Variant,
 8528        cx: &App,
 8529    ) -> Option<()> {
 8530        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8531        let room_id = active_call.0.room_id(cx)?;
 8532        self.client
 8533            .send(proto::UpdateFollowers {
 8534                room_id,
 8535                project_id,
 8536                variant: Some(update),
 8537            })
 8538            .log_err()
 8539    }
 8540
 8541    pub async fn handle_follow(
 8542        this: Entity<Self>,
 8543        envelope: TypedEnvelope<proto::Follow>,
 8544        mut cx: AsyncApp,
 8545    ) -> Result<proto::FollowResponse> {
 8546        this.update(&mut cx, |this, cx| {
 8547            let follower = Follower {
 8548                project_id: envelope.payload.project_id,
 8549                peer_id: envelope.original_sender_id()?,
 8550            };
 8551
 8552            let mut response = proto::FollowResponse::default();
 8553
 8554            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8555                let Some(workspace) = weak_workspace.upgrade() else {
 8556                    return false;
 8557                };
 8558                window_handle
 8559                    .update(cx, |_, window, cx| {
 8560                        workspace.update(cx, |workspace, cx| {
 8561                            let handler_response =
 8562                                workspace.handle_follow(follower.project_id, window, cx);
 8563                            if let Some(active_view) = handler_response.active_view
 8564                                && workspace.project.read(cx).remote_id() == follower.project_id
 8565                            {
 8566                                response.active_view = Some(active_view)
 8567                            }
 8568                        });
 8569                    })
 8570                    .is_ok()
 8571            });
 8572
 8573            Ok(response)
 8574        })
 8575    }
 8576
 8577    async fn handle_update_followers(
 8578        this: Entity<Self>,
 8579        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8580        mut cx: AsyncApp,
 8581    ) -> Result<()> {
 8582        let leader_id = envelope.original_sender_id()?;
 8583        let update = envelope.payload;
 8584
 8585        this.update(&mut cx, |this, cx| {
 8586            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8587                let Some(workspace) = weak_workspace.upgrade() else {
 8588                    return false;
 8589                };
 8590                window_handle
 8591                    .update(cx, |_, window, cx| {
 8592                        workspace.update(cx, |workspace, cx| {
 8593                            let project_id = workspace.project.read(cx).remote_id();
 8594                            if update.project_id != project_id && update.project_id.is_some() {
 8595                                return;
 8596                            }
 8597                            workspace.handle_update_followers(
 8598                                leader_id,
 8599                                update.clone(),
 8600                                window,
 8601                                cx,
 8602                            );
 8603                        });
 8604                    })
 8605                    .is_ok()
 8606            });
 8607            Ok(())
 8608        })
 8609    }
 8610
 8611    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8612        self.workspaces.iter().map(|(_, weak)| weak)
 8613    }
 8614
 8615    pub fn workspaces_with_windows(
 8616        &self,
 8617    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8618        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8619    }
 8620}
 8621
 8622impl ViewId {
 8623    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8624        Ok(Self {
 8625            creator: message
 8626                .creator
 8627                .map(CollaboratorId::PeerId)
 8628                .context("creator is missing")?,
 8629            id: message.id,
 8630        })
 8631    }
 8632
 8633    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8634        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8635            Some(proto::ViewId {
 8636                creator: Some(peer_id),
 8637                id: self.id,
 8638            })
 8639        } else {
 8640            None
 8641        }
 8642    }
 8643}
 8644
 8645impl FollowerState {
 8646    fn pane(&self) -> &Entity<Pane> {
 8647        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8648    }
 8649}
 8650
 8651pub trait WorkspaceHandle {
 8652    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8653}
 8654
 8655impl WorkspaceHandle for Entity<Workspace> {
 8656    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8657        self.read(cx)
 8658            .worktrees(cx)
 8659            .flat_map(|worktree| {
 8660                let worktree_id = worktree.read(cx).id();
 8661                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8662                    worktree_id,
 8663                    path: f.path.clone(),
 8664                })
 8665            })
 8666            .collect::<Vec<_>>()
 8667    }
 8668}
 8669
 8670pub async fn last_opened_workspace_location(
 8671    db: &WorkspaceDb,
 8672    fs: &dyn fs::Fs,
 8673) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8674    db.last_workspace(fs)
 8675        .await
 8676        .log_err()
 8677        .flatten()
 8678        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8679}
 8680
 8681pub async fn last_session_workspace_locations(
 8682    db: &WorkspaceDb,
 8683    last_session_id: &str,
 8684    last_session_window_stack: Option<Vec<WindowId>>,
 8685    fs: &dyn fs::Fs,
 8686) -> Option<Vec<SessionWorkspace>> {
 8687    db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8688        .await
 8689        .log_err()
 8690}
 8691
 8692pub async fn restore_multiworkspace(
 8693    multi_workspace: SerializedMultiWorkspace,
 8694    app_state: Arc<AppState>,
 8695    cx: &mut AsyncApp,
 8696) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8697    let SerializedMultiWorkspace {
 8698        active_workspace,
 8699        state,
 8700    } = multi_workspace;
 8701
 8702    let workspace_result = if active_workspace.paths.is_empty() {
 8703        cx.update(|cx| {
 8704            open_workspace_by_id(active_workspace.workspace_id, app_state.clone(), None, cx)
 8705        })
 8706        .await
 8707    } else {
 8708        cx.update(|cx| {
 8709            Workspace::new_local(
 8710                active_workspace.paths.paths().to_vec(),
 8711                app_state.clone(),
 8712                None,
 8713                None,
 8714                None,
 8715                OpenMode::Activate,
 8716                cx,
 8717            )
 8718        })
 8719        .await
 8720        .map(|result| result.window)
 8721    };
 8722
 8723    let window_handle = match workspace_result {
 8724        Ok(handle) => handle,
 8725        Err(err) => {
 8726            log::error!("Failed to restore active workspace: {err:#}");
 8727
 8728            let mut fallback_handle = None;
 8729            for key in &state.project_group_keys {
 8730                let key: ProjectGroupKey = key.clone().into();
 8731                let paths = key.path_list().paths().to_vec();
 8732                match cx
 8733                    .update(|cx| {
 8734                        Workspace::new_local(
 8735                            paths,
 8736                            app_state.clone(),
 8737                            None,
 8738                            None,
 8739                            None,
 8740                            OpenMode::Activate,
 8741                            cx,
 8742                        )
 8743                    })
 8744                    .await
 8745                {
 8746                    Ok(OpenResult { window, .. }) => {
 8747                        fallback_handle = Some(window);
 8748                        break;
 8749                    }
 8750                    Err(fallback_err) => {
 8751                        log::error!("Fallback project group also failed: {fallback_err:#}");
 8752                    }
 8753                }
 8754            }
 8755
 8756            fallback_handle.ok_or(err)?
 8757        }
 8758    };
 8759
 8760    apply_restored_multiworkspace_state(window_handle, &state, app_state.fs.clone(), cx).await;
 8761
 8762    window_handle
 8763        .update(cx, |_, window, _cx| {
 8764            window.activate_window();
 8765        })
 8766        .ok();
 8767
 8768    Ok(window_handle)
 8769}
 8770
 8771pub async fn apply_restored_multiworkspace_state(
 8772    window_handle: WindowHandle<MultiWorkspace>,
 8773    state: &MultiWorkspaceState,
 8774    fs: Arc<dyn fs::Fs>,
 8775    cx: &mut AsyncApp,
 8776) {
 8777    let MultiWorkspaceState {
 8778        sidebar_open,
 8779        project_group_keys,
 8780        sidebar_state,
 8781        ..
 8782    } = state;
 8783
 8784    if !project_group_keys.is_empty() {
 8785        // Resolve linked worktree paths to their main repo paths so
 8786        // stale keys from previous sessions get normalized and deduped.
 8787        let mut resolved_keys: Vec<ProjectGroupKey> = Vec::new();
 8788        for key in project_group_keys
 8789            .iter()
 8790            .cloned()
 8791            .map(ProjectGroupKey::from)
 8792        {
 8793            if key.path_list().paths().is_empty() {
 8794                continue;
 8795            }
 8796            let mut resolved_paths = Vec::new();
 8797            for path in key.path_list().paths() {
 8798                if key.host().is_none()
 8799                    && let Some(common_dir) =
 8800                        project::discover_root_repo_common_dir(path, fs.as_ref()).await
 8801                {
 8802                    let main_path = common_dir.parent().unwrap_or(&common_dir);
 8803                    resolved_paths.push(main_path.to_path_buf());
 8804                } else {
 8805                    resolved_paths.push(path.to_path_buf());
 8806                }
 8807            }
 8808            let resolved = ProjectGroupKey::new(key.host(), PathList::new(&resolved_paths));
 8809            if !resolved_keys.contains(&resolved) {
 8810                resolved_keys.push(resolved);
 8811            }
 8812        }
 8813
 8814        window_handle
 8815            .update(cx, |multi_workspace, _window, _cx| {
 8816                multi_workspace.restore_project_group_keys(resolved_keys);
 8817            })
 8818            .ok();
 8819    }
 8820
 8821    if *sidebar_open {
 8822        window_handle
 8823            .update(cx, |multi_workspace, _, cx| {
 8824                multi_workspace.open_sidebar(cx);
 8825            })
 8826            .ok();
 8827    }
 8828
 8829    if let Some(sidebar_state) = sidebar_state {
 8830        window_handle
 8831            .update(cx, |multi_workspace, window, cx| {
 8832                if let Some(sidebar) = multi_workspace.sidebar() {
 8833                    sidebar.restore_serialized_state(sidebar_state, window, cx);
 8834                }
 8835                multi_workspace.serialize(cx);
 8836            })
 8837            .ok();
 8838    }
 8839}
 8840
 8841actions!(
 8842    collab,
 8843    [
 8844        /// Opens the channel notes for the current call.
 8845        ///
 8846        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8847        /// channel in the collab panel.
 8848        ///
 8849        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8850        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8851        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8852        OpenChannelNotes,
 8853        /// Mutes your microphone.
 8854        Mute,
 8855        /// Deafens yourself (mute both microphone and speakers).
 8856        Deafen,
 8857        /// Leaves the current call.
 8858        LeaveCall,
 8859        /// Shares the current project with collaborators.
 8860        ShareProject,
 8861        /// Shares your screen with collaborators.
 8862        ScreenShare,
 8863        /// Copies the current room name and session id for debugging purposes.
 8864        CopyRoomId,
 8865    ]
 8866);
 8867
 8868/// Opens the channel notes for a specific channel by its ID.
 8869#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8870#[action(namespace = collab)]
 8871#[serde(deny_unknown_fields)]
 8872pub struct OpenChannelNotesById {
 8873    pub channel_id: u64,
 8874}
 8875
 8876actions!(
 8877    zed,
 8878    [
 8879        /// Opens the Zed log file.
 8880        OpenLog,
 8881        /// Reveals the Zed log file in the system file manager.
 8882        RevealLogInFileManager
 8883    ]
 8884);
 8885
 8886async fn join_channel_internal(
 8887    channel_id: ChannelId,
 8888    app_state: &Arc<AppState>,
 8889    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8890    requesting_workspace: Option<WeakEntity<Workspace>>,
 8891    active_call: &dyn AnyActiveCall,
 8892    cx: &mut AsyncApp,
 8893) -> Result<bool> {
 8894    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8895        if !active_call.is_in_room(cx) {
 8896            return (false, false);
 8897        }
 8898
 8899        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8900        let should_prompt = active_call.is_sharing_project(cx)
 8901            && active_call.has_remote_participants(cx)
 8902            && !already_in_channel;
 8903        (should_prompt, already_in_channel)
 8904    });
 8905
 8906    if already_in_channel {
 8907        let task = cx.update(|cx| {
 8908            if let Some((project, host)) = active_call.most_active_project(cx) {
 8909                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8910            } else {
 8911                None
 8912            }
 8913        });
 8914        if let Some(task) = task {
 8915            task.await?;
 8916        }
 8917        return anyhow::Ok(true);
 8918    }
 8919
 8920    if should_prompt {
 8921        if let Some(multi_workspace) = requesting_window {
 8922            let answer = multi_workspace
 8923                .update(cx, |_, window, cx| {
 8924                    window.prompt(
 8925                        PromptLevel::Warning,
 8926                        "Do you want to switch channels?",
 8927                        Some("Leaving this call will unshare your current project."),
 8928                        &["Yes, Join Channel", "Cancel"],
 8929                        cx,
 8930                    )
 8931                })?
 8932                .await;
 8933
 8934            if answer == Ok(1) {
 8935                return Ok(false);
 8936            }
 8937        } else {
 8938            return Ok(false);
 8939        }
 8940    }
 8941
 8942    let client = cx.update(|cx| active_call.client(cx));
 8943
 8944    let mut client_status = client.status();
 8945
 8946    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8947    'outer: loop {
 8948        let Some(status) = client_status.recv().await else {
 8949            anyhow::bail!("error connecting");
 8950        };
 8951
 8952        match status {
 8953            Status::Connecting
 8954            | Status::Authenticating
 8955            | Status::Authenticated
 8956            | Status::Reconnecting
 8957            | Status::Reauthenticating
 8958            | Status::Reauthenticated => continue,
 8959            Status::Connected { .. } => break 'outer,
 8960            Status::SignedOut | Status::AuthenticationError => {
 8961                return Err(ErrorCode::SignedOut.into());
 8962            }
 8963            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8964            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8965                return Err(ErrorCode::Disconnected.into());
 8966            }
 8967        }
 8968    }
 8969
 8970    let joined = cx
 8971        .update(|cx| active_call.join_channel(channel_id, cx))
 8972        .await?;
 8973
 8974    if !joined {
 8975        return anyhow::Ok(true);
 8976    }
 8977
 8978    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8979
 8980    let task = cx.update(|cx| {
 8981        if let Some((project, host)) = active_call.most_active_project(cx) {
 8982            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8983        }
 8984
 8985        // If you are the first to join a channel, see if you should share your project.
 8986        if !active_call.has_remote_participants(cx)
 8987            && !active_call.local_participant_is_guest(cx)
 8988            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8989        {
 8990            let project = workspace.update(cx, |workspace, cx| {
 8991                let project = workspace.project.read(cx);
 8992
 8993                if !active_call.share_on_join(cx) {
 8994                    return None;
 8995                }
 8996
 8997                if (project.is_local() || project.is_via_remote_server())
 8998                    && project.visible_worktrees(cx).any(|tree| {
 8999                        tree.read(cx)
 9000                            .root_entry()
 9001                            .is_some_and(|entry| entry.is_dir())
 9002                    })
 9003                {
 9004                    Some(workspace.project.clone())
 9005                } else {
 9006                    None
 9007                }
 9008            });
 9009            if let Some(project) = project {
 9010                let share_task = active_call.share_project(project, cx);
 9011                return Some(cx.spawn(async move |_cx| -> Result<()> {
 9012                    share_task.await?;
 9013                    Ok(())
 9014                }));
 9015            }
 9016        }
 9017
 9018        None
 9019    });
 9020    if let Some(task) = task {
 9021        task.await?;
 9022        return anyhow::Ok(true);
 9023    }
 9024    anyhow::Ok(false)
 9025}
 9026
 9027pub fn join_channel(
 9028    channel_id: ChannelId,
 9029    app_state: Arc<AppState>,
 9030    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9031    requesting_workspace: Option<WeakEntity<Workspace>>,
 9032    cx: &mut App,
 9033) -> Task<Result<()>> {
 9034    let active_call = GlobalAnyActiveCall::global(cx).clone();
 9035    cx.spawn(async move |cx| {
 9036        let result = join_channel_internal(
 9037            channel_id,
 9038            &app_state,
 9039            requesting_window,
 9040            requesting_workspace,
 9041            &*active_call.0,
 9042            cx,
 9043        )
 9044        .await;
 9045
 9046        // join channel succeeded, and opened a window
 9047        if matches!(result, Ok(true)) {
 9048            return anyhow::Ok(());
 9049        }
 9050
 9051        // find an existing workspace to focus and show call controls
 9052        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 9053        if active_window.is_none() {
 9054            // no open workspaces, make one to show the error in (blergh)
 9055            let OpenResult {
 9056                window: window_handle,
 9057                ..
 9058            } = cx
 9059                .update(|cx| {
 9060                    Workspace::new_local(
 9061                        vec![],
 9062                        app_state.clone(),
 9063                        requesting_window,
 9064                        None,
 9065                        None,
 9066                        OpenMode::Activate,
 9067                        cx,
 9068                    )
 9069                })
 9070                .await?;
 9071
 9072            window_handle
 9073                .update(cx, |_, window, _cx| {
 9074                    window.activate_window();
 9075                })
 9076                .ok();
 9077
 9078            if result.is_ok() {
 9079                cx.update(|cx| {
 9080                    cx.dispatch_action(&OpenChannelNotes);
 9081                });
 9082            }
 9083
 9084            active_window = Some(window_handle);
 9085        }
 9086
 9087        if let Err(err) = result {
 9088            log::error!("failed to join channel: {}", err);
 9089            if let Some(active_window) = active_window {
 9090                active_window
 9091                    .update(cx, |_, window, cx| {
 9092                        let detail: SharedString = match err.error_code() {
 9093                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 9094                            ErrorCode::UpgradeRequired => concat!(
 9095                                "Your are running an unsupported version of Zed. ",
 9096                                "Please update to continue."
 9097                            )
 9098                            .into(),
 9099                            ErrorCode::NoSuchChannel => concat!(
 9100                                "No matching channel was found. ",
 9101                                "Please check the link and try again."
 9102                            )
 9103                            .into(),
 9104                            ErrorCode::Forbidden => concat!(
 9105                                "This channel is private, and you do not have access. ",
 9106                                "Please ask someone to add you and try again."
 9107                            )
 9108                            .into(),
 9109                            ErrorCode::Disconnected => {
 9110                                "Please check your internet connection and try again.".into()
 9111                            }
 9112                            _ => format!("{}\n\nPlease try again.", err).into(),
 9113                        };
 9114                        window.prompt(
 9115                            PromptLevel::Critical,
 9116                            "Failed to join channel",
 9117                            Some(&detail),
 9118                            &["Ok"],
 9119                            cx,
 9120                        )
 9121                    })?
 9122                    .await
 9123                    .ok();
 9124            }
 9125        }
 9126
 9127        // return ok, we showed the error to the user.
 9128        anyhow::Ok(())
 9129    })
 9130}
 9131
 9132pub async fn get_any_active_multi_workspace(
 9133    app_state: Arc<AppState>,
 9134    mut cx: AsyncApp,
 9135) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 9136    // find an existing workspace to focus and show call controls
 9137    let active_window = activate_any_workspace_window(&mut cx);
 9138    if active_window.is_none() {
 9139        cx.update(|cx| {
 9140            Workspace::new_local(
 9141                vec![],
 9142                app_state.clone(),
 9143                None,
 9144                None,
 9145                None,
 9146                OpenMode::Activate,
 9147                cx,
 9148            )
 9149        })
 9150        .await?;
 9151    }
 9152    activate_any_workspace_window(&mut cx).context("could not open zed")
 9153}
 9154
 9155fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 9156    cx.update(|cx| {
 9157        if let Some(workspace_window) = cx
 9158            .active_window()
 9159            .and_then(|window| window.downcast::<MultiWorkspace>())
 9160        {
 9161            return Some(workspace_window);
 9162        }
 9163
 9164        for window in cx.windows() {
 9165            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 9166                workspace_window
 9167                    .update(cx, |_, window, _| window.activate_window())
 9168                    .ok();
 9169                return Some(workspace_window);
 9170            }
 9171        }
 9172        None
 9173    })
 9174}
 9175
 9176pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 9177    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 9178}
 9179
 9180pub fn workspace_windows_for_location(
 9181    serialized_location: &SerializedWorkspaceLocation,
 9182    cx: &App,
 9183) -> Vec<WindowHandle<MultiWorkspace>> {
 9184    cx.windows()
 9185        .into_iter()
 9186        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9187        .filter(|multi_workspace| {
 9188            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 9189                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 9190                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 9191                }
 9192                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 9193                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 9194                    a.distro_name == b.distro_name
 9195                }
 9196                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 9197                    a.container_id == b.container_id
 9198                }
 9199                #[cfg(any(test, feature = "test-support"))]
 9200                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 9201                    a.id == b.id
 9202                }
 9203                _ => false,
 9204            };
 9205
 9206            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 9207                multi_workspace.workspaces().any(|workspace| {
 9208                    match workspace.read(cx).workspace_location(cx) {
 9209                        WorkspaceLocation::Location(location, _) => {
 9210                            match (&location, serialized_location) {
 9211                                (
 9212                                    SerializedWorkspaceLocation::Local,
 9213                                    SerializedWorkspaceLocation::Local,
 9214                                ) => true,
 9215                                (
 9216                                    SerializedWorkspaceLocation::Remote(a),
 9217                                    SerializedWorkspaceLocation::Remote(b),
 9218                                ) => same_host(a, b),
 9219                                _ => false,
 9220                            }
 9221                        }
 9222                        _ => false,
 9223                    }
 9224                })
 9225            })
 9226        })
 9227        .collect()
 9228}
 9229
 9230pub async fn find_existing_workspace(
 9231    abs_paths: &[PathBuf],
 9232    open_options: &OpenOptions,
 9233    location: &SerializedWorkspaceLocation,
 9234    cx: &mut AsyncApp,
 9235) -> (
 9236    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 9237    OpenVisible,
 9238) {
 9239    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 9240    let mut open_visible = OpenVisible::All;
 9241    let mut best_match = None;
 9242
 9243    cx.update(|cx| {
 9244        for window in workspace_windows_for_location(location, cx) {
 9245            if let Ok(multi_workspace) = window.read(cx) {
 9246                for workspace in multi_workspace.workspaces() {
 9247                    let project = workspace.read(cx).project.read(cx);
 9248                    let m = project.visibility_for_paths(
 9249                        abs_paths,
 9250                        open_options.open_new_workspace == None,
 9251                        cx,
 9252                    );
 9253                    if m > best_match {
 9254                        existing = Some((window, workspace.clone()));
 9255                        best_match = m;
 9256                    } else if best_match.is_none() && open_options.open_new_workspace == Some(false)
 9257                    {
 9258                        existing = Some((window, workspace.clone()))
 9259                    }
 9260                }
 9261            }
 9262        }
 9263    });
 9264
 9265    // With -n, only reuse a window if the path is genuinely contained
 9266    // within an existing worktree (don't fall back to any arbitrary window).
 9267    if open_options.open_new_workspace == Some(true) && best_match.is_none() {
 9268        existing = None;
 9269    }
 9270
 9271    if open_options.open_new_workspace != Some(true) {
 9272        let all_paths_are_files = existing
 9273            .as_ref()
 9274            .and_then(|(_, target_workspace)| {
 9275                cx.update(|cx| {
 9276                    let workspace = target_workspace.read(cx);
 9277                    let project = workspace.project.read(cx);
 9278                    let path_style = workspace.path_style(cx);
 9279                    Some(!abs_paths.iter().any(|path| {
 9280                        let path = util::paths::SanitizedPath::new(path);
 9281                        project.worktrees(cx).any(|worktree| {
 9282                            let worktree = worktree.read(cx);
 9283                            let abs_path = worktree.abs_path();
 9284                            path_style
 9285                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 9286                                .and_then(|rel| worktree.entry_for_path(&rel))
 9287                                .is_some_and(|e| e.is_dir())
 9288                        })
 9289                    }))
 9290                })
 9291            })
 9292            .unwrap_or(false);
 9293
 9294        if open_options.open_new_workspace.is_none()
 9295            && existing.is_some()
 9296            && open_options.wait
 9297            && all_paths_are_files
 9298        {
 9299            cx.update(|cx| {
 9300                let windows = workspace_windows_for_location(location, cx);
 9301                let window = cx
 9302                    .active_window()
 9303                    .and_then(|window| window.downcast::<MultiWorkspace>())
 9304                    .filter(|window| windows.contains(window))
 9305                    .or_else(|| windows.into_iter().next());
 9306                if let Some(window) = window {
 9307                    if let Ok(multi_workspace) = window.read(cx) {
 9308                        let active_workspace = multi_workspace.workspace().clone();
 9309                        existing = Some((window, active_workspace));
 9310                        open_visible = OpenVisible::None;
 9311                    }
 9312                }
 9313            });
 9314        }
 9315    }
 9316    (existing, open_visible)
 9317}
 9318
 9319#[derive(Default, Clone)]
 9320pub struct OpenOptions {
 9321    pub visible: Option<OpenVisible>,
 9322    pub focus: Option<bool>,
 9323    pub open_new_workspace: Option<bool>,
 9324    pub force_existing_window: bool,
 9325    pub wait: bool,
 9326    pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9327    pub open_mode: OpenMode,
 9328    pub env: Option<HashMap<String, String>>,
 9329    pub open_in_dev_container: bool,
 9330}
 9331
 9332impl OpenOptions {
 9333    fn should_reuse_existing_window(&self) -> bool {
 9334        self.open_new_workspace.is_none() && self.open_mode != OpenMode::NewWindow
 9335    }
 9336}
 9337
 9338/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 9339/// or [`Workspace::open_workspace_for_paths`].
 9340pub struct OpenResult {
 9341    pub window: WindowHandle<MultiWorkspace>,
 9342    pub workspace: Entity<Workspace>,
 9343    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 9344}
 9345
 9346/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 9347pub fn open_workspace_by_id(
 9348    workspace_id: WorkspaceId,
 9349    app_state: Arc<AppState>,
 9350    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9351    cx: &mut App,
 9352) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 9353    let project_handle = Project::local(
 9354        app_state.client.clone(),
 9355        app_state.node_runtime.clone(),
 9356        app_state.user_store.clone(),
 9357        app_state.languages.clone(),
 9358        app_state.fs.clone(),
 9359        None,
 9360        project::LocalProjectFlags {
 9361            init_worktree_trust: true,
 9362            ..project::LocalProjectFlags::default()
 9363        },
 9364        cx,
 9365    );
 9366
 9367    let db = WorkspaceDb::global(cx);
 9368    let kvp = db::kvp::KeyValueStore::global(cx);
 9369    cx.spawn(async move |cx| {
 9370        let serialized_workspace = db
 9371            .workspace_for_id(workspace_id)
 9372            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 9373
 9374        let centered_layout = serialized_workspace.centered_layout;
 9375
 9376        let (window, workspace) = if let Some(window) = requesting_window {
 9377            let workspace = window.update(cx, |multi_workspace, window, cx| {
 9378                let workspace = cx.new(|cx| {
 9379                    let mut workspace = Workspace::new(
 9380                        Some(workspace_id),
 9381                        project_handle.clone(),
 9382                        app_state.clone(),
 9383                        window,
 9384                        cx,
 9385                    );
 9386                    workspace.centered_layout = centered_layout;
 9387                    workspace
 9388                });
 9389                multi_workspace.add(workspace.clone(), &*window, cx);
 9390                workspace
 9391            })?;
 9392            (window, workspace)
 9393        } else {
 9394            let window_bounds_override = window_bounds_env_override();
 9395
 9396            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 9397                (Some(WindowBounds::Windowed(bounds)), None)
 9398            } else if let Some(display) = serialized_workspace.display
 9399                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 9400            {
 9401                (Some(bounds.0), Some(display))
 9402            } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
 9403                (Some(bounds), Some(display))
 9404            } else {
 9405                (None, None)
 9406            };
 9407
 9408            let options = cx.update(|cx| {
 9409                let mut options = (app_state.build_window_options)(display, cx);
 9410                options.window_bounds = window_bounds;
 9411                options
 9412            });
 9413
 9414            let window = cx.open_window(options, {
 9415                let app_state = app_state.clone();
 9416                let project_handle = project_handle.clone();
 9417                move |window, cx| {
 9418                    let workspace = cx.new(|cx| {
 9419                        let mut workspace = Workspace::new(
 9420                            Some(workspace_id),
 9421                            project_handle,
 9422                            app_state,
 9423                            window,
 9424                            cx,
 9425                        );
 9426                        workspace.centered_layout = centered_layout;
 9427                        workspace
 9428                    });
 9429                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9430                }
 9431            })?;
 9432
 9433            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 9434                multi_workspace.workspace().clone()
 9435            })?;
 9436
 9437            (window, workspace)
 9438        };
 9439
 9440        notify_if_database_failed(window, cx);
 9441
 9442        // Restore items from the serialized workspace
 9443        window
 9444            .update(cx, |_, window, cx| {
 9445                workspace.update(cx, |_workspace, cx| {
 9446                    open_items(Some(serialized_workspace), vec![], window, cx)
 9447                })
 9448            })?
 9449            .await?;
 9450
 9451        window.update(cx, |_, window, cx| {
 9452            workspace.update(cx, |workspace, cx| {
 9453                workspace.serialize_workspace(window, cx);
 9454            });
 9455        })?;
 9456
 9457        Ok(window)
 9458    })
 9459}
 9460
 9461#[allow(clippy::type_complexity)]
 9462pub fn open_paths(
 9463    abs_paths: &[PathBuf],
 9464    app_state: Arc<AppState>,
 9465    mut open_options: OpenOptions,
 9466    cx: &mut App,
 9467) -> Task<anyhow::Result<OpenResult>> {
 9468    let abs_paths = abs_paths.to_vec();
 9469    #[cfg(target_os = "windows")]
 9470    let wsl_path = abs_paths
 9471        .iter()
 9472        .find_map(|p| util::paths::WslPath::from_path(p));
 9473
 9474    cx.spawn(async move |cx| {
 9475        let (mut existing, mut open_visible) = find_existing_workspace(
 9476            &abs_paths,
 9477            &open_options,
 9478            &SerializedWorkspaceLocation::Local,
 9479            cx,
 9480        )
 9481        .await;
 9482
 9483        // Fallback: if no workspace contains the paths and all paths are files,
 9484        // prefer an existing local workspace window (active window first).
 9485        if open_options.should_reuse_existing_window() && existing.is_none() {
 9486            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 9487            let all_metadatas = futures::future::join_all(all_paths)
 9488                .await
 9489                .into_iter()
 9490                .filter_map(|result| result.ok().flatten());
 9491
 9492            if all_metadatas.into_iter().all(|file| !file.is_dir) {
 9493                cx.update(|cx| {
 9494                    let windows = workspace_windows_for_location(
 9495                        &SerializedWorkspaceLocation::Local,
 9496                        cx,
 9497                    );
 9498                    let window = cx
 9499                        .active_window()
 9500                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9501                        .filter(|window| windows.contains(window))
 9502                        .or_else(|| windows.into_iter().next());
 9503                    if let Some(window) = window {
 9504                        if let Ok(multi_workspace) = window.read(cx) {
 9505                            let active_workspace = multi_workspace.workspace().clone();
 9506                            existing = Some((window, active_workspace));
 9507                            open_visible = OpenVisible::None;
 9508                        }
 9509                    }
 9510                });
 9511            }
 9512        }
 9513
 9514        // Fallback for directories: when no flag is specified and no existing
 9515        // workspace matched, check the user's setting to decide whether to add
 9516        // the directory as a new workspace in the active window's MultiWorkspace
 9517        // or open a new window.
 9518        if open_options.should_reuse_existing_window() && existing.is_none() {
 9519            let use_existing_window = open_options.force_existing_window
 9520                || cx.update(|cx| {
 9521                    WorkspaceSettings::get_global(cx).cli_default_open_behavior
 9522                        == settings::CliDefaultOpenBehavior::ExistingWindow
 9523                });
 9524
 9525            if use_existing_window {
 9526                let target_window = cx.update(|cx| {
 9527                    let windows = workspace_windows_for_location(
 9528                        &SerializedWorkspaceLocation::Local,
 9529                        cx,
 9530                    );
 9531                    let window = cx
 9532                        .active_window()
 9533                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9534                        .filter(|window| windows.contains(window))
 9535                        .or_else(|| windows.into_iter().next());
 9536                    window.filter(|window| {
 9537                        window
 9538                            .read(cx)
 9539                            .is_ok_and(|mw| mw.multi_workspace_enabled(cx))
 9540                    })
 9541                });
 9542
 9543                if let Some(window) = target_window {
 9544                    open_options.requesting_window = Some(window);
 9545                    window
 9546                        .update(cx, |multi_workspace, _, cx| {
 9547                            multi_workspace.open_sidebar(cx);
 9548                        })
 9549                        .log_err();
 9550                }
 9551            }
 9552        }
 9553
 9554        let open_in_dev_container = open_options.open_in_dev_container;
 9555
 9556        let result = if let Some((existing, target_workspace)) = existing {
 9557            let open_task = existing
 9558                .update(cx, |multi_workspace, window, cx| {
 9559                    window.activate_window();
 9560                    multi_workspace.activate(target_workspace.clone(), window, cx);
 9561                    target_workspace.update(cx, |workspace, cx| {
 9562                        if open_in_dev_container {
 9563                            workspace.set_open_in_dev_container(true);
 9564                        }
 9565                        workspace.open_paths(
 9566                            abs_paths,
 9567                            OpenOptions {
 9568                                visible: Some(open_visible),
 9569                                ..Default::default()
 9570                            },
 9571                            None,
 9572                            window,
 9573                            cx,
 9574                        )
 9575                    })
 9576                })?
 9577                .await;
 9578
 9579            _ = existing.update(cx, |multi_workspace, _, cx| {
 9580                let workspace = multi_workspace.workspace().clone();
 9581                workspace.update(cx, |workspace, cx| {
 9582                    for item in open_task.iter().flatten() {
 9583                        if let Err(e) = item {
 9584                            workspace.show_error(&e, cx);
 9585                        }
 9586                    }
 9587                });
 9588            });
 9589
 9590            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9591        } else {
 9592            let init = if open_in_dev_container {
 9593                Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>| {
 9594                    workspace.set_open_in_dev_container(true);
 9595                }) as Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>)
 9596            } else {
 9597                None
 9598            };
 9599            let result = cx
 9600                .update(move |cx| {
 9601                    Workspace::new_local(
 9602                        abs_paths,
 9603                        app_state.clone(),
 9604                        open_options.requesting_window,
 9605                        open_options.env,
 9606                        init,
 9607                        open_options.open_mode,
 9608                        cx,
 9609                    )
 9610                })
 9611                .await;
 9612
 9613            if let Ok(ref result) = result {
 9614                result.window
 9615                    .update(cx, |_, window, _cx| {
 9616                        window.activate_window();
 9617                    })
 9618                    .log_err();
 9619            }
 9620
 9621            result
 9622        };
 9623
 9624        #[cfg(target_os = "windows")]
 9625        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9626            && let Ok(ref result) = result
 9627        {
 9628            result.window
 9629                .update(cx, move |multi_workspace, _window, cx| {
 9630                    struct OpenInWsl;
 9631                    let workspace = multi_workspace.workspace().clone();
 9632                    workspace.update(cx, |workspace, cx| {
 9633                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9634                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9635                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9636                            cx.new(move |cx| {
 9637                                MessageNotification::new(msg, cx)
 9638                                    .primary_message("Open in WSL")
 9639                                    .primary_icon(IconName::FolderOpen)
 9640                                    .primary_on_click(move |window, cx| {
 9641                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9642                                                distro: remote::WslConnectionOptions {
 9643                                                        distro_name: distro.clone(),
 9644                                                    user: None,
 9645                                                },
 9646                                                paths: vec![path.clone().into()],
 9647                                            }), cx)
 9648                                    })
 9649                            })
 9650                        });
 9651                    });
 9652                })
 9653                .unwrap();
 9654        };
 9655        result
 9656    })
 9657}
 9658
 9659pub fn open_new(
 9660    open_options: OpenOptions,
 9661    app_state: Arc<AppState>,
 9662    cx: &mut App,
 9663    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9664) -> Task<anyhow::Result<()>> {
 9665    let addition = open_options.open_mode;
 9666    let task = Workspace::new_local(
 9667        Vec::new(),
 9668        app_state,
 9669        open_options.requesting_window,
 9670        open_options.env,
 9671        Some(Box::new(init)),
 9672        addition,
 9673        cx,
 9674    );
 9675    cx.spawn(async move |cx| {
 9676        let OpenResult { window, .. } = task.await?;
 9677        window
 9678            .update(cx, |_, window, _cx| {
 9679                window.activate_window();
 9680            })
 9681            .ok();
 9682        Ok(())
 9683    })
 9684}
 9685
 9686pub fn create_and_open_local_file(
 9687    path: &'static Path,
 9688    window: &mut Window,
 9689    cx: &mut Context<Workspace>,
 9690    default_content: impl 'static + Send + FnOnce() -> Rope,
 9691) -> Task<Result<Box<dyn ItemHandle>>> {
 9692    cx.spawn_in(window, async move |workspace, cx| {
 9693        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9694        if !fs.is_file(path).await {
 9695            fs.create_file(path, Default::default()).await?;
 9696            fs.save(path, &default_content(), Default::default())
 9697                .await?;
 9698        }
 9699
 9700        workspace
 9701            .update_in(cx, |workspace, window, cx| {
 9702                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9703                    let path = workspace
 9704                        .project
 9705                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9706                    cx.spawn_in(window, async move |workspace, cx| {
 9707                        let path = path.await?;
 9708
 9709                        let path = fs.canonicalize(&path).await.unwrap_or(path);
 9710
 9711                        let mut items = workspace
 9712                            .update_in(cx, |workspace, window, cx| {
 9713                                workspace.open_paths(
 9714                                    vec![path.to_path_buf()],
 9715                                    OpenOptions {
 9716                                        visible: Some(OpenVisible::None),
 9717                                        ..Default::default()
 9718                                    },
 9719                                    None,
 9720                                    window,
 9721                                    cx,
 9722                                )
 9723                            })?
 9724                            .await;
 9725                        let item = items.pop().flatten();
 9726                        item.with_context(|| format!("path {path:?} is not a file"))?
 9727                    })
 9728                })
 9729            })?
 9730            .await?
 9731            .await
 9732    })
 9733}
 9734
 9735pub fn open_remote_project_with_new_connection(
 9736    window: WindowHandle<MultiWorkspace>,
 9737    remote_connection: Arc<dyn RemoteConnection>,
 9738    cancel_rx: oneshot::Receiver<()>,
 9739    delegate: Arc<dyn RemoteClientDelegate>,
 9740    app_state: Arc<AppState>,
 9741    paths: Vec<PathBuf>,
 9742    cx: &mut App,
 9743) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9744    cx.spawn(async move |cx| {
 9745        let (workspace_id, serialized_workspace) =
 9746            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9747                .await?;
 9748
 9749        let session = match cx
 9750            .update(|cx| {
 9751                remote::RemoteClient::new(
 9752                    ConnectionIdentifier::Workspace(workspace_id.0),
 9753                    remote_connection,
 9754                    cancel_rx,
 9755                    delegate,
 9756                    cx,
 9757                )
 9758            })
 9759            .await?
 9760        {
 9761            Some(result) => result,
 9762            None => return Ok(Vec::new()),
 9763        };
 9764
 9765        let project = cx.update(|cx| {
 9766            project::Project::remote(
 9767                session,
 9768                app_state.client.clone(),
 9769                app_state.node_runtime.clone(),
 9770                app_state.user_store.clone(),
 9771                app_state.languages.clone(),
 9772                app_state.fs.clone(),
 9773                true,
 9774                cx,
 9775            )
 9776        });
 9777
 9778        open_remote_project_inner(
 9779            project,
 9780            paths,
 9781            workspace_id,
 9782            serialized_workspace,
 9783            app_state,
 9784            window,
 9785            None,
 9786            cx,
 9787        )
 9788        .await
 9789    })
 9790}
 9791
 9792pub fn open_remote_project_with_existing_connection(
 9793    connection_options: RemoteConnectionOptions,
 9794    project: Entity<Project>,
 9795    paths: Vec<PathBuf>,
 9796    app_state: Arc<AppState>,
 9797    window: WindowHandle<MultiWorkspace>,
 9798    provisional_project_group_key: Option<ProjectGroupKey>,
 9799    cx: &mut AsyncApp,
 9800) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9801    cx.spawn(async move |cx| {
 9802        let (workspace_id, serialized_workspace) =
 9803            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9804
 9805        open_remote_project_inner(
 9806            project,
 9807            paths,
 9808            workspace_id,
 9809            serialized_workspace,
 9810            app_state,
 9811            window,
 9812            provisional_project_group_key,
 9813            cx,
 9814        )
 9815        .await
 9816    })
 9817}
 9818
 9819async fn open_remote_project_inner(
 9820    project: Entity<Project>,
 9821    paths: Vec<PathBuf>,
 9822    workspace_id: WorkspaceId,
 9823    serialized_workspace: Option<SerializedWorkspace>,
 9824    app_state: Arc<AppState>,
 9825    window: WindowHandle<MultiWorkspace>,
 9826    provisional_project_group_key: Option<ProjectGroupKey>,
 9827    cx: &mut AsyncApp,
 9828) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9829    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9830    let toolchains = db.toolchains(workspace_id).await?;
 9831    for (toolchain, worktree_path, path) in toolchains {
 9832        project
 9833            .update(cx, |this, cx| {
 9834                let Some(worktree_id) =
 9835                    this.find_worktree(&worktree_path, cx)
 9836                        .and_then(|(worktree, rel_path)| {
 9837                            if rel_path.is_empty() {
 9838                                Some(worktree.read(cx).id())
 9839                            } else {
 9840                                None
 9841                            }
 9842                        })
 9843                else {
 9844                    return Task::ready(None);
 9845                };
 9846
 9847                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9848            })
 9849            .await;
 9850    }
 9851    let mut project_paths_to_open = vec![];
 9852    let mut project_path_errors = vec![];
 9853
 9854    for path in paths {
 9855        let result = cx
 9856            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9857            .await;
 9858        match result {
 9859            Ok((_, project_path)) => {
 9860                project_paths_to_open.push((path.clone(), Some(project_path)));
 9861            }
 9862            Err(error) => {
 9863                project_path_errors.push(error);
 9864            }
 9865        };
 9866    }
 9867
 9868    if project_paths_to_open.is_empty() {
 9869        return Err(project_path_errors.pop().context("no paths given")?);
 9870    }
 9871
 9872    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9873        telemetry::event!("SSH Project Opened");
 9874
 9875        let new_workspace = cx.new(|cx| {
 9876            let mut workspace =
 9877                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9878            workspace.update_history(cx);
 9879
 9880            if let Some(ref serialized) = serialized_workspace {
 9881                workspace.centered_layout = serialized.centered_layout;
 9882            }
 9883
 9884            workspace
 9885        });
 9886
 9887        if let Some(project_group_key) = provisional_project_group_key.clone() {
 9888            multi_workspace.set_workspace_group_key(&new_workspace, project_group_key);
 9889        }
 9890        multi_workspace.activate(new_workspace.clone(), window, cx);
 9891        new_workspace
 9892    })?;
 9893
 9894    let items = window
 9895        .update(cx, |_, window, cx| {
 9896            window.activate_window();
 9897            workspace.update(cx, |_workspace, cx| {
 9898                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9899            })
 9900        })?
 9901        .await?;
 9902
 9903    workspace.update(cx, |workspace, cx| {
 9904        for error in project_path_errors {
 9905            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9906                if let Some(path) = error.error_tag("path") {
 9907                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9908                }
 9909            } else {
 9910                workspace.show_error(&error, cx)
 9911            }
 9912        }
 9913    });
 9914
 9915    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9916}
 9917
 9918fn deserialize_remote_project(
 9919    connection_options: RemoteConnectionOptions,
 9920    paths: Vec<PathBuf>,
 9921    cx: &AsyncApp,
 9922) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9923    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9924    cx.background_spawn(async move {
 9925        let remote_connection_id = db
 9926            .get_or_create_remote_connection(connection_options)
 9927            .await?;
 9928
 9929        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
 9930
 9931        let workspace_id = if let Some(workspace_id) =
 9932            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9933        {
 9934            workspace_id
 9935        } else {
 9936            db.next_id().await?
 9937        };
 9938
 9939        Ok((workspace_id, serialized_workspace))
 9940    })
 9941}
 9942
 9943pub fn join_in_room_project(
 9944    project_id: u64,
 9945    follow_user_id: u64,
 9946    app_state: Arc<AppState>,
 9947    cx: &mut App,
 9948) -> Task<Result<()>> {
 9949    let windows = cx.windows();
 9950    cx.spawn(async move |cx| {
 9951        let existing_window_and_workspace: Option<(
 9952            WindowHandle<MultiWorkspace>,
 9953            Entity<Workspace>,
 9954        )> = windows.into_iter().find_map(|window_handle| {
 9955            window_handle
 9956                .downcast::<MultiWorkspace>()
 9957                .and_then(|window_handle| {
 9958                    window_handle
 9959                        .update(cx, |multi_workspace, _window, cx| {
 9960                            for workspace in multi_workspace.workspaces() {
 9961                                if workspace.read(cx).project().read(cx).remote_id()
 9962                                    == Some(project_id)
 9963                                {
 9964                                    return Some((window_handle, workspace.clone()));
 9965                                }
 9966                            }
 9967                            None
 9968                        })
 9969                        .unwrap_or(None)
 9970                })
 9971        });
 9972
 9973        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9974            existing_window_and_workspace
 9975        {
 9976            existing_window
 9977                .update(cx, |multi_workspace, window, cx| {
 9978                    multi_workspace.activate(target_workspace, window, cx);
 9979                })
 9980                .ok();
 9981            existing_window
 9982        } else {
 9983            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9984            let project = cx
 9985                .update(|cx| {
 9986                    active_call.0.join_project(
 9987                        project_id,
 9988                        app_state.languages.clone(),
 9989                        app_state.fs.clone(),
 9990                        cx,
 9991                    )
 9992                })
 9993                .await?;
 9994
 9995            let window_bounds_override = window_bounds_env_override();
 9996            cx.update(|cx| {
 9997                let mut options = (app_state.build_window_options)(None, cx);
 9998                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9999                cx.open_window(options, |window, cx| {
10000                    let workspace = cx.new(|cx| {
10001                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
10002                    });
10003                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
10004                })
10005            })?
10006        };
10007
10008        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
10009            cx.activate(true);
10010            window.activate_window();
10011
10012            // We set the active workspace above, so this is the correct workspace.
10013            let workspace = multi_workspace.workspace().clone();
10014            workspace.update(cx, |workspace, cx| {
10015                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
10016                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
10017                    .or_else(|| {
10018                        // If we couldn't follow the given user, follow the host instead.
10019                        let collaborator = workspace
10020                            .project()
10021                            .read(cx)
10022                            .collaborators()
10023                            .values()
10024                            .find(|collaborator| collaborator.is_host)?;
10025                        Some(collaborator.peer_id)
10026                    });
10027
10028                if let Some(follow_peer_id) = follow_peer_id {
10029                    workspace.follow(follow_peer_id, window, cx);
10030                }
10031            });
10032        })?;
10033
10034        anyhow::Ok(())
10035    })
10036}
10037
10038pub fn reload(cx: &mut App) {
10039    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
10040    let mut workspace_windows = cx
10041        .windows()
10042        .into_iter()
10043        .filter_map(|window| window.downcast::<MultiWorkspace>())
10044        .collect::<Vec<_>>();
10045
10046    // If multiple windows have unsaved changes, and need a save prompt,
10047    // prompt in the active window before switching to a different window.
10048    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
10049
10050    let mut prompt = None;
10051    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
10052        prompt = window
10053            .update(cx, |_, window, cx| {
10054                window.prompt(
10055                    PromptLevel::Info,
10056                    "Are you sure you want to restart?",
10057                    None,
10058                    &["Restart", "Cancel"],
10059                    cx,
10060                )
10061            })
10062            .ok();
10063    }
10064
10065    cx.spawn(async move |cx| {
10066        if let Some(prompt) = prompt {
10067            let answer = prompt.await?;
10068            if answer != 0 {
10069                return anyhow::Ok(());
10070            }
10071        }
10072
10073        // If the user cancels any save prompt, then keep the app open.
10074        for window in workspace_windows {
10075            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
10076                let workspace = multi_workspace.workspace().clone();
10077                workspace.update(cx, |workspace, cx| {
10078                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
10079                })
10080            }) && !should_close.await?
10081            {
10082                return anyhow::Ok(());
10083            }
10084        }
10085        cx.update(|cx| cx.restart());
10086        anyhow::Ok(())
10087    })
10088    .detach_and_log_err(cx);
10089}
10090
10091fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
10092    let mut parts = value.split(',');
10093    let x: usize = parts.next()?.parse().ok()?;
10094    let y: usize = parts.next()?.parse().ok()?;
10095    Some(point(px(x as f32), px(y as f32)))
10096}
10097
10098fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
10099    let mut parts = value.split(',');
10100    let width: usize = parts.next()?.parse().ok()?;
10101    let height: usize = parts.next()?.parse().ok()?;
10102    Some(size(px(width as f32), px(height as f32)))
10103}
10104
10105/// Add client-side decorations (rounded corners, shadows, resize handling) when
10106/// appropriate.
10107///
10108/// The `border_radius_tiling` parameter allows overriding which corners get
10109/// rounded, independently of the actual window tiling state. This is used
10110/// specifically for the workspace switcher sidebar: when the sidebar is open,
10111/// we want square corners on the left (so the sidebar appears flush with the
10112/// window edge) but we still need the shadow padding for proper visual
10113/// appearance. Unlike actual window tiling, this only affects border radius -
10114/// not padding or shadows.
10115pub fn client_side_decorations(
10116    element: impl IntoElement,
10117    window: &mut Window,
10118    cx: &mut App,
10119    border_radius_tiling: Tiling,
10120) -> Stateful<Div> {
10121    const BORDER_SIZE: Pixels = px(1.0);
10122    let decorations = window.window_decorations();
10123    let tiling = match decorations {
10124        Decorations::Server => Tiling::default(),
10125        Decorations::Client { tiling } => tiling,
10126    };
10127
10128    match decorations {
10129        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
10130        Decorations::Server => window.set_client_inset(px(0.0)),
10131    }
10132
10133    struct GlobalResizeEdge(ResizeEdge);
10134    impl Global for GlobalResizeEdge {}
10135
10136    div()
10137        .id("window-backdrop")
10138        .bg(transparent_black())
10139        .map(|div| match decorations {
10140            Decorations::Server => div,
10141            Decorations::Client { .. } => div
10142                .when(
10143                    !(tiling.top
10144                        || tiling.right
10145                        || border_radius_tiling.top
10146                        || border_radius_tiling.right),
10147                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10148                )
10149                .when(
10150                    !(tiling.top
10151                        || tiling.left
10152                        || border_radius_tiling.top
10153                        || border_radius_tiling.left),
10154                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10155                )
10156                .when(
10157                    !(tiling.bottom
10158                        || tiling.right
10159                        || border_radius_tiling.bottom
10160                        || border_radius_tiling.right),
10161                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10162                )
10163                .when(
10164                    !(tiling.bottom
10165                        || tiling.left
10166                        || border_radius_tiling.bottom
10167                        || border_radius_tiling.left),
10168                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10169                )
10170                .when(!tiling.top, |div| {
10171                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
10172                })
10173                .when(!tiling.bottom, |div| {
10174                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
10175                })
10176                .when(!tiling.left, |div| {
10177                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10178                })
10179                .when(!tiling.right, |div| {
10180                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10181                })
10182                .on_mouse_move(move |e, window, cx| {
10183                    let size = window.window_bounds().get_bounds().size;
10184                    let pos = e.position;
10185
10186                    let new_edge =
10187                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10188
10189                    let edge = cx.try_global::<GlobalResizeEdge>();
10190                    if new_edge != edge.map(|edge| edge.0) {
10191                        window
10192                            .window_handle()
10193                            .update(cx, |workspace, _, cx| {
10194                                cx.notify(workspace.entity_id());
10195                            })
10196                            .ok();
10197                    }
10198                })
10199                .on_mouse_down(MouseButton::Left, move |e, window, _| {
10200                    let size = window.window_bounds().get_bounds().size;
10201                    let pos = e.position;
10202
10203                    let edge = match resize_edge(
10204                        pos,
10205                        theme::CLIENT_SIDE_DECORATION_SHADOW,
10206                        size,
10207                        tiling,
10208                    ) {
10209                        Some(value) => value,
10210                        None => return,
10211                    };
10212
10213                    window.start_window_resize(edge);
10214                }),
10215        })
10216        .size_full()
10217        .child(
10218            div()
10219                .cursor(CursorStyle::Arrow)
10220                .map(|div| match decorations {
10221                    Decorations::Server => div,
10222                    Decorations::Client { .. } => div
10223                        .border_color(cx.theme().colors().border)
10224                        .when(
10225                            !(tiling.top
10226                                || tiling.right
10227                                || border_radius_tiling.top
10228                                || border_radius_tiling.right),
10229                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10230                        )
10231                        .when(
10232                            !(tiling.top
10233                                || tiling.left
10234                                || border_radius_tiling.top
10235                                || border_radius_tiling.left),
10236                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10237                        )
10238                        .when(
10239                            !(tiling.bottom
10240                                || tiling.right
10241                                || border_radius_tiling.bottom
10242                                || border_radius_tiling.right),
10243                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10244                        )
10245                        .when(
10246                            !(tiling.bottom
10247                                || tiling.left
10248                                || border_radius_tiling.bottom
10249                                || border_radius_tiling.left),
10250                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10251                        )
10252                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10253                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10254                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10255                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10256                        .when(!tiling.is_tiled(), |div| {
10257                            div.shadow(vec![gpui::BoxShadow {
10258                                color: Hsla {
10259                                    h: 0.,
10260                                    s: 0.,
10261                                    l: 0.,
10262                                    a: 0.4,
10263                                },
10264                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10265                                spread_radius: px(0.),
10266                                offset: point(px(0.0), px(0.0)),
10267                            }])
10268                        }),
10269                })
10270                .on_mouse_move(|_e, _, cx| {
10271                    cx.stop_propagation();
10272                })
10273                .size_full()
10274                .child(element),
10275        )
10276        .map(|div| match decorations {
10277            Decorations::Server => div,
10278            Decorations::Client { tiling, .. } => div.child(
10279                canvas(
10280                    |_bounds, window, _| {
10281                        window.insert_hitbox(
10282                            Bounds::new(
10283                                point(px(0.0), px(0.0)),
10284                                window.window_bounds().get_bounds().size,
10285                            ),
10286                            HitboxBehavior::Normal,
10287                        )
10288                    },
10289                    move |_bounds, hitbox, window, cx| {
10290                        let mouse = window.mouse_position();
10291                        let size = window.window_bounds().get_bounds().size;
10292                        let Some(edge) =
10293                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10294                        else {
10295                            return;
10296                        };
10297                        cx.set_global(GlobalResizeEdge(edge));
10298                        window.set_cursor_style(
10299                            match edge {
10300                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10301                                ResizeEdge::Left | ResizeEdge::Right => {
10302                                    CursorStyle::ResizeLeftRight
10303                                }
10304                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10305                                    CursorStyle::ResizeUpLeftDownRight
10306                                }
10307                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10308                                    CursorStyle::ResizeUpRightDownLeft
10309                                }
10310                            },
10311                            &hitbox,
10312                        );
10313                    },
10314                )
10315                .size_full()
10316                .absolute(),
10317            ),
10318        })
10319}
10320
10321fn resize_edge(
10322    pos: Point<Pixels>,
10323    shadow_size: Pixels,
10324    window_size: Size<Pixels>,
10325    tiling: Tiling,
10326) -> Option<ResizeEdge> {
10327    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10328    if bounds.contains(&pos) {
10329        return None;
10330    }
10331
10332    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10333    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10334    if !tiling.top && top_left_bounds.contains(&pos) {
10335        return Some(ResizeEdge::TopLeft);
10336    }
10337
10338    let top_right_bounds = Bounds::new(
10339        Point::new(window_size.width - corner_size.width, px(0.)),
10340        corner_size,
10341    );
10342    if !tiling.top && top_right_bounds.contains(&pos) {
10343        return Some(ResizeEdge::TopRight);
10344    }
10345
10346    let bottom_left_bounds = Bounds::new(
10347        Point::new(px(0.), window_size.height - corner_size.height),
10348        corner_size,
10349    );
10350    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10351        return Some(ResizeEdge::BottomLeft);
10352    }
10353
10354    let bottom_right_bounds = Bounds::new(
10355        Point::new(
10356            window_size.width - corner_size.width,
10357            window_size.height - corner_size.height,
10358        ),
10359        corner_size,
10360    );
10361    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10362        return Some(ResizeEdge::BottomRight);
10363    }
10364
10365    if !tiling.top && pos.y < shadow_size {
10366        Some(ResizeEdge::Top)
10367    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10368        Some(ResizeEdge::Bottom)
10369    } else if !tiling.left && pos.x < shadow_size {
10370        Some(ResizeEdge::Left)
10371    } else if !tiling.right && pos.x > window_size.width - shadow_size {
10372        Some(ResizeEdge::Right)
10373    } else {
10374        None
10375    }
10376}
10377
10378fn join_pane_into_active(
10379    active_pane: &Entity<Pane>,
10380    pane: &Entity<Pane>,
10381    window: &mut Window,
10382    cx: &mut App,
10383) {
10384    if pane == active_pane {
10385    } else if pane.read(cx).items_len() == 0 {
10386        pane.update(cx, |_, cx| {
10387            cx.emit(pane::Event::Remove {
10388                focus_on_pane: None,
10389            });
10390        })
10391    } else {
10392        move_all_items(pane, active_pane, window, cx);
10393    }
10394}
10395
10396fn move_all_items(
10397    from_pane: &Entity<Pane>,
10398    to_pane: &Entity<Pane>,
10399    window: &mut Window,
10400    cx: &mut App,
10401) {
10402    let destination_is_different = from_pane != to_pane;
10403    let mut moved_items = 0;
10404    for (item_ix, item_handle) in from_pane
10405        .read(cx)
10406        .items()
10407        .enumerate()
10408        .map(|(ix, item)| (ix, item.clone()))
10409        .collect::<Vec<_>>()
10410    {
10411        let ix = item_ix - moved_items;
10412        if destination_is_different {
10413            // Close item from previous pane
10414            from_pane.update(cx, |source, cx| {
10415                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10416            });
10417            moved_items += 1;
10418        }
10419
10420        // This automatically removes duplicate items in the pane
10421        to_pane.update(cx, |destination, cx| {
10422            destination.add_item(item_handle, true, true, None, window, cx);
10423            window.focus(&destination.focus_handle(cx), cx)
10424        });
10425    }
10426}
10427
10428pub fn move_item(
10429    source: &Entity<Pane>,
10430    destination: &Entity<Pane>,
10431    item_id_to_move: EntityId,
10432    destination_index: usize,
10433    activate: bool,
10434    window: &mut Window,
10435    cx: &mut App,
10436) {
10437    let Some((item_ix, item_handle)) = source
10438        .read(cx)
10439        .items()
10440        .enumerate()
10441        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10442        .map(|(ix, item)| (ix, item.clone()))
10443    else {
10444        // Tab was closed during drag
10445        return;
10446    };
10447
10448    if source != destination {
10449        // Close item from previous pane
10450        source.update(cx, |source, cx| {
10451            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10452        });
10453    }
10454
10455    // This automatically removes duplicate items in the pane
10456    destination.update(cx, |destination, cx| {
10457        destination.add_item_inner(
10458            item_handle,
10459            activate,
10460            activate,
10461            activate,
10462            Some(destination_index),
10463            window,
10464            cx,
10465        );
10466        if activate {
10467            window.focus(&destination.focus_handle(cx), cx)
10468        }
10469    });
10470}
10471
10472pub fn move_active_item(
10473    source: &Entity<Pane>,
10474    destination: &Entity<Pane>,
10475    focus_destination: bool,
10476    close_if_empty: 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    source.update(cx, |source_pane, cx| {
10487        let item_id = active_item.item_id();
10488        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10489        destination.update(cx, |target_pane, cx| {
10490            target_pane.add_item(
10491                active_item,
10492                focus_destination,
10493                focus_destination,
10494                Some(target_pane.items_len()),
10495                window,
10496                cx,
10497            );
10498        });
10499    });
10500}
10501
10502pub fn clone_active_item(
10503    workspace_id: Option<WorkspaceId>,
10504    source: &Entity<Pane>,
10505    destination: &Entity<Pane>,
10506    focus_destination: bool,
10507    window: &mut Window,
10508    cx: &mut App,
10509) {
10510    if source == destination {
10511        return;
10512    }
10513    let Some(active_item) = source.read(cx).active_item() else {
10514        return;
10515    };
10516    if !active_item.can_split(cx) {
10517        return;
10518    }
10519    let destination = destination.downgrade();
10520    let task = active_item.clone_on_split(workspace_id, window, cx);
10521    window
10522        .spawn(cx, async move |cx| {
10523            let Some(clone) = task.await else {
10524                return;
10525            };
10526            destination
10527                .update_in(cx, |target_pane, window, cx| {
10528                    target_pane.add_item(
10529                        clone,
10530                        focus_destination,
10531                        focus_destination,
10532                        Some(target_pane.items_len()),
10533                        window,
10534                        cx,
10535                    );
10536                })
10537                .log_err();
10538        })
10539        .detach();
10540}
10541
10542#[derive(Debug)]
10543pub struct WorkspacePosition {
10544    pub window_bounds: Option<WindowBounds>,
10545    pub display: Option<Uuid>,
10546    pub centered_layout: bool,
10547}
10548
10549pub fn remote_workspace_position_from_db(
10550    connection_options: RemoteConnectionOptions,
10551    paths_to_open: &[PathBuf],
10552    cx: &App,
10553) -> Task<Result<WorkspacePosition>> {
10554    let paths = paths_to_open.to_vec();
10555    let db = WorkspaceDb::global(cx);
10556    let kvp = db::kvp::KeyValueStore::global(cx);
10557
10558    cx.background_spawn(async move {
10559        let remote_connection_id = db
10560            .get_or_create_remote_connection(connection_options)
10561            .await
10562            .context("fetching serialized ssh project")?;
10563        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10564
10565        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10566            (Some(WindowBounds::Windowed(bounds)), None)
10567        } else {
10568            let restorable_bounds = serialized_workspace
10569                .as_ref()
10570                .and_then(|workspace| {
10571                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10572                })
10573                .or_else(|| persistence::read_default_window_bounds(&kvp));
10574
10575            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10576                (Some(serialized_bounds), Some(serialized_display))
10577            } else {
10578                (None, None)
10579            }
10580        };
10581
10582        let centered_layout = serialized_workspace
10583            .as_ref()
10584            .map(|w| w.centered_layout)
10585            .unwrap_or(false);
10586
10587        Ok(WorkspacePosition {
10588            window_bounds,
10589            display,
10590            centered_layout,
10591        })
10592    })
10593}
10594
10595pub fn with_active_or_new_workspace(
10596    cx: &mut App,
10597    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10598) {
10599    match cx
10600        .active_window()
10601        .and_then(|w| w.downcast::<MultiWorkspace>())
10602    {
10603        Some(multi_workspace) => {
10604            cx.defer(move |cx| {
10605                multi_workspace
10606                    .update(cx, |multi_workspace, window, cx| {
10607                        let workspace = multi_workspace.workspace().clone();
10608                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10609                    })
10610                    .log_err();
10611            });
10612        }
10613        None => {
10614            let app_state = AppState::global(cx);
10615            open_new(
10616                OpenOptions::default(),
10617                app_state,
10618                cx,
10619                move |workspace, window, cx| f(workspace, window, cx),
10620            )
10621            .detach_and_log_err(cx);
10622        }
10623    }
10624}
10625
10626/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10627/// key. This migration path only runs once per panel per workspace.
10628fn load_legacy_panel_size(
10629    panel_key: &str,
10630    dock_position: DockPosition,
10631    workspace: &Workspace,
10632    cx: &mut App,
10633) -> Option<Pixels> {
10634    #[derive(Deserialize)]
10635    struct LegacyPanelState {
10636        #[serde(default)]
10637        width: Option<Pixels>,
10638        #[serde(default)]
10639        height: Option<Pixels>,
10640    }
10641
10642    let workspace_id = workspace
10643        .database_id()
10644        .map(|id| i64::from(id).to_string())
10645        .or_else(|| workspace.session_id())?;
10646
10647    let legacy_key = match panel_key {
10648        "ProjectPanel" => {
10649            format!("{}-{:?}", "ProjectPanel", workspace_id)
10650        }
10651        "OutlinePanel" => {
10652            format!("{}-{:?}", "OutlinePanel", workspace_id)
10653        }
10654        "GitPanel" => {
10655            format!("{}-{:?}", "GitPanel", workspace_id)
10656        }
10657        "TerminalPanel" => {
10658            format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10659        }
10660        _ => return None,
10661    };
10662
10663    let kvp = db::kvp::KeyValueStore::global(cx);
10664    let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10665    let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10666    let size = match dock_position {
10667        DockPosition::Bottom => state.height,
10668        DockPosition::Left | DockPosition::Right => state.width,
10669    }?;
10670
10671    cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10672        .detach_and_log_err(cx);
10673
10674    Some(size)
10675}
10676
10677#[cfg(test)]
10678mod tests {
10679    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10680
10681    use super::*;
10682    use crate::{
10683        dock::{PanelEvent, test::TestPanel},
10684        item::{
10685            ItemBufferKind, ItemEvent,
10686            test::{TestItem, TestProjectItem},
10687        },
10688    };
10689    use fs::FakeFs;
10690    use gpui::{
10691        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10692        UpdateGlobal, VisualTestContext, px,
10693    };
10694    use project::{Project, ProjectEntryId};
10695    use serde_json::json;
10696    use settings::SettingsStore;
10697    use util::path;
10698    use util::rel_path::rel_path;
10699
10700    #[gpui::test]
10701    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10702        init_test(cx);
10703
10704        let fs = FakeFs::new(cx.executor());
10705        let project = Project::test(fs, [], cx).await;
10706        let (workspace, cx) =
10707            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10708
10709        // Adding an item with no ambiguity renders the tab without detail.
10710        let item1 = cx.new(|cx| {
10711            let mut item = TestItem::new(cx);
10712            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10713            item
10714        });
10715        workspace.update_in(cx, |workspace, window, cx| {
10716            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10717        });
10718        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10719
10720        // Adding an item that creates ambiguity increases the level of detail on
10721        // both tabs.
10722        let item2 = cx.new_window_entity(|_window, cx| {
10723            let mut item = TestItem::new(cx);
10724            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10725            item
10726        });
10727        workspace.update_in(cx, |workspace, window, cx| {
10728            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10729        });
10730        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10731        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10732
10733        // Adding an item that creates ambiguity increases the level of detail only
10734        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10735        // we stop at the highest detail available.
10736        let item3 = cx.new(|cx| {
10737            let mut item = TestItem::new(cx);
10738            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10739            item
10740        });
10741        workspace.update_in(cx, |workspace, window, cx| {
10742            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10743        });
10744        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10745        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10746        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10747    }
10748
10749    #[gpui::test]
10750    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10751        init_test(cx);
10752
10753        let fs = FakeFs::new(cx.executor());
10754        fs.insert_tree(
10755            "/root1",
10756            json!({
10757                "one.txt": "",
10758                "two.txt": "",
10759            }),
10760        )
10761        .await;
10762        fs.insert_tree(
10763            "/root2",
10764            json!({
10765                "three.txt": "",
10766            }),
10767        )
10768        .await;
10769
10770        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10771        let (workspace, cx) =
10772            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10773        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10774        let worktree_id = project.update(cx, |project, cx| {
10775            project.worktrees(cx).next().unwrap().read(cx).id()
10776        });
10777
10778        let item1 = cx.new(|cx| {
10779            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10780        });
10781        let item2 = cx.new(|cx| {
10782            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10783        });
10784
10785        // Add an item to an empty pane
10786        workspace.update_in(cx, |workspace, window, cx| {
10787            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10788        });
10789        project.update(cx, |project, cx| {
10790            assert_eq!(
10791                project.active_entry(),
10792                project
10793                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10794                    .map(|e| e.id)
10795            );
10796        });
10797        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10798
10799        // Add a second item to a non-empty pane
10800        workspace.update_in(cx, |workspace, window, cx| {
10801            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10802        });
10803        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10804        project.update(cx, |project, cx| {
10805            assert_eq!(
10806                project.active_entry(),
10807                project
10808                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10809                    .map(|e| e.id)
10810            );
10811        });
10812
10813        // Close the active item
10814        pane.update_in(cx, |pane, window, cx| {
10815            pane.close_active_item(&Default::default(), window, cx)
10816        })
10817        .await
10818        .unwrap();
10819        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10820        project.update(cx, |project, cx| {
10821            assert_eq!(
10822                project.active_entry(),
10823                project
10824                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10825                    .map(|e| e.id)
10826            );
10827        });
10828
10829        // Add a project folder
10830        project
10831            .update(cx, |project, cx| {
10832                project.find_or_create_worktree("root2", true, cx)
10833            })
10834            .await
10835            .unwrap();
10836        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10837
10838        // Remove a project folder
10839        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10840        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10841    }
10842
10843    #[gpui::test]
10844    async fn test_close_window(cx: &mut TestAppContext) {
10845        init_test(cx);
10846
10847        let fs = FakeFs::new(cx.executor());
10848        fs.insert_tree("/root", json!({ "one": "" })).await;
10849
10850        let project = Project::test(fs, ["root".as_ref()], cx).await;
10851        let (workspace, cx) =
10852            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10853
10854        // When there are no dirty items, there's nothing to do.
10855        let item1 = cx.new(TestItem::new);
10856        workspace.update_in(cx, |w, window, cx| {
10857            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10858        });
10859        let task = workspace.update_in(cx, |w, window, cx| {
10860            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10861        });
10862        assert!(task.await.unwrap());
10863
10864        // When there are dirty untitled items, prompt to save each one. If the user
10865        // cancels any prompt, then abort.
10866        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10867        let item3 = cx.new(|cx| {
10868            TestItem::new(cx)
10869                .with_dirty(true)
10870                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10871        });
10872        workspace.update_in(cx, |w, window, cx| {
10873            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10874            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10875        });
10876        let task = workspace.update_in(cx, |w, window, cx| {
10877            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10878        });
10879        cx.executor().run_until_parked();
10880        cx.simulate_prompt_answer("Cancel"); // cancel save all
10881        cx.executor().run_until_parked();
10882        assert!(!cx.has_pending_prompt());
10883        assert!(!task.await.unwrap());
10884    }
10885
10886    #[gpui::test]
10887    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10888        init_test(cx);
10889
10890        let fs = FakeFs::new(cx.executor());
10891        fs.insert_tree("/root", json!({ "one": "" })).await;
10892
10893        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10894        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10895        let multi_workspace_handle =
10896            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10897        cx.run_until_parked();
10898
10899        multi_workspace_handle
10900            .update(cx, |mw, _window, cx| {
10901                mw.open_sidebar(cx);
10902            })
10903            .unwrap();
10904
10905        let workspace_a = multi_workspace_handle
10906            .read_with(cx, |mw, _| mw.workspace().clone())
10907            .unwrap();
10908
10909        let workspace_b = multi_workspace_handle
10910            .update(cx, |mw, window, cx| {
10911                mw.test_add_workspace(project_b, window, cx)
10912            })
10913            .unwrap();
10914
10915        // Activate workspace A
10916        multi_workspace_handle
10917            .update(cx, |mw, window, cx| {
10918                let workspace = mw.workspaces().next().unwrap().clone();
10919                mw.activate(workspace, window, cx);
10920            })
10921            .unwrap();
10922
10923        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10924
10925        // Workspace A has a clean item
10926        let item_a = cx.new(TestItem::new);
10927        workspace_a.update_in(cx, |w, window, cx| {
10928            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10929        });
10930
10931        // Workspace B has a dirty item
10932        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10933        workspace_b.update_in(cx, |w, window, cx| {
10934            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10935        });
10936
10937        // Verify workspace A is active
10938        multi_workspace_handle
10939            .read_with(cx, |mw, _| {
10940                assert_eq!(mw.workspace(), &workspace_a);
10941            })
10942            .unwrap();
10943
10944        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10945        multi_workspace_handle
10946            .update(cx, |mw, window, cx| {
10947                mw.close_window(&CloseWindow, window, cx);
10948            })
10949            .unwrap();
10950        cx.run_until_parked();
10951
10952        // Workspace B should now be active since it has dirty items that need attention
10953        multi_workspace_handle
10954            .read_with(cx, |mw, _| {
10955                assert_eq!(
10956                    mw.workspace(),
10957                    &workspace_b,
10958                    "workspace B should be activated when it prompts"
10959                );
10960            })
10961            .unwrap();
10962
10963        // User cancels the save prompt from workspace B
10964        cx.simulate_prompt_answer("Cancel");
10965        cx.run_until_parked();
10966
10967        // Window should still exist because workspace B's close was cancelled
10968        assert!(
10969            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10970            "window should still exist after cancelling one workspace's close"
10971        );
10972    }
10973
10974    #[gpui::test]
10975    async fn test_remove_workspace_prompts_for_unsaved_changes(cx: &mut TestAppContext) {
10976        init_test(cx);
10977
10978        let fs = FakeFs::new(cx.executor());
10979        fs.insert_tree("/root", json!({ "one": "" })).await;
10980
10981        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10982        let project_b = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10983        let multi_workspace_handle =
10984            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10985        cx.run_until_parked();
10986
10987        multi_workspace_handle
10988            .update(cx, |mw, _window, cx| mw.open_sidebar(cx))
10989            .unwrap();
10990
10991        let workspace_a = multi_workspace_handle
10992            .read_with(cx, |mw, _| mw.workspace().clone())
10993            .unwrap();
10994
10995        let workspace_b = multi_workspace_handle
10996            .update(cx, |mw, window, cx| {
10997                mw.test_add_workspace(project_b, window, cx)
10998            })
10999            .unwrap();
11000
11001        // Activate workspace A.
11002        multi_workspace_handle
11003            .update(cx, |mw, window, cx| {
11004                mw.activate(workspace_a.clone(), window, cx);
11005            })
11006            .unwrap();
11007
11008        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
11009
11010        // Workspace B has a dirty item.
11011        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
11012        workspace_b.update_in(cx, |w, window, cx| {
11013            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
11014        });
11015
11016        // Try to remove workspace B. It should prompt because of the dirty item.
11017        let remove_task = multi_workspace_handle
11018            .update(cx, |mw, window, cx| {
11019                mw.remove([workspace_b.clone()], |_, _, _| unreachable!(), window, cx)
11020            })
11021            .unwrap();
11022        cx.run_until_parked();
11023
11024        // The prompt should have activated workspace B.
11025        multi_workspace_handle
11026            .read_with(cx, |mw, _| {
11027                assert_eq!(
11028                    mw.workspace(),
11029                    &workspace_b,
11030                    "workspace B should be active while prompting"
11031                );
11032            })
11033            .unwrap();
11034
11035        // Cancel the prompt — user stays on workspace B.
11036        cx.simulate_prompt_answer("Cancel");
11037        cx.run_until_parked();
11038        let removed = remove_task.await.unwrap();
11039        assert!(!removed, "removal should have been cancelled");
11040
11041        multi_workspace_handle
11042            .read_with(cx, |mw, _| {
11043                assert_eq!(
11044                    mw.workspace(),
11045                    &workspace_b,
11046                    "user should stay on workspace B after cancelling"
11047                );
11048                assert_eq!(mw.workspaces().count(), 2, "both workspaces should remain");
11049            })
11050            .unwrap();
11051
11052        // Try again. This time accept the prompt.
11053        let remove_task = multi_workspace_handle
11054            .update(cx, |mw, window, cx| {
11055                // First switch back to A.
11056                mw.activate(workspace_a.clone(), window, cx);
11057                mw.remove([workspace_b.clone()], |_, _, _| unreachable!(), window, cx)
11058            })
11059            .unwrap();
11060        cx.run_until_parked();
11061
11062        // Accept the save prompt.
11063        cx.simulate_prompt_answer("Don't Save");
11064        cx.run_until_parked();
11065        let removed = remove_task.await.unwrap();
11066        assert!(removed, "removal should have succeeded");
11067
11068        // Should be back on workspace A, and B should be gone.
11069        multi_workspace_handle
11070            .read_with(cx, |mw, _| {
11071                assert_eq!(
11072                    mw.workspace(),
11073                    &workspace_a,
11074                    "should be back on workspace A after removing B"
11075                );
11076                assert_eq!(mw.workspaces().count(), 1, "only workspace A should remain");
11077            })
11078            .unwrap();
11079    }
11080
11081    #[gpui::test]
11082    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
11083        init_test(cx);
11084
11085        // Register TestItem as a serializable item
11086        cx.update(|cx| {
11087            register_serializable_item::<TestItem>(cx);
11088        });
11089
11090        let fs = FakeFs::new(cx.executor());
11091        fs.insert_tree("/root", json!({ "one": "" })).await;
11092
11093        let project = Project::test(fs, ["root".as_ref()], cx).await;
11094        let (workspace, cx) =
11095            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11096
11097        // When there are dirty untitled items, but they can serialize, then there is no prompt.
11098        let item1 = cx.new(|cx| {
11099            TestItem::new(cx)
11100                .with_dirty(true)
11101                .with_serialize(|| Some(Task::ready(Ok(()))))
11102        });
11103        let item2 = cx.new(|cx| {
11104            TestItem::new(cx)
11105                .with_dirty(true)
11106                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11107                .with_serialize(|| Some(Task::ready(Ok(()))))
11108        });
11109        workspace.update_in(cx, |w, window, cx| {
11110            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
11111            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
11112        });
11113        let task = workspace.update_in(cx, |w, window, cx| {
11114            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
11115        });
11116        assert!(task.await.unwrap());
11117    }
11118
11119    #[gpui::test]
11120    async fn test_close_pane_items(cx: &mut TestAppContext) {
11121        init_test(cx);
11122
11123        let fs = FakeFs::new(cx.executor());
11124
11125        let project = Project::test(fs, None, cx).await;
11126        let (workspace, cx) =
11127            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11128
11129        let item1 = cx.new(|cx| {
11130            TestItem::new(cx)
11131                .with_dirty(true)
11132                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11133        });
11134        let item2 = cx.new(|cx| {
11135            TestItem::new(cx)
11136                .with_dirty(true)
11137                .with_conflict(true)
11138                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11139        });
11140        let item3 = cx.new(|cx| {
11141            TestItem::new(cx)
11142                .with_dirty(true)
11143                .with_conflict(true)
11144                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
11145        });
11146        let item4 = cx.new(|cx| {
11147            TestItem::new(cx).with_dirty(true).with_project_items(&[{
11148                let project_item = TestProjectItem::new_untitled(cx);
11149                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11150                project_item
11151            }])
11152        });
11153        let pane = workspace.update_in(cx, |workspace, window, cx| {
11154            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
11155            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
11156            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
11157            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
11158            workspace.active_pane().clone()
11159        });
11160
11161        let close_items = pane.update_in(cx, |pane, window, cx| {
11162            pane.activate_item(1, true, true, window, cx);
11163            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
11164            let item1_id = item1.item_id();
11165            let item3_id = item3.item_id();
11166            let item4_id = item4.item_id();
11167            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
11168                [item1_id, item3_id, item4_id].contains(&id)
11169            })
11170        });
11171        cx.executor().run_until_parked();
11172
11173        assert!(cx.has_pending_prompt());
11174        cx.simulate_prompt_answer("Save all");
11175
11176        cx.executor().run_until_parked();
11177
11178        // Item 1 is saved. There's a prompt to save item 3.
11179        pane.update(cx, |pane, cx| {
11180            assert_eq!(item1.read(cx).save_count, 1);
11181            assert_eq!(item1.read(cx).save_as_count, 0);
11182            assert_eq!(item1.read(cx).reload_count, 0);
11183            assert_eq!(pane.items_len(), 3);
11184            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
11185        });
11186        assert!(cx.has_pending_prompt());
11187
11188        // Cancel saving item 3.
11189        cx.simulate_prompt_answer("Discard");
11190        cx.executor().run_until_parked();
11191
11192        // Item 3 is reloaded. There's a prompt to save item 4.
11193        pane.update(cx, |pane, cx| {
11194            assert_eq!(item3.read(cx).save_count, 0);
11195            assert_eq!(item3.read(cx).save_as_count, 0);
11196            assert_eq!(item3.read(cx).reload_count, 1);
11197            assert_eq!(pane.items_len(), 2);
11198            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
11199        });
11200
11201        // There's a prompt for a path for item 4.
11202        cx.simulate_new_path_selection(|_| Some(Default::default()));
11203        close_items.await.unwrap();
11204
11205        // The requested items are closed.
11206        pane.update(cx, |pane, cx| {
11207            assert_eq!(item4.read(cx).save_count, 0);
11208            assert_eq!(item4.read(cx).save_as_count, 1);
11209            assert_eq!(item4.read(cx).reload_count, 0);
11210            assert_eq!(pane.items_len(), 1);
11211            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
11212        });
11213    }
11214
11215    #[gpui::test]
11216    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
11217        init_test(cx);
11218
11219        let fs = FakeFs::new(cx.executor());
11220        let project = Project::test(fs, [], cx).await;
11221        let (workspace, cx) =
11222            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11223
11224        // Create several workspace items with single project entries, and two
11225        // workspace items with multiple project entries.
11226        let single_entry_items = (0..=4)
11227            .map(|project_entry_id| {
11228                cx.new(|cx| {
11229                    TestItem::new(cx)
11230                        .with_dirty(true)
11231                        .with_project_items(&[dirty_project_item(
11232                            project_entry_id,
11233                            &format!("{project_entry_id}.txt"),
11234                            cx,
11235                        )])
11236                })
11237            })
11238            .collect::<Vec<_>>();
11239        let item_2_3 = cx.new(|cx| {
11240            TestItem::new(cx)
11241                .with_dirty(true)
11242                .with_buffer_kind(ItemBufferKind::Multibuffer)
11243                .with_project_items(&[
11244                    single_entry_items[2].read(cx).project_items[0].clone(),
11245                    single_entry_items[3].read(cx).project_items[0].clone(),
11246                ])
11247        });
11248        let item_3_4 = cx.new(|cx| {
11249            TestItem::new(cx)
11250                .with_dirty(true)
11251                .with_buffer_kind(ItemBufferKind::Multibuffer)
11252                .with_project_items(&[
11253                    single_entry_items[3].read(cx).project_items[0].clone(),
11254                    single_entry_items[4].read(cx).project_items[0].clone(),
11255                ])
11256        });
11257
11258        // Create two panes that contain the following project entries:
11259        //   left pane:
11260        //     multi-entry items:   (2, 3)
11261        //     single-entry items:  0, 2, 3, 4
11262        //   right pane:
11263        //     single-entry items:  4, 1
11264        //     multi-entry items:   (3, 4)
11265        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
11266            let left_pane = workspace.active_pane().clone();
11267            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
11268            workspace.add_item_to_active_pane(
11269                single_entry_items[0].boxed_clone(),
11270                None,
11271                true,
11272                window,
11273                cx,
11274            );
11275            workspace.add_item_to_active_pane(
11276                single_entry_items[2].boxed_clone(),
11277                None,
11278                true,
11279                window,
11280                cx,
11281            );
11282            workspace.add_item_to_active_pane(
11283                single_entry_items[3].boxed_clone(),
11284                None,
11285                true,
11286                window,
11287                cx,
11288            );
11289            workspace.add_item_to_active_pane(
11290                single_entry_items[4].boxed_clone(),
11291                None,
11292                true,
11293                window,
11294                cx,
11295            );
11296
11297            let right_pane =
11298                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11299
11300            let boxed_clone = single_entry_items[1].boxed_clone();
11301            let right_pane = window.spawn(cx, async move |cx| {
11302                right_pane.await.inspect(|right_pane| {
11303                    right_pane
11304                        .update_in(cx, |pane, window, cx| {
11305                            pane.add_item(boxed_clone, true, true, None, window, cx);
11306                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11307                        })
11308                        .unwrap();
11309                })
11310            });
11311
11312            (left_pane, right_pane)
11313        });
11314        let right_pane = right_pane.await.unwrap();
11315        cx.focus(&right_pane);
11316
11317        let close = right_pane.update_in(cx, |pane, window, cx| {
11318            pane.close_all_items(&CloseAllItems::default(), window, cx)
11319                .unwrap()
11320        });
11321        cx.executor().run_until_parked();
11322
11323        let msg = cx.pending_prompt().unwrap().0;
11324        assert!(msg.contains("1.txt"));
11325        assert!(!msg.contains("2.txt"));
11326        assert!(!msg.contains("3.txt"));
11327        assert!(!msg.contains("4.txt"));
11328
11329        // With best-effort close, cancelling item 1 keeps it open but items 4
11330        // and (3,4) still close since their entries exist in left pane.
11331        cx.simulate_prompt_answer("Cancel");
11332        close.await;
11333
11334        right_pane.read_with(cx, |pane, _| {
11335            assert_eq!(pane.items_len(), 1);
11336        });
11337
11338        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11339        left_pane
11340            .update_in(cx, |left_pane, window, cx| {
11341                left_pane.close_item_by_id(
11342                    single_entry_items[3].entity_id(),
11343                    SaveIntent::Skip,
11344                    window,
11345                    cx,
11346                )
11347            })
11348            .await
11349            .unwrap();
11350
11351        let close = left_pane.update_in(cx, |pane, window, cx| {
11352            pane.close_all_items(&CloseAllItems::default(), window, cx)
11353                .unwrap()
11354        });
11355        cx.executor().run_until_parked();
11356
11357        let details = cx.pending_prompt().unwrap().1;
11358        assert!(details.contains("0.txt"));
11359        assert!(details.contains("3.txt"));
11360        assert!(details.contains("4.txt"));
11361        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11362        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11363        // assert!(!details.contains("2.txt"));
11364
11365        cx.simulate_prompt_answer("Save all");
11366        cx.executor().run_until_parked();
11367        close.await;
11368
11369        left_pane.read_with(cx, |pane, _| {
11370            assert_eq!(pane.items_len(), 0);
11371        });
11372    }
11373
11374    #[gpui::test]
11375    async fn test_autosave(cx: &mut gpui::TestAppContext) {
11376        init_test(cx);
11377
11378        let fs = FakeFs::new(cx.executor());
11379        let project = Project::test(fs, [], cx).await;
11380        let (workspace, cx) =
11381            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11382        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11383
11384        let item = cx.new(|cx| {
11385            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11386        });
11387        let item_id = item.entity_id();
11388        workspace.update_in(cx, |workspace, window, cx| {
11389            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11390        });
11391
11392        // Autosave on window change.
11393        item.update(cx, |item, cx| {
11394            SettingsStore::update_global(cx, |settings, cx| {
11395                settings.update_user_settings(cx, |settings| {
11396                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11397                })
11398            });
11399            item.is_dirty = true;
11400        });
11401
11402        // Deactivating the window saves the file.
11403        cx.deactivate_window();
11404        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11405
11406        // Re-activating the window doesn't save the file.
11407        cx.update(|window, _| window.activate_window());
11408        cx.executor().run_until_parked();
11409        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11410
11411        // Autosave on focus change.
11412        item.update_in(cx, |item, window, cx| {
11413            cx.focus_self(window);
11414            SettingsStore::update_global(cx, |settings, cx| {
11415                settings.update_user_settings(cx, |settings| {
11416                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11417                })
11418            });
11419            item.is_dirty = true;
11420        });
11421        // Blurring the item saves the file.
11422        item.update_in(cx, |_, window, _| window.blur());
11423        cx.executor().run_until_parked();
11424        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11425
11426        // Deactivating the window still saves the file.
11427        item.update_in(cx, |item, window, cx| {
11428            cx.focus_self(window);
11429            item.is_dirty = true;
11430        });
11431        cx.deactivate_window();
11432        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11433
11434        // Autosave after delay.
11435        item.update(cx, |item, cx| {
11436            SettingsStore::update_global(cx, |settings, cx| {
11437                settings.update_user_settings(cx, |settings| {
11438                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11439                        milliseconds: 500.into(),
11440                    });
11441                })
11442            });
11443            item.is_dirty = true;
11444            cx.emit(ItemEvent::Edit);
11445        });
11446
11447        // Delay hasn't fully expired, so the file is still dirty and unsaved.
11448        cx.executor().advance_clock(Duration::from_millis(250));
11449        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11450
11451        // After delay expires, the file is saved.
11452        cx.executor().advance_clock(Duration::from_millis(250));
11453        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11454
11455        // Autosave after delay, should save earlier than delay if tab is closed
11456        item.update(cx, |item, cx| {
11457            item.is_dirty = true;
11458            cx.emit(ItemEvent::Edit);
11459        });
11460        cx.executor().advance_clock(Duration::from_millis(250));
11461        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11462
11463        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11464        pane.update_in(cx, |pane, window, cx| {
11465            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11466        })
11467        .await
11468        .unwrap();
11469        assert!(!cx.has_pending_prompt());
11470        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11471
11472        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11473        workspace.update_in(cx, |workspace, window, cx| {
11474            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11475        });
11476        item.update_in(cx, |item, _window, cx| {
11477            item.is_dirty = true;
11478            for project_item in &mut item.project_items {
11479                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11480            }
11481        });
11482        cx.run_until_parked();
11483        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11484
11485        // Autosave on focus change, ensuring closing the tab counts as such.
11486        item.update(cx, |item, cx| {
11487            SettingsStore::update_global(cx, |settings, cx| {
11488                settings.update_user_settings(cx, |settings| {
11489                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11490                })
11491            });
11492            item.is_dirty = true;
11493            for project_item in &mut item.project_items {
11494                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11495            }
11496        });
11497
11498        pane.update_in(cx, |pane, window, cx| {
11499            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11500        })
11501        .await
11502        .unwrap();
11503        assert!(!cx.has_pending_prompt());
11504        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11505
11506        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11507        workspace.update_in(cx, |workspace, window, cx| {
11508            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11509        });
11510        item.update_in(cx, |item, window, cx| {
11511            item.project_items[0].update(cx, |item, _| {
11512                item.entry_id = None;
11513            });
11514            item.is_dirty = true;
11515            window.blur();
11516        });
11517        cx.run_until_parked();
11518        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11519
11520        // Ensure autosave is prevented for deleted files also when closing the buffer.
11521        let _close_items = pane.update_in(cx, |pane, window, cx| {
11522            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11523        });
11524        cx.run_until_parked();
11525        assert!(cx.has_pending_prompt());
11526        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11527    }
11528
11529    #[gpui::test]
11530    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11531        init_test(cx);
11532
11533        let fs = FakeFs::new(cx.executor());
11534        let project = Project::test(fs, [], cx).await;
11535        let (workspace, cx) =
11536            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11537
11538        // Create a multibuffer-like item with two child focus handles,
11539        // simulating individual buffer editors within a multibuffer.
11540        let item = cx.new(|cx| {
11541            TestItem::new(cx)
11542                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11543                .with_child_focus_handles(2, cx)
11544        });
11545        workspace.update_in(cx, |workspace, window, cx| {
11546            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11547        });
11548
11549        // Set autosave to OnFocusChange and focus the first child handle,
11550        // simulating the user's cursor being inside one of the multibuffer's excerpts.
11551        item.update_in(cx, |item, window, cx| {
11552            SettingsStore::update_global(cx, |settings, cx| {
11553                settings.update_user_settings(cx, |settings| {
11554                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11555                })
11556            });
11557            item.is_dirty = true;
11558            window.focus(&item.child_focus_handles[0], cx);
11559        });
11560        cx.executor().run_until_parked();
11561        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11562
11563        // Moving focus from one child to another within the same item should
11564        // NOT trigger autosave — focus is still within the item's focus hierarchy.
11565        item.update_in(cx, |item, window, cx| {
11566            window.focus(&item.child_focus_handles[1], cx);
11567        });
11568        cx.executor().run_until_parked();
11569        item.read_with(cx, |item, _| {
11570            assert_eq!(
11571                item.save_count, 0,
11572                "Switching focus between children within the same item should not autosave"
11573            );
11574        });
11575
11576        // Blurring the item saves the file. This is the core regression scenario:
11577        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11578        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11579        // the leaf is always a child focus handle, so `on_blur` never detected
11580        // focus leaving the item.
11581        item.update_in(cx, |_, window, _| window.blur());
11582        cx.executor().run_until_parked();
11583        item.read_with(cx, |item, _| {
11584            assert_eq!(
11585                item.save_count, 1,
11586                "Blurring should trigger autosave when focus was on a child of the item"
11587            );
11588        });
11589
11590        // Deactivating the window should also trigger autosave when a child of
11591        // the multibuffer item currently owns focus.
11592        item.update_in(cx, |item, window, cx| {
11593            item.is_dirty = true;
11594            window.focus(&item.child_focus_handles[0], cx);
11595        });
11596        cx.executor().run_until_parked();
11597        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11598
11599        cx.deactivate_window();
11600        item.read_with(cx, |item, _| {
11601            assert_eq!(
11602                item.save_count, 2,
11603                "Deactivating window should trigger autosave when focus was on a child"
11604            );
11605        });
11606    }
11607
11608    #[gpui::test]
11609    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11610        init_test(cx);
11611
11612        let fs = FakeFs::new(cx.executor());
11613
11614        let project = Project::test(fs, [], cx).await;
11615        let (workspace, cx) =
11616            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11617
11618        let item = cx.new(|cx| {
11619            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11620        });
11621        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11622        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11623        let toolbar_notify_count = Rc::new(RefCell::new(0));
11624
11625        workspace.update_in(cx, |workspace, window, cx| {
11626            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11627            let toolbar_notification_count = toolbar_notify_count.clone();
11628            cx.observe_in(&toolbar, window, move |_, _, _, _| {
11629                *toolbar_notification_count.borrow_mut() += 1
11630            })
11631            .detach();
11632        });
11633
11634        pane.read_with(cx, |pane, _| {
11635            assert!(!pane.can_navigate_backward());
11636            assert!(!pane.can_navigate_forward());
11637        });
11638
11639        item.update_in(cx, |item, _, cx| {
11640            item.set_state("one".to_string(), cx);
11641        });
11642
11643        // Toolbar must be notified to re-render the navigation buttons
11644        assert_eq!(*toolbar_notify_count.borrow(), 1);
11645
11646        pane.read_with(cx, |pane, _| {
11647            assert!(pane.can_navigate_backward());
11648            assert!(!pane.can_navigate_forward());
11649        });
11650
11651        workspace
11652            .update_in(cx, |workspace, window, cx| {
11653                workspace.go_back(pane.downgrade(), window, cx)
11654            })
11655            .await
11656            .unwrap();
11657
11658        assert_eq!(*toolbar_notify_count.borrow(), 2);
11659        pane.read_with(cx, |pane, _| {
11660            assert!(!pane.can_navigate_backward());
11661            assert!(pane.can_navigate_forward());
11662        });
11663    }
11664
11665    /// Tests that the navigation history deduplicates entries for the same item.
11666    ///
11667    /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11668    /// the navigation history deduplicates by keeping only the most recent visit to each item,
11669    /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11670    /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11671    /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11672    ///
11673    /// This behavior prevents the navigation history from growing unnecessarily large and provides
11674    /// a better user experience by eliminating redundant navigation steps when jumping between files.
11675    #[gpui::test]
11676    async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11677        init_test(cx);
11678
11679        let fs = FakeFs::new(cx.executor());
11680        let project = Project::test(fs, [], cx).await;
11681        let (workspace, cx) =
11682            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11683
11684        let item_a = cx.new(|cx| {
11685            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11686        });
11687        let item_b = cx.new(|cx| {
11688            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11689        });
11690        let item_c = cx.new(|cx| {
11691            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11692        });
11693
11694        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11695
11696        workspace.update_in(cx, |workspace, window, cx| {
11697            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11698            workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11699            workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11700        });
11701
11702        workspace.update_in(cx, |workspace, window, cx| {
11703            workspace.activate_item(&item_a, false, false, window, cx);
11704        });
11705        cx.run_until_parked();
11706
11707        workspace.update_in(cx, |workspace, window, cx| {
11708            workspace.activate_item(&item_b, false, false, window, cx);
11709        });
11710        cx.run_until_parked();
11711
11712        workspace.update_in(cx, |workspace, window, cx| {
11713            workspace.activate_item(&item_a, false, false, window, cx);
11714        });
11715        cx.run_until_parked();
11716
11717        workspace.update_in(cx, |workspace, window, cx| {
11718            workspace.activate_item(&item_b, false, false, window, cx);
11719        });
11720        cx.run_until_parked();
11721
11722        workspace.update_in(cx, |workspace, window, cx| {
11723            workspace.activate_item(&item_a, false, false, window, cx);
11724        });
11725        cx.run_until_parked();
11726
11727        workspace.update_in(cx, |workspace, window, cx| {
11728            workspace.activate_item(&item_b, false, false, window, cx);
11729        });
11730        cx.run_until_parked();
11731
11732        workspace.update_in(cx, |workspace, window, cx| {
11733            workspace.activate_item(&item_c, false, false, window, cx);
11734        });
11735        cx.run_until_parked();
11736
11737        let backward_count = pane.read_with(cx, |pane, cx| {
11738            let mut count = 0;
11739            pane.nav_history().for_each_entry(cx, &mut |_, _| {
11740                count += 1;
11741            });
11742            count
11743        });
11744        assert!(
11745            backward_count <= 4,
11746            "Should have at most 4 entries, got {}",
11747            backward_count
11748        );
11749
11750        workspace
11751            .update_in(cx, |workspace, window, cx| {
11752                workspace.go_back(pane.downgrade(), window, cx)
11753            })
11754            .await
11755            .unwrap();
11756
11757        let active_item = workspace.read_with(cx, |workspace, cx| {
11758            workspace.active_item(cx).unwrap().item_id()
11759        });
11760        assert_eq!(
11761            active_item,
11762            item_b.entity_id(),
11763            "After first go_back, should be at item B"
11764        );
11765
11766        workspace
11767            .update_in(cx, |workspace, window, cx| {
11768                workspace.go_back(pane.downgrade(), window, cx)
11769            })
11770            .await
11771            .unwrap();
11772
11773        let active_item = workspace.read_with(cx, |workspace, cx| {
11774            workspace.active_item(cx).unwrap().item_id()
11775        });
11776        assert_eq!(
11777            active_item,
11778            item_a.entity_id(),
11779            "After second go_back, should be at item A"
11780        );
11781
11782        pane.read_with(cx, |pane, _| {
11783            assert!(pane.can_navigate_forward(), "Should be able to go forward");
11784        });
11785    }
11786
11787    #[gpui::test]
11788    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11789        init_test(cx);
11790        let fs = FakeFs::new(cx.executor());
11791        let project = Project::test(fs, [], cx).await;
11792        let (multi_workspace, cx) =
11793            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11794        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11795
11796        workspace.update_in(cx, |workspace, window, cx| {
11797            let first_item = cx.new(|cx| {
11798                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11799            });
11800            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11801            workspace.split_pane(
11802                workspace.active_pane().clone(),
11803                SplitDirection::Right,
11804                window,
11805                cx,
11806            );
11807            workspace.split_pane(
11808                workspace.active_pane().clone(),
11809                SplitDirection::Right,
11810                window,
11811                cx,
11812            );
11813        });
11814
11815        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11816            let panes = workspace.center.panes();
11817            assert!(panes.len() >= 2);
11818            (
11819                panes.first().expect("at least one pane").entity_id(),
11820                panes.last().expect("at least one pane").entity_id(),
11821            )
11822        });
11823
11824        workspace.update_in(cx, |workspace, window, cx| {
11825            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11826        });
11827        workspace.update(cx, |workspace, _| {
11828            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11829            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11830        });
11831
11832        cx.dispatch_action(ActivateLastPane);
11833
11834        workspace.update(cx, |workspace, _| {
11835            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11836        });
11837    }
11838
11839    #[gpui::test]
11840    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11841        init_test(cx);
11842        let fs = FakeFs::new(cx.executor());
11843
11844        let project = Project::test(fs, [], cx).await;
11845        let (workspace, cx) =
11846            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11847
11848        let panel = workspace.update_in(cx, |workspace, window, cx| {
11849            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11850            workspace.add_panel(panel.clone(), window, cx);
11851
11852            workspace
11853                .right_dock()
11854                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11855
11856            panel
11857        });
11858
11859        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11860        pane.update_in(cx, |pane, window, cx| {
11861            let item = cx.new(TestItem::new);
11862            pane.add_item(Box::new(item), true, true, None, window, cx);
11863        });
11864
11865        // Transfer focus from center to panel
11866        workspace.update_in(cx, |workspace, window, cx| {
11867            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11868        });
11869
11870        workspace.update_in(cx, |workspace, window, cx| {
11871            assert!(workspace.right_dock().read(cx).is_open());
11872            assert!(!panel.is_zoomed(window, cx));
11873            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11874        });
11875
11876        // Transfer focus from panel to center
11877        workspace.update_in(cx, |workspace, window, cx| {
11878            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11879        });
11880
11881        workspace.update_in(cx, |workspace, window, cx| {
11882            assert!(workspace.right_dock().read(cx).is_open());
11883            assert!(!panel.is_zoomed(window, cx));
11884            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11885            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11886        });
11887
11888        // Close the dock
11889        workspace.update_in(cx, |workspace, window, cx| {
11890            workspace.toggle_dock(DockPosition::Right, window, cx);
11891        });
11892
11893        workspace.update_in(cx, |workspace, window, cx| {
11894            assert!(!workspace.right_dock().read(cx).is_open());
11895            assert!(!panel.is_zoomed(window, cx));
11896            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11897            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11898        });
11899
11900        // Open the dock
11901        workspace.update_in(cx, |workspace, window, cx| {
11902            workspace.toggle_dock(DockPosition::Right, window, cx);
11903        });
11904
11905        workspace.update_in(cx, |workspace, window, cx| {
11906            assert!(workspace.right_dock().read(cx).is_open());
11907            assert!(!panel.is_zoomed(window, cx));
11908            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11909        });
11910
11911        // Focus and zoom panel
11912        panel.update_in(cx, |panel, window, cx| {
11913            cx.focus_self(window);
11914            panel.set_zoomed(true, window, cx)
11915        });
11916
11917        workspace.update_in(cx, |workspace, window, cx| {
11918            assert!(workspace.right_dock().read(cx).is_open());
11919            assert!(panel.is_zoomed(window, cx));
11920            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11921        });
11922
11923        // Transfer focus to the center closes the dock
11924        workspace.update_in(cx, |workspace, window, cx| {
11925            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11926        });
11927
11928        workspace.update_in(cx, |workspace, window, cx| {
11929            assert!(!workspace.right_dock().read(cx).is_open());
11930            assert!(panel.is_zoomed(window, cx));
11931            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11932        });
11933
11934        // Transferring focus back to the panel keeps it zoomed
11935        workspace.update_in(cx, |workspace, window, cx| {
11936            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11937        });
11938
11939        workspace.update_in(cx, |workspace, window, cx| {
11940            assert!(workspace.right_dock().read(cx).is_open());
11941            assert!(panel.is_zoomed(window, cx));
11942            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11943        });
11944
11945        // Close the dock while it is zoomed
11946        workspace.update_in(cx, |workspace, window, cx| {
11947            workspace.toggle_dock(DockPosition::Right, window, cx)
11948        });
11949
11950        workspace.update_in(cx, |workspace, window, cx| {
11951            assert!(!workspace.right_dock().read(cx).is_open());
11952            assert!(panel.is_zoomed(window, cx));
11953            assert!(workspace.zoomed.is_none());
11954            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11955        });
11956
11957        // Opening the dock, when it's zoomed, retains focus
11958        workspace.update_in(cx, |workspace, window, cx| {
11959            workspace.toggle_dock(DockPosition::Right, window, cx)
11960        });
11961
11962        workspace.update_in(cx, |workspace, window, cx| {
11963            assert!(workspace.right_dock().read(cx).is_open());
11964            assert!(panel.is_zoomed(window, cx));
11965            assert!(workspace.zoomed.is_some());
11966            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11967        });
11968
11969        // Unzoom and close the panel, zoom the active pane.
11970        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11971        workspace.update_in(cx, |workspace, window, cx| {
11972            workspace.toggle_dock(DockPosition::Right, window, cx)
11973        });
11974        pane.update_in(cx, |pane, window, cx| {
11975            pane.toggle_zoom(&Default::default(), window, cx)
11976        });
11977
11978        // Opening a dock unzooms the pane.
11979        workspace.update_in(cx, |workspace, window, cx| {
11980            workspace.toggle_dock(DockPosition::Right, window, cx)
11981        });
11982        workspace.update_in(cx, |workspace, window, cx| {
11983            let pane = pane.read(cx);
11984            assert!(!pane.is_zoomed());
11985            assert!(!pane.focus_handle(cx).is_focused(window));
11986            assert!(workspace.right_dock().read(cx).is_open());
11987            assert!(workspace.zoomed.is_none());
11988        });
11989    }
11990
11991    #[gpui::test]
11992    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11993        init_test(cx);
11994        let fs = FakeFs::new(cx.executor());
11995
11996        let project = Project::test(fs, [], cx).await;
11997        let (workspace, cx) =
11998            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11999
12000        let panel = workspace.update_in(cx, |workspace, window, cx| {
12001            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12002            workspace.add_panel(panel.clone(), window, cx);
12003            panel
12004        });
12005
12006        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12007        pane.update_in(cx, |pane, window, cx| {
12008            let item = cx.new(TestItem::new);
12009            pane.add_item(Box::new(item), true, true, None, window, cx);
12010        });
12011
12012        // Enable close_panel_on_toggle
12013        cx.update_global(|store: &mut SettingsStore, cx| {
12014            store.update_user_settings(cx, |settings| {
12015                settings.workspace.close_panel_on_toggle = Some(true);
12016            });
12017        });
12018
12019        // Panel starts closed. Toggling should open and focus it.
12020        workspace.update_in(cx, |workspace, window, cx| {
12021            assert!(!workspace.right_dock().read(cx).is_open());
12022            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12023        });
12024
12025        workspace.update_in(cx, |workspace, window, cx| {
12026            assert!(
12027                workspace.right_dock().read(cx).is_open(),
12028                "Dock should be open after toggling from center"
12029            );
12030            assert!(
12031                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12032                "Panel should be focused after toggling from center"
12033            );
12034        });
12035
12036        // Panel is open and focused. Toggling should close the panel and
12037        // return focus to the center.
12038        workspace.update_in(cx, |workspace, window, cx| {
12039            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12040        });
12041
12042        workspace.update_in(cx, |workspace, window, cx| {
12043            assert!(
12044                !workspace.right_dock().read(cx).is_open(),
12045                "Dock should be closed after toggling from focused panel"
12046            );
12047            assert!(
12048                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12049                "Panel should not be focused after toggling from focused panel"
12050            );
12051        });
12052
12053        // Open the dock and focus something else so the panel is open but not
12054        // focused. Toggling should focus the panel (not close it).
12055        workspace.update_in(cx, |workspace, window, cx| {
12056            workspace
12057                .right_dock()
12058                .update(cx, |dock, cx| dock.set_open(true, window, cx));
12059            window.focus(&pane.read(cx).focus_handle(cx), cx);
12060        });
12061
12062        workspace.update_in(cx, |workspace, window, cx| {
12063            assert!(workspace.right_dock().read(cx).is_open());
12064            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12065            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12066        });
12067
12068        workspace.update_in(cx, |workspace, window, cx| {
12069            assert!(
12070                workspace.right_dock().read(cx).is_open(),
12071                "Dock should remain open when toggling focuses an open-but-unfocused panel"
12072            );
12073            assert!(
12074                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12075                "Panel should be focused after toggling an open-but-unfocused panel"
12076            );
12077        });
12078
12079        // Now disable the setting and verify the original behavior: toggling
12080        // from a focused panel moves focus to center but leaves the dock open.
12081        cx.update_global(|store: &mut SettingsStore, cx| {
12082            store.update_user_settings(cx, |settings| {
12083                settings.workspace.close_panel_on_toggle = Some(false);
12084            });
12085        });
12086
12087        workspace.update_in(cx, |workspace, window, cx| {
12088            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12089        });
12090
12091        workspace.update_in(cx, |workspace, window, cx| {
12092            assert!(
12093                workspace.right_dock().read(cx).is_open(),
12094                "Dock should remain open when setting is disabled"
12095            );
12096            assert!(
12097                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12098                "Panel should not be focused after toggling with setting disabled"
12099            );
12100        });
12101    }
12102
12103    #[gpui::test]
12104    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
12105        init_test(cx);
12106        let fs = FakeFs::new(cx.executor());
12107
12108        let project = Project::test(fs, [], cx).await;
12109        let (workspace, cx) =
12110            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12111
12112        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
12113            workspace.active_pane().clone()
12114        });
12115
12116        // Add an item to the pane so it can be zoomed
12117        workspace.update_in(cx, |workspace, window, cx| {
12118            let item = cx.new(TestItem::new);
12119            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
12120        });
12121
12122        // Initially not zoomed
12123        workspace.update_in(cx, |workspace, _window, cx| {
12124            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
12125            assert!(
12126                workspace.zoomed.is_none(),
12127                "Workspace should track no zoomed pane"
12128            );
12129            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
12130        });
12131
12132        // Zoom In
12133        pane.update_in(cx, |pane, window, cx| {
12134            pane.zoom_in(&crate::ZoomIn, window, cx);
12135        });
12136
12137        workspace.update_in(cx, |workspace, window, cx| {
12138            assert!(
12139                pane.read(cx).is_zoomed(),
12140                "Pane should be zoomed after ZoomIn"
12141            );
12142            assert!(
12143                workspace.zoomed.is_some(),
12144                "Workspace should track the zoomed pane"
12145            );
12146            assert!(
12147                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
12148                "ZoomIn should focus the pane"
12149            );
12150        });
12151
12152        // Zoom In again is a no-op
12153        pane.update_in(cx, |pane, window, cx| {
12154            pane.zoom_in(&crate::ZoomIn, window, cx);
12155        });
12156
12157        workspace.update_in(cx, |workspace, window, cx| {
12158            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
12159            assert!(
12160                workspace.zoomed.is_some(),
12161                "Workspace still tracks zoomed pane"
12162            );
12163            assert!(
12164                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
12165                "Pane remains focused after repeated ZoomIn"
12166            );
12167        });
12168
12169        // Zoom Out
12170        pane.update_in(cx, |pane, window, cx| {
12171            pane.zoom_out(&crate::ZoomOut, window, cx);
12172        });
12173
12174        workspace.update_in(cx, |workspace, _window, cx| {
12175            assert!(
12176                !pane.read(cx).is_zoomed(),
12177                "Pane should unzoom after ZoomOut"
12178            );
12179            assert!(
12180                workspace.zoomed.is_none(),
12181                "Workspace clears zoom tracking after ZoomOut"
12182            );
12183        });
12184
12185        // Zoom Out again is a no-op
12186        pane.update_in(cx, |pane, window, cx| {
12187            pane.zoom_out(&crate::ZoomOut, window, cx);
12188        });
12189
12190        workspace.update_in(cx, |workspace, _window, cx| {
12191            assert!(
12192                !pane.read(cx).is_zoomed(),
12193                "Second ZoomOut keeps pane unzoomed"
12194            );
12195            assert!(
12196                workspace.zoomed.is_none(),
12197                "Workspace remains without zoomed pane"
12198            );
12199        });
12200    }
12201
12202    #[gpui::test]
12203    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
12204        init_test(cx);
12205        let fs = FakeFs::new(cx.executor());
12206
12207        let project = Project::test(fs, [], cx).await;
12208        let (workspace, cx) =
12209            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12210        workspace.update_in(cx, |workspace, window, cx| {
12211            // Open two docks
12212            let left_dock = workspace.dock_at_position(DockPosition::Left);
12213            let right_dock = workspace.dock_at_position(DockPosition::Right);
12214
12215            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12216            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12217
12218            assert!(left_dock.read(cx).is_open());
12219            assert!(right_dock.read(cx).is_open());
12220        });
12221
12222        workspace.update_in(cx, |workspace, window, cx| {
12223            // Toggle all docks - should close both
12224            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12225
12226            let left_dock = workspace.dock_at_position(DockPosition::Left);
12227            let right_dock = workspace.dock_at_position(DockPosition::Right);
12228            assert!(!left_dock.read(cx).is_open());
12229            assert!(!right_dock.read(cx).is_open());
12230        });
12231
12232        workspace.update_in(cx, |workspace, window, cx| {
12233            // Toggle again - should reopen both
12234            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12235
12236            let left_dock = workspace.dock_at_position(DockPosition::Left);
12237            let right_dock = workspace.dock_at_position(DockPosition::Right);
12238            assert!(left_dock.read(cx).is_open());
12239            assert!(right_dock.read(cx).is_open());
12240        });
12241    }
12242
12243    #[gpui::test]
12244    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
12245        init_test(cx);
12246        let fs = FakeFs::new(cx.executor());
12247
12248        let project = Project::test(fs, [], cx).await;
12249        let (workspace, cx) =
12250            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12251        workspace.update_in(cx, |workspace, window, cx| {
12252            // Open two docks
12253            let left_dock = workspace.dock_at_position(DockPosition::Left);
12254            let right_dock = workspace.dock_at_position(DockPosition::Right);
12255
12256            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12257            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12258
12259            assert!(left_dock.read(cx).is_open());
12260            assert!(right_dock.read(cx).is_open());
12261        });
12262
12263        workspace.update_in(cx, |workspace, window, cx| {
12264            // Close them manually
12265            workspace.toggle_dock(DockPosition::Left, window, cx);
12266            workspace.toggle_dock(DockPosition::Right, window, cx);
12267
12268            let left_dock = workspace.dock_at_position(DockPosition::Left);
12269            let right_dock = workspace.dock_at_position(DockPosition::Right);
12270            assert!(!left_dock.read(cx).is_open());
12271            assert!(!right_dock.read(cx).is_open());
12272        });
12273
12274        workspace.update_in(cx, |workspace, window, cx| {
12275            // Toggle all docks - only last closed (right dock) should reopen
12276            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12277
12278            let left_dock = workspace.dock_at_position(DockPosition::Left);
12279            let right_dock = workspace.dock_at_position(DockPosition::Right);
12280            assert!(!left_dock.read(cx).is_open());
12281            assert!(right_dock.read(cx).is_open());
12282        });
12283    }
12284
12285    #[gpui::test]
12286    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
12287        init_test(cx);
12288        let fs = FakeFs::new(cx.executor());
12289        let project = Project::test(fs, [], cx).await;
12290        let (multi_workspace, cx) =
12291            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12292        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12293
12294        // Open two docks (left and right) with one panel each
12295        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12296            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12297            workspace.add_panel(left_panel.clone(), window, cx);
12298
12299            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12300            workspace.add_panel(right_panel.clone(), window, cx);
12301
12302            workspace.toggle_dock(DockPosition::Left, window, cx);
12303            workspace.toggle_dock(DockPosition::Right, window, cx);
12304
12305            // Verify initial state
12306            assert!(
12307                workspace.left_dock().read(cx).is_open(),
12308                "Left dock should be open"
12309            );
12310            assert_eq!(
12311                workspace
12312                    .left_dock()
12313                    .read(cx)
12314                    .visible_panel()
12315                    .unwrap()
12316                    .panel_id(),
12317                left_panel.panel_id(),
12318                "Left panel should be visible in left dock"
12319            );
12320            assert!(
12321                workspace.right_dock().read(cx).is_open(),
12322                "Right dock should be open"
12323            );
12324            assert_eq!(
12325                workspace
12326                    .right_dock()
12327                    .read(cx)
12328                    .visible_panel()
12329                    .unwrap()
12330                    .panel_id(),
12331                right_panel.panel_id(),
12332                "Right panel should be visible in right dock"
12333            );
12334            assert!(
12335                !workspace.bottom_dock().read(cx).is_open(),
12336                "Bottom dock should be closed"
12337            );
12338
12339            (left_panel, right_panel)
12340        });
12341
12342        // Focus the left panel and move it to the next position (bottom dock)
12343        workspace.update_in(cx, |workspace, window, cx| {
12344            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12345            assert!(
12346                left_panel.read(cx).focus_handle(cx).is_focused(window),
12347                "Left panel should be focused"
12348            );
12349        });
12350
12351        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12352
12353        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12354        workspace.update(cx, |workspace, cx| {
12355            assert!(
12356                !workspace.left_dock().read(cx).is_open(),
12357                "Left dock should be closed"
12358            );
12359            assert!(
12360                workspace.bottom_dock().read(cx).is_open(),
12361                "Bottom dock should now be open"
12362            );
12363            assert_eq!(
12364                left_panel.read(cx).position,
12365                DockPosition::Bottom,
12366                "Left panel should now be in the bottom dock"
12367            );
12368            assert_eq!(
12369                workspace
12370                    .bottom_dock()
12371                    .read(cx)
12372                    .visible_panel()
12373                    .unwrap()
12374                    .panel_id(),
12375                left_panel.panel_id(),
12376                "Left panel should be the visible panel in the bottom dock"
12377            );
12378        });
12379
12380        // Toggle all docks off
12381        workspace.update_in(cx, |workspace, window, cx| {
12382            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12383            assert!(
12384                !workspace.left_dock().read(cx).is_open(),
12385                "Left dock should be closed"
12386            );
12387            assert!(
12388                !workspace.right_dock().read(cx).is_open(),
12389                "Right dock should be closed"
12390            );
12391            assert!(
12392                !workspace.bottom_dock().read(cx).is_open(),
12393                "Bottom dock should be closed"
12394            );
12395        });
12396
12397        // Toggle all docks back on and verify positions are restored
12398        workspace.update_in(cx, |workspace, window, cx| {
12399            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12400            assert!(
12401                !workspace.left_dock().read(cx).is_open(),
12402                "Left dock should remain closed"
12403            );
12404            assert!(
12405                workspace.right_dock().read(cx).is_open(),
12406                "Right dock should remain open"
12407            );
12408            assert!(
12409                workspace.bottom_dock().read(cx).is_open(),
12410                "Bottom dock should remain open"
12411            );
12412            assert_eq!(
12413                left_panel.read(cx).position,
12414                DockPosition::Bottom,
12415                "Left panel should remain in the bottom dock"
12416            );
12417            assert_eq!(
12418                right_panel.read(cx).position,
12419                DockPosition::Right,
12420                "Right panel should remain in the right dock"
12421            );
12422            assert_eq!(
12423                workspace
12424                    .bottom_dock()
12425                    .read(cx)
12426                    .visible_panel()
12427                    .unwrap()
12428                    .panel_id(),
12429                left_panel.panel_id(),
12430                "Left panel should be the visible panel in the right dock"
12431            );
12432        });
12433    }
12434
12435    #[gpui::test]
12436    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12437        init_test(cx);
12438
12439        let fs = FakeFs::new(cx.executor());
12440
12441        let project = Project::test(fs, None, cx).await;
12442        let (workspace, cx) =
12443            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12444
12445        // Let's arrange the panes like this:
12446        //
12447        // +-----------------------+
12448        // |         top           |
12449        // +------+--------+-------+
12450        // | left | center | right |
12451        // +------+--------+-------+
12452        // |        bottom         |
12453        // +-----------------------+
12454
12455        let top_item = cx.new(|cx| {
12456            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12457        });
12458        let bottom_item = cx.new(|cx| {
12459            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12460        });
12461        let left_item = cx.new(|cx| {
12462            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12463        });
12464        let right_item = cx.new(|cx| {
12465            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12466        });
12467        let center_item = cx.new(|cx| {
12468            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12469        });
12470
12471        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12472            let top_pane_id = workspace.active_pane().entity_id();
12473            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12474            workspace.split_pane(
12475                workspace.active_pane().clone(),
12476                SplitDirection::Down,
12477                window,
12478                cx,
12479            );
12480            top_pane_id
12481        });
12482        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12483            let bottom_pane_id = workspace.active_pane().entity_id();
12484            workspace.add_item_to_active_pane(
12485                Box::new(bottom_item.clone()),
12486                None,
12487                false,
12488                window,
12489                cx,
12490            );
12491            workspace.split_pane(
12492                workspace.active_pane().clone(),
12493                SplitDirection::Up,
12494                window,
12495                cx,
12496            );
12497            bottom_pane_id
12498        });
12499        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12500            let left_pane_id = workspace.active_pane().entity_id();
12501            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12502            workspace.split_pane(
12503                workspace.active_pane().clone(),
12504                SplitDirection::Right,
12505                window,
12506                cx,
12507            );
12508            left_pane_id
12509        });
12510        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12511            let right_pane_id = workspace.active_pane().entity_id();
12512            workspace.add_item_to_active_pane(
12513                Box::new(right_item.clone()),
12514                None,
12515                false,
12516                window,
12517                cx,
12518            );
12519            workspace.split_pane(
12520                workspace.active_pane().clone(),
12521                SplitDirection::Left,
12522                window,
12523                cx,
12524            );
12525            right_pane_id
12526        });
12527        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12528            let center_pane_id = workspace.active_pane().entity_id();
12529            workspace.add_item_to_active_pane(
12530                Box::new(center_item.clone()),
12531                None,
12532                false,
12533                window,
12534                cx,
12535            );
12536            center_pane_id
12537        });
12538        cx.executor().run_until_parked();
12539
12540        workspace.update_in(cx, |workspace, window, cx| {
12541            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12542
12543            // Join into next from center pane into right
12544            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12545        });
12546
12547        workspace.update_in(cx, |workspace, window, cx| {
12548            let active_pane = workspace.active_pane();
12549            assert_eq!(right_pane_id, active_pane.entity_id());
12550            assert_eq!(2, active_pane.read(cx).items_len());
12551            let item_ids_in_pane =
12552                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12553            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12554            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12555
12556            // Join into next from right pane into bottom
12557            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12558        });
12559
12560        workspace.update_in(cx, |workspace, window, cx| {
12561            let active_pane = workspace.active_pane();
12562            assert_eq!(bottom_pane_id, active_pane.entity_id());
12563            assert_eq!(3, active_pane.read(cx).items_len());
12564            let item_ids_in_pane =
12565                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12566            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12567            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12568            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12569
12570            // Join into next from bottom pane into left
12571            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12572        });
12573
12574        workspace.update_in(cx, |workspace, window, cx| {
12575            let active_pane = workspace.active_pane();
12576            assert_eq!(left_pane_id, active_pane.entity_id());
12577            assert_eq!(4, active_pane.read(cx).items_len());
12578            let item_ids_in_pane =
12579                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12580            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12581            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12582            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12583            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12584
12585            // Join into next from left pane into top
12586            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12587        });
12588
12589        workspace.update_in(cx, |workspace, window, cx| {
12590            let active_pane = workspace.active_pane();
12591            assert_eq!(top_pane_id, active_pane.entity_id());
12592            assert_eq!(5, active_pane.read(cx).items_len());
12593            let item_ids_in_pane =
12594                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12595            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12596            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12597            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12598            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12599            assert!(item_ids_in_pane.contains(&top_item.item_id()));
12600
12601            // Single pane left: no-op
12602            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12603        });
12604
12605        workspace.update(cx, |workspace, _cx| {
12606            let active_pane = workspace.active_pane();
12607            assert_eq!(top_pane_id, active_pane.entity_id());
12608        });
12609    }
12610
12611    fn add_an_item_to_active_pane(
12612        cx: &mut VisualTestContext,
12613        workspace: &Entity<Workspace>,
12614        item_id: u64,
12615    ) -> Entity<TestItem> {
12616        let item = cx.new(|cx| {
12617            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12618                item_id,
12619                "item{item_id}.txt",
12620                cx,
12621            )])
12622        });
12623        workspace.update_in(cx, |workspace, window, cx| {
12624            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12625        });
12626        item
12627    }
12628
12629    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12630        workspace.update_in(cx, |workspace, window, cx| {
12631            workspace.split_pane(
12632                workspace.active_pane().clone(),
12633                SplitDirection::Right,
12634                window,
12635                cx,
12636            )
12637        })
12638    }
12639
12640    #[gpui::test]
12641    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12642        init_test(cx);
12643        let fs = FakeFs::new(cx.executor());
12644        let project = Project::test(fs, None, cx).await;
12645        let (workspace, cx) =
12646            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12647
12648        add_an_item_to_active_pane(cx, &workspace, 1);
12649        split_pane(cx, &workspace);
12650        add_an_item_to_active_pane(cx, &workspace, 2);
12651        split_pane(cx, &workspace); // empty pane
12652        split_pane(cx, &workspace);
12653        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12654
12655        cx.executor().run_until_parked();
12656
12657        workspace.update(cx, |workspace, cx| {
12658            let num_panes = workspace.panes().len();
12659            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12660            let active_item = workspace
12661                .active_pane()
12662                .read(cx)
12663                .active_item()
12664                .expect("item is in focus");
12665
12666            assert_eq!(num_panes, 4);
12667            assert_eq!(num_items_in_current_pane, 1);
12668            assert_eq!(active_item.item_id(), last_item.item_id());
12669        });
12670
12671        workspace.update_in(cx, |workspace, window, cx| {
12672            workspace.join_all_panes(window, cx);
12673        });
12674
12675        workspace.update(cx, |workspace, cx| {
12676            let num_panes = workspace.panes().len();
12677            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12678            let active_item = workspace
12679                .active_pane()
12680                .read(cx)
12681                .active_item()
12682                .expect("item is in focus");
12683
12684            assert_eq!(num_panes, 1);
12685            assert_eq!(num_items_in_current_pane, 3);
12686            assert_eq!(active_item.item_id(), last_item.item_id());
12687        });
12688    }
12689
12690    #[gpui::test]
12691    async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12692        init_test(cx);
12693        let fs = FakeFs::new(cx.executor());
12694
12695        let project = Project::test(fs, [], cx).await;
12696        let (multi_workspace, cx) =
12697            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12698        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12699
12700        workspace.update(cx, |workspace, _cx| {
12701            workspace.bounds.size.width = px(800.);
12702        });
12703
12704        workspace.update_in(cx, |workspace, window, cx| {
12705            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12706            workspace.add_panel(panel, window, cx);
12707            workspace.toggle_dock(DockPosition::Right, window, cx);
12708        });
12709
12710        let (panel, resized_width, ratio_basis_width) =
12711            workspace.update_in(cx, |workspace, window, cx| {
12712                let item = cx.new(|cx| {
12713                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12714                });
12715                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12716
12717                let dock = workspace.right_dock().read(cx);
12718                let workspace_width = workspace.bounds.size.width;
12719                let initial_width = workspace
12720                    .dock_size(&dock, window, cx)
12721                    .expect("flexible dock should have an initial width");
12722
12723                assert_eq!(initial_width, workspace_width / 2.);
12724
12725                workspace.resize_right_dock(px(300.), window, cx);
12726
12727                let dock = workspace.right_dock().read(cx);
12728                let resized_width = workspace
12729                    .dock_size(&dock, window, cx)
12730                    .expect("flexible dock should keep its resized width");
12731
12732                assert_eq!(resized_width, px(300.));
12733
12734                let panel = workspace
12735                    .right_dock()
12736                    .read(cx)
12737                    .visible_panel()
12738                    .expect("flexible dock should have a visible panel")
12739                    .panel_id();
12740
12741                (panel, resized_width, workspace_width)
12742            });
12743
12744        workspace.update_in(cx, |workspace, window, cx| {
12745            workspace.toggle_dock(DockPosition::Right, window, cx);
12746            workspace.toggle_dock(DockPosition::Right, window, cx);
12747
12748            let dock = workspace.right_dock().read(cx);
12749            let reopened_width = workspace
12750                .dock_size(&dock, window, cx)
12751                .expect("flexible dock should restore when reopened");
12752
12753            assert_eq!(reopened_width, resized_width);
12754
12755            let right_dock = workspace.right_dock().read(cx);
12756            let flexible_panel = right_dock
12757                .visible_panel()
12758                .expect("flexible dock should still have a visible panel");
12759            assert_eq!(flexible_panel.panel_id(), panel);
12760            assert_eq!(
12761                right_dock
12762                    .stored_panel_size_state(flexible_panel.as_ref())
12763                    .and_then(|size_state| size_state.flex),
12764                Some(
12765                    resized_width.to_f64() as f32
12766                        / (workspace.bounds.size.width - resized_width).to_f64() as f32
12767                )
12768            );
12769        });
12770
12771        workspace.update_in(cx, |workspace, window, cx| {
12772            workspace.split_pane(
12773                workspace.active_pane().clone(),
12774                SplitDirection::Right,
12775                window,
12776                cx,
12777            );
12778
12779            let dock = workspace.right_dock().read(cx);
12780            let split_width = workspace
12781                .dock_size(&dock, window, cx)
12782                .expect("flexible dock should keep its user-resized proportion");
12783
12784            assert_eq!(split_width, px(300.));
12785
12786            workspace.bounds.size.width = px(1600.);
12787
12788            let dock = workspace.right_dock().read(cx);
12789            let resized_window_width = workspace
12790                .dock_size(&dock, window, cx)
12791                .expect("flexible dock should preserve proportional size on window resize");
12792
12793            assert_eq!(
12794                resized_window_width,
12795                workspace.bounds.size.width
12796                    * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12797            );
12798        });
12799    }
12800
12801    #[gpui::test]
12802    async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12803        init_test(cx);
12804        let fs = FakeFs::new(cx.executor());
12805
12806        // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12807        {
12808            let project = Project::test(fs.clone(), [], cx).await;
12809            let (multi_workspace, cx) =
12810                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12811            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12812
12813            workspace.update(cx, |workspace, _cx| {
12814                workspace.set_random_database_id();
12815                workspace.bounds.size.width = px(800.);
12816            });
12817
12818            let panel = workspace.update_in(cx, |workspace, window, cx| {
12819                let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12820                workspace.add_panel(panel.clone(), window, cx);
12821                workspace.toggle_dock(DockPosition::Left, window, cx);
12822                panel
12823            });
12824
12825            workspace.update_in(cx, |workspace, window, cx| {
12826                workspace.resize_left_dock(px(350.), window, cx);
12827            });
12828
12829            cx.run_until_parked();
12830
12831            let persisted = workspace.read_with(cx, |workspace, cx| {
12832                workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12833            });
12834            assert_eq!(
12835                persisted.and_then(|s| s.size),
12836                Some(px(350.)),
12837                "fixed-width panel size should be persisted to KVP"
12838            );
12839
12840            // Remove the panel and re-add a fresh instance with the same key.
12841            // The new instance should have its size state restored from KVP.
12842            workspace.update_in(cx, |workspace, window, cx| {
12843                workspace.remove_panel(&panel, window, cx);
12844            });
12845
12846            workspace.update_in(cx, |workspace, window, cx| {
12847                let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12848                workspace.add_panel(new_panel, window, cx);
12849
12850                let left_dock = workspace.left_dock().read(cx);
12851                let size_state = left_dock
12852                    .panel::<TestPanel>()
12853                    .and_then(|p| left_dock.stored_panel_size_state(&p));
12854                assert_eq!(
12855                    size_state.and_then(|s| s.size),
12856                    Some(px(350.)),
12857                    "re-added fixed-width panel should restore persisted size from KVP"
12858                );
12859            });
12860        }
12861
12862        // Flexible panel: both pixel size and ratio are persisted and restored.
12863        {
12864            let project = Project::test(fs.clone(), [], cx).await;
12865            let (multi_workspace, cx) =
12866                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12867            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12868
12869            workspace.update(cx, |workspace, _cx| {
12870                workspace.set_random_database_id();
12871                workspace.bounds.size.width = px(800.);
12872            });
12873
12874            let panel = workspace.update_in(cx, |workspace, window, cx| {
12875                let item = cx.new(|cx| {
12876                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12877                });
12878                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12879
12880                let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12881                workspace.add_panel(panel.clone(), window, cx);
12882                workspace.toggle_dock(DockPosition::Right, window, cx);
12883                panel
12884            });
12885
12886            workspace.update_in(cx, |workspace, window, cx| {
12887                workspace.resize_right_dock(px(300.), window, cx);
12888            });
12889
12890            cx.run_until_parked();
12891
12892            let persisted = workspace
12893                .read_with(cx, |workspace, cx| {
12894                    workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12895                })
12896                .expect("flexible panel state should be persisted to KVP");
12897            assert_eq!(
12898                persisted.size, None,
12899                "flexible panel should not persist a redundant pixel size"
12900            );
12901            let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12902
12903            // Remove the panel and re-add: both size and ratio should be restored.
12904            workspace.update_in(cx, |workspace, window, cx| {
12905                workspace.remove_panel(&panel, window, cx);
12906            });
12907
12908            workspace.update_in(cx, |workspace, window, cx| {
12909                let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12910                workspace.add_panel(new_panel, window, cx);
12911
12912                let right_dock = workspace.right_dock().read(cx);
12913                let size_state = right_dock
12914                    .panel::<TestPanel>()
12915                    .and_then(|p| right_dock.stored_panel_size_state(&p))
12916                    .expect("re-added flexible panel should have restored size state from KVP");
12917                assert_eq!(
12918                    size_state.size, None,
12919                    "re-added flexible panel should not have a persisted pixel size"
12920                );
12921                assert_eq!(
12922                    size_state.flex,
12923                    Some(original_ratio),
12924                    "re-added flexible panel should restore persisted flex"
12925                );
12926            });
12927        }
12928    }
12929
12930    #[gpui::test]
12931    async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12932        init_test(cx);
12933        let fs = FakeFs::new(cx.executor());
12934
12935        let project = Project::test(fs, [], cx).await;
12936        let (multi_workspace, cx) =
12937            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12938        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12939
12940        workspace.update(cx, |workspace, _cx| {
12941            workspace.bounds.size.width = px(900.);
12942        });
12943
12944        // Step 1: Add a tab to the center pane then open a flexible panel in the left
12945        // dock. With one full-width center pane the default ratio is 0.5, so the panel
12946        // and the center pane each take half the workspace width.
12947        workspace.update_in(cx, |workspace, window, cx| {
12948            let item = cx.new(|cx| {
12949                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12950            });
12951            workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12952
12953            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12954            workspace.add_panel(panel, window, cx);
12955            workspace.toggle_dock(DockPosition::Left, window, cx);
12956
12957            let left_dock = workspace.left_dock().read(cx);
12958            let left_width = workspace
12959                .dock_size(&left_dock, window, cx)
12960                .expect("left dock should have an active panel");
12961
12962            assert_eq!(
12963                left_width,
12964                workspace.bounds.size.width / 2.,
12965                "flexible left panel should split evenly with the center pane"
12966            );
12967        });
12968
12969        // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12970        // change horizontal width fractions, so the flexible panel stays at the same
12971        // width as each half of the split.
12972        workspace.update_in(cx, |workspace, window, cx| {
12973            workspace.split_pane(
12974                workspace.active_pane().clone(),
12975                SplitDirection::Down,
12976                window,
12977                cx,
12978            );
12979
12980            let left_dock = workspace.left_dock().read(cx);
12981            let left_width = workspace
12982                .dock_size(&left_dock, window, cx)
12983                .expect("left dock should still have an active panel after vertical split");
12984
12985            assert_eq!(
12986                left_width,
12987                workspace.bounds.size.width / 2.,
12988                "flexible left panel width should match each vertically-split pane"
12989            );
12990        });
12991
12992        // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12993        // size reduces the available width, so the flexible left panel and the center
12994        // panes all shrink proportionally to accommodate it.
12995        workspace.update_in(cx, |workspace, window, cx| {
12996            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12997            workspace.add_panel(panel, window, cx);
12998            workspace.toggle_dock(DockPosition::Right, window, cx);
12999
13000            let right_dock = workspace.right_dock().read(cx);
13001            let right_width = workspace
13002                .dock_size(&right_dock, window, cx)
13003                .expect("right dock should have an active panel");
13004
13005            let left_dock = workspace.left_dock().read(cx);
13006            let left_width = workspace
13007                .dock_size(&left_dock, window, cx)
13008                .expect("left dock should still have an active panel");
13009
13010            let available_width = workspace.bounds.size.width - right_width;
13011            assert_eq!(
13012                left_width,
13013                available_width / 2.,
13014                "flexible left panel should shrink proportionally as the right dock takes space"
13015            );
13016        });
13017
13018        // Step 4: Toggle the right dock's panel to flexible. Now both docks use
13019        // flex sizing and the workspace width is divided among left-flex, center
13020        // (implicit flex 1.0), and right-flex.
13021        workspace.update_in(cx, |workspace, window, cx| {
13022            let right_dock = workspace.right_dock().clone();
13023            let right_panel = right_dock
13024                .read(cx)
13025                .visible_panel()
13026                .expect("right dock should have a visible panel")
13027                .clone();
13028            workspace.toggle_dock_panel_flexible_size(
13029                &right_dock,
13030                right_panel.as_ref(),
13031                window,
13032                cx,
13033            );
13034
13035            let right_dock = right_dock.read(cx);
13036            let right_panel = right_dock
13037                .visible_panel()
13038                .expect("right dock should still have a visible panel");
13039            assert!(
13040                right_panel.has_flexible_size(window, cx),
13041                "right panel should now be flexible"
13042            );
13043
13044            let right_size_state = right_dock
13045                .stored_panel_size_state(right_panel.as_ref())
13046                .expect("right panel should have a stored size state after toggling");
13047            let right_flex = right_size_state
13048                .flex
13049                .expect("right panel should have a flex value after toggling");
13050
13051            let left_dock = workspace.left_dock().read(cx);
13052            let left_width = workspace
13053                .dock_size(&left_dock, window, cx)
13054                .expect("left dock should still have an active panel");
13055            let right_width = workspace
13056                .dock_size(&right_dock, window, cx)
13057                .expect("right dock should still have an active panel");
13058
13059            let left_flex = workspace
13060                .default_dock_flex(DockPosition::Left)
13061                .expect("left dock should have a default flex");
13062
13063            let total_flex = left_flex + 1.0 + right_flex;
13064            let expected_left = left_flex / total_flex * workspace.bounds.size.width;
13065            let expected_right = right_flex / total_flex * workspace.bounds.size.width;
13066            assert_eq!(
13067                left_width, expected_left,
13068                "flexible left panel should share workspace width via flex ratios"
13069            );
13070            assert_eq!(
13071                right_width, expected_right,
13072                "flexible right panel should share workspace width via flex ratios"
13073            );
13074        });
13075    }
13076
13077    struct TestModal(FocusHandle);
13078
13079    impl TestModal {
13080        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
13081            Self(cx.focus_handle())
13082        }
13083    }
13084
13085    impl EventEmitter<DismissEvent> for TestModal {}
13086
13087    impl Focusable for TestModal {
13088        fn focus_handle(&self, _cx: &App) -> FocusHandle {
13089            self.0.clone()
13090        }
13091    }
13092
13093    impl ModalView for TestModal {}
13094
13095    impl Render for TestModal {
13096        fn render(
13097            &mut self,
13098            _window: &mut Window,
13099            _cx: &mut Context<TestModal>,
13100        ) -> impl IntoElement {
13101            div().track_focus(&self.0)
13102        }
13103    }
13104
13105    #[gpui::test]
13106    async fn test_panels(cx: &mut gpui::TestAppContext) {
13107        init_test(cx);
13108        let fs = FakeFs::new(cx.executor());
13109
13110        let project = Project::test(fs, [], cx).await;
13111        let (multi_workspace, cx) =
13112            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13113        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13114
13115        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
13116            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
13117            workspace.add_panel(panel_1.clone(), window, cx);
13118            workspace.toggle_dock(DockPosition::Left, window, cx);
13119            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
13120            workspace.add_panel(panel_2.clone(), window, cx);
13121            workspace.toggle_dock(DockPosition::Right, window, cx);
13122
13123            let left_dock = workspace.left_dock();
13124            assert_eq!(
13125                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13126                panel_1.panel_id()
13127            );
13128            assert_eq!(
13129                workspace.dock_size(&left_dock.read(cx), window, cx),
13130                Some(px(300.))
13131            );
13132
13133            workspace.resize_left_dock(px(1337.), window, cx);
13134            assert_eq!(
13135                workspace
13136                    .right_dock()
13137                    .read(cx)
13138                    .visible_panel()
13139                    .unwrap()
13140                    .panel_id(),
13141                panel_2.panel_id(),
13142            );
13143
13144            (panel_1, panel_2)
13145        });
13146
13147        // Move panel_1 to the right
13148        panel_1.update_in(cx, |panel_1, window, cx| {
13149            panel_1.set_position(DockPosition::Right, window, cx)
13150        });
13151
13152        workspace.update_in(cx, |workspace, window, cx| {
13153            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
13154            // Since it was the only panel on the left, the left dock should now be closed.
13155            assert!(!workspace.left_dock().read(cx).is_open());
13156            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
13157            let right_dock = workspace.right_dock();
13158            assert_eq!(
13159                right_dock.read(cx).visible_panel().unwrap().panel_id(),
13160                panel_1.panel_id()
13161            );
13162            assert_eq!(
13163                right_dock
13164                    .read(cx)
13165                    .active_panel_size()
13166                    .unwrap()
13167                    .size
13168                    .unwrap(),
13169                px(1337.)
13170            );
13171
13172            // Now we move panel_2 to the left
13173            panel_2.set_position(DockPosition::Left, window, cx);
13174        });
13175
13176        workspace.update(cx, |workspace, cx| {
13177            // Since panel_2 was not visible on the right, we don't open the left dock.
13178            assert!(!workspace.left_dock().read(cx).is_open());
13179            // And the right dock is unaffected in its displaying of panel_1
13180            assert!(workspace.right_dock().read(cx).is_open());
13181            assert_eq!(
13182                workspace
13183                    .right_dock()
13184                    .read(cx)
13185                    .visible_panel()
13186                    .unwrap()
13187                    .panel_id(),
13188                panel_1.panel_id(),
13189            );
13190        });
13191
13192        // Move panel_1 back to the left
13193        panel_1.update_in(cx, |panel_1, window, cx| {
13194            panel_1.set_position(DockPosition::Left, window, cx)
13195        });
13196
13197        workspace.update_in(cx, |workspace, window, cx| {
13198            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
13199            let left_dock = workspace.left_dock();
13200            assert!(left_dock.read(cx).is_open());
13201            assert_eq!(
13202                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13203                panel_1.panel_id()
13204            );
13205            assert_eq!(
13206                workspace.dock_size(&left_dock.read(cx), window, cx),
13207                Some(px(1337.))
13208            );
13209            // And the right dock should be closed as it no longer has any panels.
13210            assert!(!workspace.right_dock().read(cx).is_open());
13211
13212            // Now we move panel_1 to the bottom
13213            panel_1.set_position(DockPosition::Bottom, window, cx);
13214        });
13215
13216        workspace.update_in(cx, |workspace, window, cx| {
13217            // Since panel_1 was visible on the left, we close the left dock.
13218            assert!(!workspace.left_dock().read(cx).is_open());
13219            // The bottom dock is sized based on the panel's default size,
13220            // since the panel orientation changed from vertical to horizontal.
13221            let bottom_dock = workspace.bottom_dock();
13222            assert_eq!(
13223                workspace.dock_size(&bottom_dock.read(cx), window, cx),
13224                Some(px(300.))
13225            );
13226            // Close bottom dock and move panel_1 back to the left.
13227            bottom_dock.update(cx, |bottom_dock, cx| {
13228                bottom_dock.set_open(false, window, cx)
13229            });
13230            panel_1.set_position(DockPosition::Left, window, cx);
13231        });
13232
13233        // Emit activated event on panel 1
13234        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
13235
13236        // Now the left dock is open and panel_1 is active and focused.
13237        workspace.update_in(cx, |workspace, window, cx| {
13238            let left_dock = workspace.left_dock();
13239            assert!(left_dock.read(cx).is_open());
13240            assert_eq!(
13241                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13242                panel_1.panel_id(),
13243            );
13244            assert!(panel_1.focus_handle(cx).is_focused(window));
13245        });
13246
13247        // Emit closed event on panel 2, which is not active
13248        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13249
13250        // Wo don't close the left dock, because panel_2 wasn't the active panel
13251        workspace.update(cx, |workspace, cx| {
13252            let left_dock = workspace.left_dock();
13253            assert!(left_dock.read(cx).is_open());
13254            assert_eq!(
13255                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13256                panel_1.panel_id(),
13257            );
13258        });
13259
13260        // Emitting a ZoomIn event shows the panel as zoomed.
13261        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
13262        workspace.read_with(cx, |workspace, _| {
13263            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13264            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
13265        });
13266
13267        // Move panel to another dock while it is zoomed
13268        panel_1.update_in(cx, |panel, window, cx| {
13269            panel.set_position(DockPosition::Right, window, cx)
13270        });
13271        workspace.read_with(cx, |workspace, _| {
13272            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13273
13274            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13275        });
13276
13277        // This is a helper for getting a:
13278        // - valid focus on an element,
13279        // - that isn't a part of the panes and panels system of the Workspace,
13280        // - and doesn't trigger the 'on_focus_lost' API.
13281        let focus_other_view = {
13282            let workspace = workspace.clone();
13283            move |cx: &mut VisualTestContext| {
13284                workspace.update_in(cx, |workspace, window, cx| {
13285                    if workspace.active_modal::<TestModal>(cx).is_some() {
13286                        workspace.toggle_modal(window, cx, TestModal::new);
13287                        workspace.toggle_modal(window, cx, TestModal::new);
13288                    } else {
13289                        workspace.toggle_modal(window, cx, TestModal::new);
13290                    }
13291                })
13292            }
13293        };
13294
13295        // If focus is transferred to another view that's not a panel or another pane, we still show
13296        // the panel as zoomed.
13297        focus_other_view(cx);
13298        workspace.read_with(cx, |workspace, _| {
13299            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13300            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13301        });
13302
13303        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13304        workspace.update_in(cx, |_workspace, window, cx| {
13305            cx.focus_self(window);
13306        });
13307        workspace.read_with(cx, |workspace, _| {
13308            assert_eq!(workspace.zoomed, None);
13309            assert_eq!(workspace.zoomed_position, None);
13310        });
13311
13312        // If focus is transferred again to another view that's not a panel or a pane, we won't
13313        // show the panel as zoomed because it wasn't zoomed before.
13314        focus_other_view(cx);
13315        workspace.read_with(cx, |workspace, _| {
13316            assert_eq!(workspace.zoomed, None);
13317            assert_eq!(workspace.zoomed_position, None);
13318        });
13319
13320        // When the panel is activated, it is zoomed again.
13321        cx.dispatch_action(ToggleRightDock);
13322        workspace.read_with(cx, |workspace, _| {
13323            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13324            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13325        });
13326
13327        // Emitting a ZoomOut event unzooms the panel.
13328        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13329        workspace.read_with(cx, |workspace, _| {
13330            assert_eq!(workspace.zoomed, None);
13331            assert_eq!(workspace.zoomed_position, None);
13332        });
13333
13334        // Emit closed event on panel 1, which is active
13335        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13336
13337        // Now the left dock is closed, because panel_1 was the active panel
13338        workspace.update(cx, |workspace, cx| {
13339            let right_dock = workspace.right_dock();
13340            assert!(!right_dock.read(cx).is_open());
13341        });
13342    }
13343
13344    #[gpui::test]
13345    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13346        init_test(cx);
13347
13348        let fs = FakeFs::new(cx.background_executor.clone());
13349        let project = Project::test(fs, [], cx).await;
13350        let (workspace, cx) =
13351            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13352        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13353
13354        let dirty_regular_buffer = cx.new(|cx| {
13355            TestItem::new(cx)
13356                .with_dirty(true)
13357                .with_label("1.txt")
13358                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13359        });
13360        let dirty_regular_buffer_2 = cx.new(|cx| {
13361            TestItem::new(cx)
13362                .with_dirty(true)
13363                .with_label("2.txt")
13364                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13365        });
13366        let dirty_multi_buffer_with_both = cx.new(|cx| {
13367            TestItem::new(cx)
13368                .with_dirty(true)
13369                .with_buffer_kind(ItemBufferKind::Multibuffer)
13370                .with_label("Fake Project Search")
13371                .with_project_items(&[
13372                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13373                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13374                ])
13375        });
13376        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13377        workspace.update_in(cx, |workspace, window, cx| {
13378            workspace.add_item(
13379                pane.clone(),
13380                Box::new(dirty_regular_buffer.clone()),
13381                None,
13382                false,
13383                false,
13384                window,
13385                cx,
13386            );
13387            workspace.add_item(
13388                pane.clone(),
13389                Box::new(dirty_regular_buffer_2.clone()),
13390                None,
13391                false,
13392                false,
13393                window,
13394                cx,
13395            );
13396            workspace.add_item(
13397                pane.clone(),
13398                Box::new(dirty_multi_buffer_with_both.clone()),
13399                None,
13400                false,
13401                false,
13402                window,
13403                cx,
13404            );
13405        });
13406
13407        pane.update_in(cx, |pane, window, cx| {
13408            pane.activate_item(2, true, true, window, cx);
13409            assert_eq!(
13410                pane.active_item().unwrap().item_id(),
13411                multi_buffer_with_both_files_id,
13412                "Should select the multi buffer in the pane"
13413            );
13414        });
13415        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13416            pane.close_other_items(
13417                &CloseOtherItems {
13418                    save_intent: Some(SaveIntent::Save),
13419                    close_pinned: true,
13420                },
13421                None,
13422                window,
13423                cx,
13424            )
13425        });
13426        cx.background_executor.run_until_parked();
13427        assert!(!cx.has_pending_prompt());
13428        close_all_but_multi_buffer_task
13429            .await
13430            .expect("Closing all buffers but the multi buffer failed");
13431        pane.update(cx, |pane, cx| {
13432            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13433            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13434            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13435            assert_eq!(pane.items_len(), 1);
13436            assert_eq!(
13437                pane.active_item().unwrap().item_id(),
13438                multi_buffer_with_both_files_id,
13439                "Should have only the multi buffer left in the pane"
13440            );
13441            assert!(
13442                dirty_multi_buffer_with_both.read(cx).is_dirty,
13443                "The multi buffer containing the unsaved buffer should still be dirty"
13444            );
13445        });
13446
13447        dirty_regular_buffer.update(cx, |buffer, cx| {
13448            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13449        });
13450
13451        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13452            pane.close_active_item(
13453                &CloseActiveItem {
13454                    save_intent: Some(SaveIntent::Close),
13455                    close_pinned: false,
13456                },
13457                window,
13458                cx,
13459            )
13460        });
13461        cx.background_executor.run_until_parked();
13462        assert!(
13463            cx.has_pending_prompt(),
13464            "Dirty multi buffer should prompt a save dialog"
13465        );
13466        cx.simulate_prompt_answer("Save");
13467        cx.background_executor.run_until_parked();
13468        close_multi_buffer_task
13469            .await
13470            .expect("Closing the multi buffer failed");
13471        pane.update(cx, |pane, cx| {
13472            assert_eq!(
13473                dirty_multi_buffer_with_both.read(cx).save_count,
13474                1,
13475                "Multi buffer item should get be saved"
13476            );
13477            // Test impl does not save inner items, so we do not assert them
13478            assert_eq!(
13479                pane.items_len(),
13480                0,
13481                "No more items should be left in the pane"
13482            );
13483            assert!(pane.active_item().is_none());
13484        });
13485    }
13486
13487    #[gpui::test]
13488    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13489        cx: &mut TestAppContext,
13490    ) {
13491        init_test(cx);
13492
13493        let fs = FakeFs::new(cx.background_executor.clone());
13494        let project = Project::test(fs, [], cx).await;
13495        let (workspace, cx) =
13496            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13497        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13498
13499        let dirty_regular_buffer = cx.new(|cx| {
13500            TestItem::new(cx)
13501                .with_dirty(true)
13502                .with_label("1.txt")
13503                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13504        });
13505        let dirty_regular_buffer_2 = cx.new(|cx| {
13506            TestItem::new(cx)
13507                .with_dirty(true)
13508                .with_label("2.txt")
13509                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13510        });
13511        let clear_regular_buffer = cx.new(|cx| {
13512            TestItem::new(cx)
13513                .with_label("3.txt")
13514                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13515        });
13516
13517        let dirty_multi_buffer_with_both = cx.new(|cx| {
13518            TestItem::new(cx)
13519                .with_dirty(true)
13520                .with_buffer_kind(ItemBufferKind::Multibuffer)
13521                .with_label("Fake Project Search")
13522                .with_project_items(&[
13523                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13524                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13525                    clear_regular_buffer.read(cx).project_items[0].clone(),
13526                ])
13527        });
13528        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13529        workspace.update_in(cx, |workspace, window, cx| {
13530            workspace.add_item(
13531                pane.clone(),
13532                Box::new(dirty_regular_buffer.clone()),
13533                None,
13534                false,
13535                false,
13536                window,
13537                cx,
13538            );
13539            workspace.add_item(
13540                pane.clone(),
13541                Box::new(dirty_multi_buffer_with_both.clone()),
13542                None,
13543                false,
13544                false,
13545                window,
13546                cx,
13547            );
13548        });
13549
13550        pane.update_in(cx, |pane, window, cx| {
13551            pane.activate_item(1, true, true, window, cx);
13552            assert_eq!(
13553                pane.active_item().unwrap().item_id(),
13554                multi_buffer_with_both_files_id,
13555                "Should select the multi buffer in the pane"
13556            );
13557        });
13558        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13559            pane.close_active_item(
13560                &CloseActiveItem {
13561                    save_intent: None,
13562                    close_pinned: false,
13563                },
13564                window,
13565                cx,
13566            )
13567        });
13568        cx.background_executor.run_until_parked();
13569        assert!(
13570            cx.has_pending_prompt(),
13571            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13572        );
13573    }
13574
13575    /// Tests that when `close_on_file_delete` is enabled, files are automatically
13576    /// closed when they are deleted from disk.
13577    #[gpui::test]
13578    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13579        init_test(cx);
13580
13581        // Enable the close_on_disk_deletion setting
13582        cx.update_global(|store: &mut SettingsStore, cx| {
13583            store.update_user_settings(cx, |settings| {
13584                settings.workspace.close_on_file_delete = Some(true);
13585            });
13586        });
13587
13588        let fs = FakeFs::new(cx.background_executor.clone());
13589        let project = Project::test(fs, [], cx).await;
13590        let (workspace, cx) =
13591            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13592        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13593
13594        // Create a test item that simulates a file
13595        let item = cx.new(|cx| {
13596            TestItem::new(cx)
13597                .with_label("test.txt")
13598                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13599        });
13600
13601        // Add item to workspace
13602        workspace.update_in(cx, |workspace, window, cx| {
13603            workspace.add_item(
13604                pane.clone(),
13605                Box::new(item.clone()),
13606                None,
13607                false,
13608                false,
13609                window,
13610                cx,
13611            );
13612        });
13613
13614        // Verify the item is in the pane
13615        pane.read_with(cx, |pane, _| {
13616            assert_eq!(pane.items().count(), 1);
13617        });
13618
13619        // Simulate file deletion by setting the item's deleted state
13620        item.update(cx, |item, _| {
13621            item.set_has_deleted_file(true);
13622        });
13623
13624        // Emit UpdateTab event to trigger the close behavior
13625        cx.run_until_parked();
13626        item.update(cx, |_, cx| {
13627            cx.emit(ItemEvent::UpdateTab);
13628        });
13629
13630        // Allow the close operation to complete
13631        cx.run_until_parked();
13632
13633        // Verify the item was automatically closed
13634        pane.read_with(cx, |pane, _| {
13635            assert_eq!(
13636                pane.items().count(),
13637                0,
13638                "Item should be automatically closed when file is deleted"
13639            );
13640        });
13641    }
13642
13643    /// Tests that when `close_on_file_delete` is disabled (default), files remain
13644    /// open with a strikethrough when they are deleted from disk.
13645    #[gpui::test]
13646    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13647        init_test(cx);
13648
13649        // Ensure close_on_disk_deletion is disabled (default)
13650        cx.update_global(|store: &mut SettingsStore, cx| {
13651            store.update_user_settings(cx, |settings| {
13652                settings.workspace.close_on_file_delete = Some(false);
13653            });
13654        });
13655
13656        let fs = FakeFs::new(cx.background_executor.clone());
13657        let project = Project::test(fs, [], cx).await;
13658        let (workspace, cx) =
13659            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13660        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13661
13662        // Create a test item that simulates a file
13663        let item = cx.new(|cx| {
13664            TestItem::new(cx)
13665                .with_label("test.txt")
13666                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13667        });
13668
13669        // Add item to workspace
13670        workspace.update_in(cx, |workspace, window, cx| {
13671            workspace.add_item(
13672                pane.clone(),
13673                Box::new(item.clone()),
13674                None,
13675                false,
13676                false,
13677                window,
13678                cx,
13679            );
13680        });
13681
13682        // Verify the item is in the pane
13683        pane.read_with(cx, |pane, _| {
13684            assert_eq!(pane.items().count(), 1);
13685        });
13686
13687        // Simulate file deletion
13688        item.update(cx, |item, _| {
13689            item.set_has_deleted_file(true);
13690        });
13691
13692        // Emit UpdateTab event
13693        cx.run_until_parked();
13694        item.update(cx, |_, cx| {
13695            cx.emit(ItemEvent::UpdateTab);
13696        });
13697
13698        // Allow any potential close operation to complete
13699        cx.run_until_parked();
13700
13701        // Verify the item remains open (with strikethrough)
13702        pane.read_with(cx, |pane, _| {
13703            assert_eq!(
13704                pane.items().count(),
13705                1,
13706                "Item should remain open when close_on_disk_deletion is disabled"
13707            );
13708        });
13709
13710        // Verify the item shows as deleted
13711        item.read_with(cx, |item, _| {
13712            assert!(
13713                item.has_deleted_file,
13714                "Item should be marked as having deleted file"
13715            );
13716        });
13717    }
13718
13719    /// Tests that dirty files are not automatically closed when deleted from disk,
13720    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13721    /// unsaved changes without being prompted.
13722    #[gpui::test]
13723    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13724        init_test(cx);
13725
13726        // Enable the close_on_file_delete setting
13727        cx.update_global(|store: &mut SettingsStore, cx| {
13728            store.update_user_settings(cx, |settings| {
13729                settings.workspace.close_on_file_delete = Some(true);
13730            });
13731        });
13732
13733        let fs = FakeFs::new(cx.background_executor.clone());
13734        let project = Project::test(fs, [], cx).await;
13735        let (workspace, cx) =
13736            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13737        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13738
13739        // Create a dirty test item
13740        let item = cx.new(|cx| {
13741            TestItem::new(cx)
13742                .with_dirty(true)
13743                .with_label("test.txt")
13744                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13745        });
13746
13747        // Add item to workspace
13748        workspace.update_in(cx, |workspace, window, cx| {
13749            workspace.add_item(
13750                pane.clone(),
13751                Box::new(item.clone()),
13752                None,
13753                false,
13754                false,
13755                window,
13756                cx,
13757            );
13758        });
13759
13760        // Simulate file deletion
13761        item.update(cx, |item, _| {
13762            item.set_has_deleted_file(true);
13763        });
13764
13765        // Emit UpdateTab event to trigger the close behavior
13766        cx.run_until_parked();
13767        item.update(cx, |_, cx| {
13768            cx.emit(ItemEvent::UpdateTab);
13769        });
13770
13771        // Allow any potential close operation to complete
13772        cx.run_until_parked();
13773
13774        // Verify the item remains open (dirty files are not auto-closed)
13775        pane.read_with(cx, |pane, _| {
13776            assert_eq!(
13777                pane.items().count(),
13778                1,
13779                "Dirty items should not be automatically closed even when file is deleted"
13780            );
13781        });
13782
13783        // Verify the item is marked as deleted and still dirty
13784        item.read_with(cx, |item, _| {
13785            assert!(
13786                item.has_deleted_file,
13787                "Item should be marked as having deleted file"
13788            );
13789            assert!(item.is_dirty, "Item should still be dirty");
13790        });
13791    }
13792
13793    /// Tests that navigation history is cleaned up when files are auto-closed
13794    /// due to deletion from disk.
13795    #[gpui::test]
13796    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13797        init_test(cx);
13798
13799        // Enable the close_on_file_delete setting
13800        cx.update_global(|store: &mut SettingsStore, cx| {
13801            store.update_user_settings(cx, |settings| {
13802                settings.workspace.close_on_file_delete = Some(true);
13803            });
13804        });
13805
13806        let fs = FakeFs::new(cx.background_executor.clone());
13807        let project = Project::test(fs, [], cx).await;
13808        let (workspace, cx) =
13809            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13810        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13811
13812        // Create test items
13813        let item1 = cx.new(|cx| {
13814            TestItem::new(cx)
13815                .with_label("test1.txt")
13816                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13817        });
13818        let item1_id = item1.item_id();
13819
13820        let item2 = cx.new(|cx| {
13821            TestItem::new(cx)
13822                .with_label("test2.txt")
13823                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13824        });
13825
13826        // Add items to workspace
13827        workspace.update_in(cx, |workspace, window, cx| {
13828            workspace.add_item(
13829                pane.clone(),
13830                Box::new(item1.clone()),
13831                None,
13832                false,
13833                false,
13834                window,
13835                cx,
13836            );
13837            workspace.add_item(
13838                pane.clone(),
13839                Box::new(item2.clone()),
13840                None,
13841                false,
13842                false,
13843                window,
13844                cx,
13845            );
13846        });
13847
13848        // Activate item1 to ensure it gets navigation entries
13849        pane.update_in(cx, |pane, window, cx| {
13850            pane.activate_item(0, true, true, window, cx);
13851        });
13852
13853        // Switch to item2 and back to create navigation history
13854        pane.update_in(cx, |pane, window, cx| {
13855            pane.activate_item(1, true, true, window, cx);
13856        });
13857        cx.run_until_parked();
13858
13859        pane.update_in(cx, |pane, window, cx| {
13860            pane.activate_item(0, true, true, window, cx);
13861        });
13862        cx.run_until_parked();
13863
13864        // Simulate file deletion for item1
13865        item1.update(cx, |item, _| {
13866            item.set_has_deleted_file(true);
13867        });
13868
13869        // Emit UpdateTab event to trigger the close behavior
13870        item1.update(cx, |_, cx| {
13871            cx.emit(ItemEvent::UpdateTab);
13872        });
13873        cx.run_until_parked();
13874
13875        // Verify item1 was closed
13876        pane.read_with(cx, |pane, _| {
13877            assert_eq!(
13878                pane.items().count(),
13879                1,
13880                "Should have 1 item remaining after auto-close"
13881            );
13882        });
13883
13884        // Check navigation history after close
13885        let has_item = pane.read_with(cx, |pane, cx| {
13886            let mut has_item = false;
13887            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13888                if entry.item.id() == item1_id {
13889                    has_item = true;
13890                }
13891            });
13892            has_item
13893        });
13894
13895        assert!(
13896            !has_item,
13897            "Navigation history should not contain closed item entries"
13898        );
13899    }
13900
13901    #[gpui::test]
13902    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13903        cx: &mut TestAppContext,
13904    ) {
13905        init_test(cx);
13906
13907        let fs = FakeFs::new(cx.background_executor.clone());
13908        let project = Project::test(fs, [], cx).await;
13909        let (workspace, cx) =
13910            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13911        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13912
13913        let dirty_regular_buffer = cx.new(|cx| {
13914            TestItem::new(cx)
13915                .with_dirty(true)
13916                .with_label("1.txt")
13917                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13918        });
13919        let dirty_regular_buffer_2 = cx.new(|cx| {
13920            TestItem::new(cx)
13921                .with_dirty(true)
13922                .with_label("2.txt")
13923                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13924        });
13925        let clear_regular_buffer = cx.new(|cx| {
13926            TestItem::new(cx)
13927                .with_label("3.txt")
13928                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13929        });
13930
13931        let dirty_multi_buffer = cx.new(|cx| {
13932            TestItem::new(cx)
13933                .with_dirty(true)
13934                .with_buffer_kind(ItemBufferKind::Multibuffer)
13935                .with_label("Fake Project Search")
13936                .with_project_items(&[
13937                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13938                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13939                    clear_regular_buffer.read(cx).project_items[0].clone(),
13940                ])
13941        });
13942        workspace.update_in(cx, |workspace, window, cx| {
13943            workspace.add_item(
13944                pane.clone(),
13945                Box::new(dirty_regular_buffer.clone()),
13946                None,
13947                false,
13948                false,
13949                window,
13950                cx,
13951            );
13952            workspace.add_item(
13953                pane.clone(),
13954                Box::new(dirty_regular_buffer_2.clone()),
13955                None,
13956                false,
13957                false,
13958                window,
13959                cx,
13960            );
13961            workspace.add_item(
13962                pane.clone(),
13963                Box::new(dirty_multi_buffer.clone()),
13964                None,
13965                false,
13966                false,
13967                window,
13968                cx,
13969            );
13970        });
13971
13972        pane.update_in(cx, |pane, window, cx| {
13973            pane.activate_item(2, true, true, window, cx);
13974            assert_eq!(
13975                pane.active_item().unwrap().item_id(),
13976                dirty_multi_buffer.item_id(),
13977                "Should select the multi buffer in the pane"
13978            );
13979        });
13980        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13981            pane.close_active_item(
13982                &CloseActiveItem {
13983                    save_intent: None,
13984                    close_pinned: false,
13985                },
13986                window,
13987                cx,
13988            )
13989        });
13990        cx.background_executor.run_until_parked();
13991        assert!(
13992            !cx.has_pending_prompt(),
13993            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13994        );
13995        close_multi_buffer_task
13996            .await
13997            .expect("Closing multi buffer failed");
13998        pane.update(cx, |pane, cx| {
13999            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
14000            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
14001            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
14002            assert_eq!(
14003                pane.items()
14004                    .map(|item| item.item_id())
14005                    .sorted()
14006                    .collect::<Vec<_>>(),
14007                vec![
14008                    dirty_regular_buffer.item_id(),
14009                    dirty_regular_buffer_2.item_id(),
14010                ],
14011                "Should have no multi buffer left in the pane"
14012            );
14013            assert!(dirty_regular_buffer.read(cx).is_dirty);
14014            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
14015        });
14016    }
14017
14018    #[gpui::test]
14019    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
14020        init_test(cx);
14021        let fs = FakeFs::new(cx.executor());
14022        let project = Project::test(fs, [], cx).await;
14023        let (multi_workspace, cx) =
14024            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14025        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14026
14027        // Add a new panel to the right dock, opening the dock and setting the
14028        // focus to the new panel.
14029        let panel = workspace.update_in(cx, |workspace, window, cx| {
14030            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14031            workspace.add_panel(panel.clone(), window, cx);
14032
14033            workspace
14034                .right_dock()
14035                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14036
14037            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14038
14039            panel
14040        });
14041
14042        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
14043        // panel to the next valid position which, in this case, is the left
14044        // dock.
14045        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14046        workspace.update(cx, |workspace, cx| {
14047            assert!(workspace.left_dock().read(cx).is_open());
14048            assert_eq!(panel.read(cx).position, DockPosition::Left);
14049        });
14050
14051        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
14052        // panel to the next valid position which, in this case, is the bottom
14053        // dock.
14054        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14055        workspace.update(cx, |workspace, cx| {
14056            assert!(workspace.bottom_dock().read(cx).is_open());
14057            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
14058        });
14059
14060        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
14061        // around moving the panel to its initial position, the right dock.
14062        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14063        workspace.update(cx, |workspace, cx| {
14064            assert!(workspace.right_dock().read(cx).is_open());
14065            assert_eq!(panel.read(cx).position, DockPosition::Right);
14066        });
14067
14068        // Remove focus from the panel, ensuring that, if the panel is not
14069        // focused, the `MoveFocusedPanelToNextPosition` action does not update
14070        // the panel's position, so the panel is still in the right dock.
14071        workspace.update_in(cx, |workspace, window, cx| {
14072            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14073        });
14074
14075        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14076        workspace.update(cx, |workspace, cx| {
14077            assert!(workspace.right_dock().read(cx).is_open());
14078            assert_eq!(panel.read(cx).position, DockPosition::Right);
14079        });
14080    }
14081
14082    #[gpui::test]
14083    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
14084        init_test(cx);
14085
14086        let fs = FakeFs::new(cx.executor());
14087        let project = Project::test(fs, [], cx).await;
14088        let (workspace, cx) =
14089            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14090
14091        let item_1 = cx.new(|cx| {
14092            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14093        });
14094        workspace.update_in(cx, |workspace, window, cx| {
14095            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14096            workspace.move_item_to_pane_in_direction(
14097                &MoveItemToPaneInDirection {
14098                    direction: SplitDirection::Right,
14099                    focus: true,
14100                    clone: false,
14101                },
14102                window,
14103                cx,
14104            );
14105            workspace.move_item_to_pane_at_index(
14106                &MoveItemToPane {
14107                    destination: 3,
14108                    focus: true,
14109                    clone: false,
14110                },
14111                window,
14112                cx,
14113            );
14114
14115            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
14116            assert_eq!(
14117                pane_items_paths(&workspace.active_pane, cx),
14118                vec!["first.txt".to_string()],
14119                "Single item was not moved anywhere"
14120            );
14121        });
14122
14123        let item_2 = cx.new(|cx| {
14124            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
14125        });
14126        workspace.update_in(cx, |workspace, window, cx| {
14127            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
14128            assert_eq!(
14129                pane_items_paths(&workspace.panes[0], cx),
14130                vec!["first.txt".to_string(), "second.txt".to_string()],
14131            );
14132            workspace.move_item_to_pane_in_direction(
14133                &MoveItemToPaneInDirection {
14134                    direction: SplitDirection::Right,
14135                    focus: true,
14136                    clone: false,
14137                },
14138                window,
14139                cx,
14140            );
14141
14142            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
14143            assert_eq!(
14144                pane_items_paths(&workspace.panes[0], cx),
14145                vec!["first.txt".to_string()],
14146                "After moving, one item should be left in the original pane"
14147            );
14148            assert_eq!(
14149                pane_items_paths(&workspace.panes[1], cx),
14150                vec!["second.txt".to_string()],
14151                "New item should have been moved to the new pane"
14152            );
14153        });
14154
14155        let item_3 = cx.new(|cx| {
14156            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
14157        });
14158        workspace.update_in(cx, |workspace, window, cx| {
14159            let original_pane = workspace.panes[0].clone();
14160            workspace.set_active_pane(&original_pane, window, cx);
14161            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
14162            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
14163            assert_eq!(
14164                pane_items_paths(&workspace.active_pane, cx),
14165                vec!["first.txt".to_string(), "third.txt".to_string()],
14166                "New pane should be ready to move one item out"
14167            );
14168
14169            workspace.move_item_to_pane_at_index(
14170                &MoveItemToPane {
14171                    destination: 3,
14172                    focus: true,
14173                    clone: false,
14174                },
14175                window,
14176                cx,
14177            );
14178            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
14179            assert_eq!(
14180                pane_items_paths(&workspace.active_pane, cx),
14181                vec!["first.txt".to_string()],
14182                "After moving, one item should be left in the original pane"
14183            );
14184            assert_eq!(
14185                pane_items_paths(&workspace.panes[1], cx),
14186                vec!["second.txt".to_string()],
14187                "Previously created pane should be unchanged"
14188            );
14189            assert_eq!(
14190                pane_items_paths(&workspace.panes[2], cx),
14191                vec!["third.txt".to_string()],
14192                "New item should have been moved to the new pane"
14193            );
14194        });
14195    }
14196
14197    #[gpui::test]
14198    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
14199        init_test(cx);
14200
14201        let fs = FakeFs::new(cx.executor());
14202        let project = Project::test(fs, [], cx).await;
14203        let (workspace, cx) =
14204            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14205
14206        let item_1 = cx.new(|cx| {
14207            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14208        });
14209        workspace.update_in(cx, |workspace, window, cx| {
14210            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14211            workspace.move_item_to_pane_in_direction(
14212                &MoveItemToPaneInDirection {
14213                    direction: SplitDirection::Right,
14214                    focus: true,
14215                    clone: true,
14216                },
14217                window,
14218                cx,
14219            );
14220        });
14221        cx.run_until_parked();
14222        workspace.update_in(cx, |workspace, window, cx| {
14223            workspace.move_item_to_pane_at_index(
14224                &MoveItemToPane {
14225                    destination: 3,
14226                    focus: true,
14227                    clone: true,
14228                },
14229                window,
14230                cx,
14231            );
14232        });
14233        cx.run_until_parked();
14234
14235        workspace.update(cx, |workspace, cx| {
14236            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
14237            for pane in workspace.panes() {
14238                assert_eq!(
14239                    pane_items_paths(pane, cx),
14240                    vec!["first.txt".to_string()],
14241                    "Single item exists in all panes"
14242                );
14243            }
14244        });
14245
14246        // verify that the active pane has been updated after waiting for the
14247        // pane focus event to fire and resolve
14248        workspace.read_with(cx, |workspace, _app| {
14249            assert_eq!(
14250                workspace.active_pane(),
14251                &workspace.panes[2],
14252                "The third pane should be the active one: {:?}",
14253                workspace.panes
14254            );
14255        })
14256    }
14257
14258    #[gpui::test]
14259    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
14260        init_test(cx);
14261
14262        let fs = FakeFs::new(cx.executor());
14263        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
14264
14265        let project = Project::test(fs, ["root".as_ref()], cx).await;
14266        let (workspace, cx) =
14267            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14268
14269        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14270        // Add item to pane A with project path
14271        let item_a = cx.new(|cx| {
14272            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14273        });
14274        workspace.update_in(cx, |workspace, window, cx| {
14275            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14276        });
14277
14278        // Split to create pane B
14279        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14280            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14281        });
14282
14283        // Add item with SAME project path to pane B, and pin it
14284        let item_b = cx.new(|cx| {
14285            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14286        });
14287        pane_b.update_in(cx, |pane, window, cx| {
14288            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14289            pane.set_pinned_count(1);
14290        });
14291
14292        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14293        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14294
14295        // close_pinned: false should only close the unpinned copy
14296        workspace.update_in(cx, |workspace, window, cx| {
14297            workspace.close_item_in_all_panes(
14298                &CloseItemInAllPanes {
14299                    save_intent: Some(SaveIntent::Close),
14300                    close_pinned: false,
14301                },
14302                window,
14303                cx,
14304            )
14305        });
14306        cx.executor().run_until_parked();
14307
14308        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14309        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14310        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14311        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14312
14313        // Split again, seeing as closing the previous item also closed its
14314        // pane, so only pane remains, which does not allow us to properly test
14315        // that both items close when `close_pinned: true`.
14316        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14317            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14318        });
14319
14320        // Add an item with the same project path to pane C so that
14321        // close_item_in_all_panes can determine what to close across all panes
14322        // (it reads the active item from the active pane, and split_pane
14323        // creates an empty pane).
14324        let item_c = cx.new(|cx| {
14325            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14326        });
14327        pane_c.update_in(cx, |pane, window, cx| {
14328            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14329        });
14330
14331        // close_pinned: true should close the pinned copy too
14332        workspace.update_in(cx, |workspace, window, cx| {
14333            let panes_count = workspace.panes().len();
14334            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14335
14336            workspace.close_item_in_all_panes(
14337                &CloseItemInAllPanes {
14338                    save_intent: Some(SaveIntent::Close),
14339                    close_pinned: true,
14340                },
14341                window,
14342                cx,
14343            )
14344        });
14345        cx.executor().run_until_parked();
14346
14347        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14348        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14349        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14350        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14351    }
14352
14353    mod register_project_item_tests {
14354
14355        use super::*;
14356
14357        // View
14358        struct TestPngItemView {
14359            focus_handle: FocusHandle,
14360        }
14361        // Model
14362        struct TestPngItem {}
14363
14364        impl project::ProjectItem for TestPngItem {
14365            fn try_open(
14366                _project: &Entity<Project>,
14367                path: &ProjectPath,
14368                cx: &mut App,
14369            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14370                if path.path.extension().unwrap() == "png" {
14371                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14372                } else {
14373                    None
14374                }
14375            }
14376
14377            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14378                None
14379            }
14380
14381            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14382                None
14383            }
14384
14385            fn is_dirty(&self) -> bool {
14386                false
14387            }
14388        }
14389
14390        impl Item for TestPngItemView {
14391            type Event = ();
14392            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14393                "".into()
14394            }
14395        }
14396        impl EventEmitter<()> for TestPngItemView {}
14397        impl Focusable for TestPngItemView {
14398            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14399                self.focus_handle.clone()
14400            }
14401        }
14402
14403        impl Render for TestPngItemView {
14404            fn render(
14405                &mut self,
14406                _window: &mut Window,
14407                _cx: &mut Context<Self>,
14408            ) -> impl IntoElement {
14409                Empty
14410            }
14411        }
14412
14413        impl ProjectItem for TestPngItemView {
14414            type Item = TestPngItem;
14415
14416            fn for_project_item(
14417                _project: Entity<Project>,
14418                _pane: Option<&Pane>,
14419                _item: Entity<Self::Item>,
14420                _: &mut Window,
14421                cx: &mut Context<Self>,
14422            ) -> Self
14423            where
14424                Self: Sized,
14425            {
14426                Self {
14427                    focus_handle: cx.focus_handle(),
14428                }
14429            }
14430        }
14431
14432        // View
14433        struct TestIpynbItemView {
14434            focus_handle: FocusHandle,
14435        }
14436        // Model
14437        struct TestIpynbItem {}
14438
14439        impl project::ProjectItem for TestIpynbItem {
14440            fn try_open(
14441                _project: &Entity<Project>,
14442                path: &ProjectPath,
14443                cx: &mut App,
14444            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14445                if path.path.extension().unwrap() == "ipynb" {
14446                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14447                } else {
14448                    None
14449                }
14450            }
14451
14452            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14453                None
14454            }
14455
14456            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14457                None
14458            }
14459
14460            fn is_dirty(&self) -> bool {
14461                false
14462            }
14463        }
14464
14465        impl Item for TestIpynbItemView {
14466            type Event = ();
14467            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14468                "".into()
14469            }
14470        }
14471        impl EventEmitter<()> for TestIpynbItemView {}
14472        impl Focusable for TestIpynbItemView {
14473            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14474                self.focus_handle.clone()
14475            }
14476        }
14477
14478        impl Render for TestIpynbItemView {
14479            fn render(
14480                &mut self,
14481                _window: &mut Window,
14482                _cx: &mut Context<Self>,
14483            ) -> impl IntoElement {
14484                Empty
14485            }
14486        }
14487
14488        impl ProjectItem for TestIpynbItemView {
14489            type Item = TestIpynbItem;
14490
14491            fn for_project_item(
14492                _project: Entity<Project>,
14493                _pane: Option<&Pane>,
14494                _item: Entity<Self::Item>,
14495                _: &mut Window,
14496                cx: &mut Context<Self>,
14497            ) -> Self
14498            where
14499                Self: Sized,
14500            {
14501                Self {
14502                    focus_handle: cx.focus_handle(),
14503                }
14504            }
14505        }
14506
14507        struct TestAlternatePngItemView {
14508            focus_handle: FocusHandle,
14509        }
14510
14511        impl Item for TestAlternatePngItemView {
14512            type Event = ();
14513            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14514                "".into()
14515            }
14516        }
14517
14518        impl EventEmitter<()> for TestAlternatePngItemView {}
14519        impl Focusable for TestAlternatePngItemView {
14520            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14521                self.focus_handle.clone()
14522            }
14523        }
14524
14525        impl Render for TestAlternatePngItemView {
14526            fn render(
14527                &mut self,
14528                _window: &mut Window,
14529                _cx: &mut Context<Self>,
14530            ) -> impl IntoElement {
14531                Empty
14532            }
14533        }
14534
14535        impl ProjectItem for TestAlternatePngItemView {
14536            type Item = TestPngItem;
14537
14538            fn for_project_item(
14539                _project: Entity<Project>,
14540                _pane: Option<&Pane>,
14541                _item: Entity<Self::Item>,
14542                _: &mut Window,
14543                cx: &mut Context<Self>,
14544            ) -> Self
14545            where
14546                Self: Sized,
14547            {
14548                Self {
14549                    focus_handle: cx.focus_handle(),
14550                }
14551            }
14552        }
14553
14554        #[gpui::test]
14555        async fn test_register_project_item(cx: &mut TestAppContext) {
14556            init_test(cx);
14557
14558            cx.update(|cx| {
14559                register_project_item::<TestPngItemView>(cx);
14560                register_project_item::<TestIpynbItemView>(cx);
14561            });
14562
14563            let fs = FakeFs::new(cx.executor());
14564            fs.insert_tree(
14565                "/root1",
14566                json!({
14567                    "one.png": "BINARYDATAHERE",
14568                    "two.ipynb": "{ totally a notebook }",
14569                    "three.txt": "editing text, sure why not?"
14570                }),
14571            )
14572            .await;
14573
14574            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14575            let (workspace, cx) =
14576                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14577
14578            let worktree_id = project.update(cx, |project, cx| {
14579                project.worktrees(cx).next().unwrap().read(cx).id()
14580            });
14581
14582            let handle = workspace
14583                .update_in(cx, |workspace, window, cx| {
14584                    let project_path = (worktree_id, rel_path("one.png"));
14585                    workspace.open_path(project_path, None, true, window, cx)
14586                })
14587                .await
14588                .unwrap();
14589
14590            // Now we can check if the handle we got back errored or not
14591            assert_eq!(
14592                handle.to_any_view().entity_type(),
14593                TypeId::of::<TestPngItemView>()
14594            );
14595
14596            let handle = workspace
14597                .update_in(cx, |workspace, window, cx| {
14598                    let project_path = (worktree_id, rel_path("two.ipynb"));
14599                    workspace.open_path(project_path, None, true, window, cx)
14600                })
14601                .await
14602                .unwrap();
14603
14604            assert_eq!(
14605                handle.to_any_view().entity_type(),
14606                TypeId::of::<TestIpynbItemView>()
14607            );
14608
14609            let handle = workspace
14610                .update_in(cx, |workspace, window, cx| {
14611                    let project_path = (worktree_id, rel_path("three.txt"));
14612                    workspace.open_path(project_path, None, true, window, cx)
14613                })
14614                .await;
14615            assert!(handle.is_err());
14616        }
14617
14618        #[gpui::test]
14619        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14620            init_test(cx);
14621
14622            cx.update(|cx| {
14623                register_project_item::<TestPngItemView>(cx);
14624                register_project_item::<TestAlternatePngItemView>(cx);
14625            });
14626
14627            let fs = FakeFs::new(cx.executor());
14628            fs.insert_tree(
14629                "/root1",
14630                json!({
14631                    "one.png": "BINARYDATAHERE",
14632                    "two.ipynb": "{ totally a notebook }",
14633                    "three.txt": "editing text, sure why not?"
14634                }),
14635            )
14636            .await;
14637            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14638            let (workspace, cx) =
14639                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14640            let worktree_id = project.update(cx, |project, cx| {
14641                project.worktrees(cx).next().unwrap().read(cx).id()
14642            });
14643
14644            let handle = workspace
14645                .update_in(cx, |workspace, window, cx| {
14646                    let project_path = (worktree_id, rel_path("one.png"));
14647                    workspace.open_path(project_path, None, true, window, cx)
14648                })
14649                .await
14650                .unwrap();
14651
14652            // This _must_ be the second item registered
14653            assert_eq!(
14654                handle.to_any_view().entity_type(),
14655                TypeId::of::<TestAlternatePngItemView>()
14656            );
14657
14658            let handle = workspace
14659                .update_in(cx, |workspace, window, cx| {
14660                    let project_path = (worktree_id, rel_path("three.txt"));
14661                    workspace.open_path(project_path, None, true, window, cx)
14662                })
14663                .await;
14664            assert!(handle.is_err());
14665        }
14666    }
14667
14668    #[gpui::test]
14669    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14670        init_test(cx);
14671
14672        let fs = FakeFs::new(cx.executor());
14673        let project = Project::test(fs, [], cx).await;
14674        let (workspace, _cx) =
14675            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14676
14677        // Test with status bar shown (default)
14678        workspace.read_with(cx, |workspace, cx| {
14679            let visible = workspace.status_bar_visible(cx);
14680            assert!(visible, "Status bar should be visible by default");
14681        });
14682
14683        // Test with status bar hidden
14684        cx.update_global(|store: &mut SettingsStore, cx| {
14685            store.update_user_settings(cx, |settings| {
14686                settings.status_bar.get_or_insert_default().show = Some(false);
14687            });
14688        });
14689
14690        workspace.read_with(cx, |workspace, cx| {
14691            let visible = workspace.status_bar_visible(cx);
14692            assert!(!visible, "Status bar should be hidden when show is false");
14693        });
14694
14695        // Test with status bar shown explicitly
14696        cx.update_global(|store: &mut SettingsStore, cx| {
14697            store.update_user_settings(cx, |settings| {
14698                settings.status_bar.get_or_insert_default().show = Some(true);
14699            });
14700        });
14701
14702        workspace.read_with(cx, |workspace, cx| {
14703            let visible = workspace.status_bar_visible(cx);
14704            assert!(visible, "Status bar should be visible when show is true");
14705        });
14706    }
14707
14708    #[gpui::test]
14709    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14710        init_test(cx);
14711
14712        let fs = FakeFs::new(cx.executor());
14713        let project = Project::test(fs, [], cx).await;
14714        let (multi_workspace, cx) =
14715            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14716        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14717        let panel = workspace.update_in(cx, |workspace, window, cx| {
14718            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14719            workspace.add_panel(panel.clone(), window, cx);
14720
14721            workspace
14722                .right_dock()
14723                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14724
14725            panel
14726        });
14727
14728        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14729        let item_a = cx.new(TestItem::new);
14730        let item_b = cx.new(TestItem::new);
14731        let item_a_id = item_a.entity_id();
14732        let item_b_id = item_b.entity_id();
14733
14734        pane.update_in(cx, |pane, window, cx| {
14735            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14736            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14737        });
14738
14739        pane.read_with(cx, |pane, _| {
14740            assert_eq!(pane.items_len(), 2);
14741            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14742        });
14743
14744        workspace.update_in(cx, |workspace, window, cx| {
14745            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14746        });
14747
14748        workspace.update_in(cx, |_, window, cx| {
14749            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14750        });
14751
14752        // Assert that the `pane::CloseActiveItem` action is handled at the
14753        // workspace level when one of the dock panels is focused and, in that
14754        // case, the center pane's active item is closed but the focus is not
14755        // moved.
14756        cx.dispatch_action(pane::CloseActiveItem::default());
14757        cx.run_until_parked();
14758
14759        pane.read_with(cx, |pane, _| {
14760            assert_eq!(pane.items_len(), 1);
14761            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14762        });
14763
14764        workspace.update_in(cx, |workspace, window, cx| {
14765            assert!(workspace.right_dock().read(cx).is_open());
14766            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14767        });
14768    }
14769
14770    #[gpui::test]
14771    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14772        init_test(cx);
14773        let fs = FakeFs::new(cx.executor());
14774
14775        let project_a = Project::test(fs.clone(), [], cx).await;
14776        let project_b = Project::test(fs, [], cx).await;
14777
14778        let multi_workspace_handle =
14779            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14780        cx.run_until_parked();
14781
14782        multi_workspace_handle
14783            .update(cx, |mw, _window, cx| {
14784                mw.open_sidebar(cx);
14785            })
14786            .unwrap();
14787
14788        let workspace_a = multi_workspace_handle
14789            .read_with(cx, |mw, _| mw.workspace().clone())
14790            .unwrap();
14791
14792        let _workspace_b = multi_workspace_handle
14793            .update(cx, |mw, window, cx| {
14794                mw.test_add_workspace(project_b, window, cx)
14795            })
14796            .unwrap();
14797
14798        // Switch to workspace A
14799        multi_workspace_handle
14800            .update(cx, |mw, window, cx| {
14801                let workspace = mw.workspaces().next().unwrap().clone();
14802                mw.activate(workspace, window, cx);
14803            })
14804            .unwrap();
14805
14806        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14807
14808        // Add a panel to workspace A's right dock and open the dock
14809        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14810            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14811            workspace.add_panel(panel.clone(), window, cx);
14812            workspace
14813                .right_dock()
14814                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14815            panel
14816        });
14817
14818        // Focus the panel through the workspace (matching existing test pattern)
14819        workspace_a.update_in(cx, |workspace, window, cx| {
14820            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14821        });
14822
14823        // Zoom the panel
14824        panel.update_in(cx, |panel, window, cx| {
14825            panel.set_zoomed(true, window, cx);
14826        });
14827
14828        // Verify the panel is zoomed and the dock is open
14829        workspace_a.update_in(cx, |workspace, window, cx| {
14830            assert!(
14831                workspace.right_dock().read(cx).is_open(),
14832                "dock should be open before switch"
14833            );
14834            assert!(
14835                panel.is_zoomed(window, cx),
14836                "panel should be zoomed before switch"
14837            );
14838            assert!(
14839                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14840                "panel should be focused before switch"
14841            );
14842        });
14843
14844        // Switch to workspace B
14845        multi_workspace_handle
14846            .update(cx, |mw, window, cx| {
14847                let workspace = mw.workspaces().nth(1).unwrap().clone();
14848                mw.activate(workspace, window, cx);
14849            })
14850            .unwrap();
14851        cx.run_until_parked();
14852
14853        // Switch back to workspace A
14854        multi_workspace_handle
14855            .update(cx, |mw, window, cx| {
14856                let workspace = mw.workspaces().next().unwrap().clone();
14857                mw.activate(workspace, window, cx);
14858            })
14859            .unwrap();
14860        cx.run_until_parked();
14861
14862        // Verify the panel is still zoomed and the dock is still open
14863        workspace_a.update_in(cx, |workspace, window, cx| {
14864            assert!(
14865                workspace.right_dock().read(cx).is_open(),
14866                "dock should still be open after switching back"
14867            );
14868            assert!(
14869                panel.is_zoomed(window, cx),
14870                "panel should still be zoomed after switching back"
14871            );
14872        });
14873    }
14874
14875    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14876        pane.read(cx)
14877            .items()
14878            .flat_map(|item| {
14879                item.project_paths(cx)
14880                    .into_iter()
14881                    .map(|path| path.path.display(PathStyle::local()).into_owned())
14882            })
14883            .collect()
14884    }
14885
14886    pub fn init_test(cx: &mut TestAppContext) {
14887        cx.update(|cx| {
14888            let settings_store = SettingsStore::test(cx);
14889            cx.set_global(settings_store);
14890            cx.set_global(db::AppDatabase::test_new());
14891            theme_settings::init(theme::LoadThemes::JustBase, cx);
14892        });
14893    }
14894
14895    #[gpui::test]
14896    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14897        use settings::{ThemeName, ThemeSelection};
14898        use theme::SystemAppearance;
14899        use zed_actions::theme::ToggleMode;
14900
14901        init_test(cx);
14902
14903        let fs = FakeFs::new(cx.executor());
14904        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14905
14906        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14907            .await;
14908
14909        // Build a test project and workspace view so the test can invoke
14910        // the workspace action handler the same way the UI would.
14911        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14912        let (workspace, cx) =
14913            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14914
14915        // Seed the settings file with a plain static light theme so the
14916        // first toggle always starts from a known persisted state.
14917        workspace.update_in(cx, |_workspace, _window, cx| {
14918            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14919            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14920                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14921            });
14922        });
14923        cx.executor().advance_clock(Duration::from_millis(200));
14924        cx.run_until_parked();
14925
14926        // Confirm the initial persisted settings contain the static theme
14927        // we just wrote before any toggling happens.
14928        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14929        assert!(settings_text.contains(r#""theme": "One Light""#));
14930
14931        // Toggle once. This should migrate the persisted theme settings
14932        // into light/dark slots and enable system mode.
14933        workspace.update_in(cx, |workspace, window, cx| {
14934            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14935        });
14936        cx.executor().advance_clock(Duration::from_millis(200));
14937        cx.run_until_parked();
14938
14939        // 1. Static -> Dynamic
14940        // this assertion checks theme changed from static to dynamic.
14941        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14942        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14943        assert_eq!(
14944            parsed["theme"],
14945            serde_json::json!({
14946                "mode": "system",
14947                "light": "One Light",
14948                "dark": "One Dark"
14949            })
14950        );
14951
14952        // 2. Toggle again, suppose it will change the mode to light
14953        workspace.update_in(cx, |workspace, window, cx| {
14954            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14955        });
14956        cx.executor().advance_clock(Duration::from_millis(200));
14957        cx.run_until_parked();
14958
14959        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14960        assert!(settings_text.contains(r#""mode": "light""#));
14961    }
14962
14963    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14964        let item = TestProjectItem::new(id, path, cx);
14965        item.update(cx, |item, _| {
14966            item.is_dirty = true;
14967        });
14968        item
14969    }
14970
14971    #[gpui::test]
14972    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14973        cx: &mut gpui::TestAppContext,
14974    ) {
14975        init_test(cx);
14976        let fs = FakeFs::new(cx.executor());
14977
14978        let project = Project::test(fs, [], cx).await;
14979        let (workspace, cx) =
14980            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14981
14982        let panel = workspace.update_in(cx, |workspace, window, cx| {
14983            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14984            workspace.add_panel(panel.clone(), window, cx);
14985            workspace
14986                .right_dock()
14987                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14988            panel
14989        });
14990
14991        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14992        pane.update_in(cx, |pane, window, cx| {
14993            let item = cx.new(TestItem::new);
14994            pane.add_item(Box::new(item), true, true, None, window, cx);
14995        });
14996
14997        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14998        // mirrors the real-world flow and avoids side effects from directly
14999        // focusing the panel while the center pane is active.
15000        workspace.update_in(cx, |workspace, window, cx| {
15001            workspace.toggle_panel_focus::<TestPanel>(window, cx);
15002        });
15003
15004        panel.update_in(cx, |panel, window, cx| {
15005            panel.set_zoomed(true, window, cx);
15006        });
15007
15008        workspace.update_in(cx, |workspace, window, cx| {
15009            assert!(workspace.right_dock().read(cx).is_open());
15010            assert!(panel.is_zoomed(window, cx));
15011            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
15012        });
15013
15014        // Simulate a spurious pane::Event::Focus on the center pane while the
15015        // panel still has focus. This mirrors what happens during macOS window
15016        // activation: the center pane fires a focus event even though actual
15017        // focus remains on the dock panel.
15018        pane.update_in(cx, |_, _, cx| {
15019            cx.emit(pane::Event::Focus);
15020        });
15021
15022        // The dock must remain open because the panel had focus at the time the
15023        // event was processed. Before the fix, dock_to_preserve was None for
15024        // panels that don't implement pane(), causing the dock to close.
15025        workspace.update_in(cx, |workspace, window, cx| {
15026            assert!(
15027                workspace.right_dock().read(cx).is_open(),
15028                "Dock should stay open when its zoomed panel (without pane()) still has focus"
15029            );
15030            assert!(panel.is_zoomed(window, cx));
15031        });
15032    }
15033
15034    #[gpui::test]
15035    async fn test_panels_stay_open_after_position_change_and_settings_update(
15036        cx: &mut gpui::TestAppContext,
15037    ) {
15038        init_test(cx);
15039        let fs = FakeFs::new(cx.executor());
15040        let project = Project::test(fs, [], cx).await;
15041        let (workspace, cx) =
15042            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
15043
15044        // Add two panels to the left dock and open it.
15045        let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
15046            let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
15047            let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
15048            workspace.add_panel(panel_a.clone(), window, cx);
15049            workspace.add_panel(panel_b.clone(), window, cx);
15050            workspace.left_dock().update(cx, |dock, cx| {
15051                dock.set_open(true, window, cx);
15052                dock.activate_panel(0, window, cx);
15053            });
15054            (panel_a, panel_b)
15055        });
15056
15057        workspace.update_in(cx, |workspace, _, cx| {
15058            assert!(workspace.left_dock().read(cx).is_open());
15059        });
15060
15061        // Simulate a feature flag changing default dock positions: both panels
15062        // move from Left to Right.
15063        workspace.update_in(cx, |_workspace, _window, cx| {
15064            panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
15065            panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
15066            cx.update_global::<SettingsStore, _>(|_, _| {});
15067        });
15068
15069        // Both panels should now be in the right dock.
15070        workspace.update_in(cx, |workspace, _, cx| {
15071            let right_dock = workspace.right_dock().read(cx);
15072            assert_eq!(right_dock.panels_len(), 2);
15073        });
15074
15075        // Open the right dock and activate panel_b (simulating the user
15076        // opening the panel after it moved).
15077        workspace.update_in(cx, |workspace, window, cx| {
15078            workspace.right_dock().update(cx, |dock, cx| {
15079                dock.set_open(true, window, cx);
15080                dock.activate_panel(1, window, cx);
15081            });
15082        });
15083
15084        // Now trigger another SettingsStore change
15085        workspace.update_in(cx, |_workspace, _window, cx| {
15086            cx.update_global::<SettingsStore, _>(|_, _| {});
15087        });
15088
15089        workspace.update_in(cx, |workspace, _, cx| {
15090            assert!(
15091                workspace.right_dock().read(cx).is_open(),
15092                "Right dock should still be open after a settings change"
15093            );
15094            assert_eq!(
15095                workspace.right_dock().read(cx).panels_len(),
15096                2,
15097                "Both panels should still be in the right dock"
15098            );
15099        });
15100    }
15101}