workspace.rs

    1pub mod active_file_name;
    2pub mod dock;
    3pub mod history_manager;
    4pub mod invalid_item_view;
    5pub mod item;
    6mod modal_layer;
    7mod multi_workspace;
    8#[cfg(test)]
    9mod multi_workspace_tests;
   10pub mod notifications;
   11pub mod pane;
   12pub mod pane_group;
   13pub mod path_list {
   14    pub use util::path_list::{PathList, SerializedPathList};
   15}
   16mod persistence;
   17pub mod searchable;
   18mod security_modal;
   19pub mod shared_screen;
   20use db::smol::future::yield_now;
   21pub use shared_screen::SharedScreen;
   22mod status_bar;
   23pub mod tasks;
   24mod theme_preview;
   25mod toast_layer;
   26mod toolbar;
   27pub mod welcome;
   28mod workspace_settings;
   29
   30pub use crate::notifications::NotificationFrame;
   31pub use dock::Panel;
   32pub use multi_workspace::{
   33    CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
   34    MultiWorkspaceEvent, NextWorkspace, PreviousWorkspace, Sidebar, SidebarEvent, SidebarHandle,
   35    SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar, sidebar_side_context_menu,
   36};
   37pub use path_list::{PathList, SerializedPathList};
   38pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   39
   40use anyhow::{Context as _, Result, anyhow};
   41use client::{
   42    ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
   43    proto::{self, ErrorCode, PanelId, PeerId},
   44};
   45use collections::{HashMap, HashSet, hash_map};
   46use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   47use fs::Fs;
   48use futures::{
   49    Future, FutureExt, StreamExt,
   50    channel::{
   51        mpsc::{self, UnboundedReceiver, UnboundedSender},
   52        oneshot,
   53    },
   54    future::{Shared, try_join_all},
   55};
   56use gpui::{
   57    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
   58    Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   59    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   60    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   61    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   62    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   63};
   64pub use history_manager::*;
   65pub use item::{
   66    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   67    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   68};
   69use itertools::Itertools;
   70use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   71pub use modal_layer::*;
   72use node_runtime::NodeRuntime;
   73use notifications::{
   74    DetachAndPromptErr, Notifications, dismiss_app_notification,
   75    simple_message_notification::MessageNotification,
   76};
   77pub use pane::*;
   78pub use pane_group::{
   79    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   80    SplitDirection,
   81};
   82use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
   83pub use persistence::{
   84    WorkspaceDb, delete_unloaded_items,
   85    model::{
   86        DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
   87        SessionWorkspace,
   88    },
   89    read_serialized_multi_workspaces, resolve_worktree_workspaces,
   90};
   91use postage::stream::Stream;
   92use project::{
   93    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
   94    WorktreeSettings,
   95    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   96    project_settings::ProjectSettings,
   97    toolchain_store::ToolchainStoreEvent,
   98    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
   99};
  100use remote::{
  101    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
  102    remote_client::ConnectionIdentifier,
  103};
  104use schemars::JsonSchema;
  105use serde::Deserialize;
  106use session::AppSession;
  107use settings::{
  108    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  109};
  110
  111use sqlez::{
  112    bindable::{Bind, Column, StaticColumnCount},
  113    statement::Statement,
  114};
  115use status_bar::StatusBar;
  116pub use status_bar::StatusItemView;
  117use std::{
  118    any::TypeId,
  119    borrow::Cow,
  120    cell::RefCell,
  121    cmp,
  122    collections::VecDeque,
  123    env,
  124    hash::Hash,
  125    path::{Path, PathBuf},
  126    process::ExitStatus,
  127    rc::Rc,
  128    sync::{
  129        Arc, LazyLock,
  130        atomic::{AtomicBool, AtomicUsize},
  131    },
  132    time::Duration,
  133};
  134use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  135use theme::{ActiveTheme, SystemAppearance};
  136use theme_settings::ThemeSettings;
  137pub use toolbar::{
  138    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  139};
  140pub use ui;
  141use ui::{Window, prelude::*};
  142use util::{
  143    ResultExt, TryFutureExt,
  144    paths::{PathStyle, SanitizedPath},
  145    rel_path::RelPath,
  146    serde::default_true,
  147};
  148use uuid::Uuid;
  149pub use workspace_settings::{
  150    AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
  151    WorkspaceSettings,
  152};
  153use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
  154
  155use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::NotificationId};
  156use crate::{
  157    persistence::{
  158        SerializedAxis,
  159        model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
  160    },
  161    security_modal::SecurityModal,
  162};
  163
  164pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  165
  166static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  167    env::var("ZED_WINDOW_SIZE")
  168        .ok()
  169        .as_deref()
  170        .and_then(parse_pixel_size_env_var)
  171});
  172
  173static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  174    env::var("ZED_WINDOW_POSITION")
  175        .ok()
  176        .as_deref()
  177        .and_then(parse_pixel_position_env_var)
  178});
  179
  180pub trait TerminalProvider {
  181    fn spawn(
  182        &self,
  183        task: SpawnInTerminal,
  184        window: &mut Window,
  185        cx: &mut App,
  186    ) -> Task<Option<Result<ExitStatus>>>;
  187}
  188
  189pub trait DebuggerProvider {
  190    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  191    fn start_session(
  192        &self,
  193        definition: DebugScenario,
  194        task_context: SharedTaskContext,
  195        active_buffer: Option<Entity<Buffer>>,
  196        worktree_id: Option<WorktreeId>,
  197        window: &mut Window,
  198        cx: &mut App,
  199    );
  200
  201    fn spawn_task_or_modal(
  202        &self,
  203        workspace: &mut Workspace,
  204        action: &Spawn,
  205        window: &mut Window,
  206        cx: &mut Context<Workspace>,
  207    );
  208
  209    fn task_scheduled(&self, cx: &mut App);
  210    fn debug_scenario_scheduled(&self, cx: &mut App);
  211    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  212
  213    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  214}
  215
  216/// Opens a file or directory.
  217#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  218#[action(namespace = workspace)]
  219pub struct Open {
  220    /// When true, opens in a new window. When false, adds to the current
  221    /// window as a new workspace (multi-workspace).
  222    #[serde(default = "Open::default_create_new_window")]
  223    pub create_new_window: bool,
  224}
  225
  226impl Open {
  227    pub const DEFAULT: Self = Self {
  228        create_new_window: true,
  229    };
  230
  231    /// Used by `#[serde(default)]` on the `create_new_window` field so that
  232    /// the serde default and `Open::DEFAULT` stay in sync.
  233    fn default_create_new_window() -> bool {
  234        Self::DEFAULT.create_new_window
  235    }
  236}
  237
  238impl Default for Open {
  239    fn default() -> Self {
  240        Self::DEFAULT
  241    }
  242}
  243
  244actions!(
  245    workspace,
  246    [
  247        /// Activates the next pane in the workspace.
  248        ActivateNextPane,
  249        /// Activates the previous pane in the workspace.
  250        ActivatePreviousPane,
  251        /// Activates the last pane in the workspace.
  252        ActivateLastPane,
  253        /// Switches to the next window.
  254        ActivateNextWindow,
  255        /// Switches to the previous window.
  256        ActivatePreviousWindow,
  257        /// Adds a folder to the current project.
  258        AddFolderToProject,
  259        /// Clears all notifications.
  260        ClearAllNotifications,
  261        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  262        ClearNavigationHistory,
  263        /// Closes the active dock.
  264        CloseActiveDock,
  265        /// Closes all docks.
  266        CloseAllDocks,
  267        /// Toggles all docks.
  268        ToggleAllDocks,
  269        /// Closes the current window.
  270        CloseWindow,
  271        /// Closes the current project.
  272        CloseProject,
  273        /// Opens the feedback dialog.
  274        Feedback,
  275        /// Follows the next collaborator in the session.
  276        FollowNextCollaborator,
  277        /// Moves the focused panel to the next position.
  278        MoveFocusedPanelToNextPosition,
  279        /// Creates a new file.
  280        NewFile,
  281        /// Creates a new file in a vertical split.
  282        NewFileSplitVertical,
  283        /// Creates a new file in a horizontal split.
  284        NewFileSplitHorizontal,
  285        /// Opens a new search.
  286        NewSearch,
  287        /// Opens a new window.
  288        NewWindow,
  289        /// Opens multiple files.
  290        OpenFiles,
  291        /// Opens the current location in terminal.
  292        OpenInTerminal,
  293        /// Opens the component preview.
  294        OpenComponentPreview,
  295        /// Reloads the active item.
  296        ReloadActiveItem,
  297        /// Resets the active dock to its default size.
  298        ResetActiveDockSize,
  299        /// Resets all open docks to their default sizes.
  300        ResetOpenDocksSize,
  301        /// Reloads the application
  302        Reload,
  303        /// Saves the current file with a new name.
  304        SaveAs,
  305        /// Saves without formatting.
  306        SaveWithoutFormat,
  307        /// Shuts down all debug adapters.
  308        ShutdownDebugAdapters,
  309        /// Suppresses the current notification.
  310        SuppressNotification,
  311        /// Toggles the bottom dock.
  312        ToggleBottomDock,
  313        /// Toggles centered layout mode.
  314        ToggleCenteredLayout,
  315        /// Toggles edit prediction feature globally for all files.
  316        ToggleEditPrediction,
  317        /// Toggles the left dock.
  318        ToggleLeftDock,
  319        /// Toggles the right dock.
  320        ToggleRightDock,
  321        /// Toggles zoom on the active pane.
  322        ToggleZoom,
  323        /// Toggles read-only mode for the active item (if supported by that item).
  324        ToggleReadOnlyFile,
  325        /// Zooms in on the active pane.
  326        ZoomIn,
  327        /// Zooms out of the active pane.
  328        ZoomOut,
  329        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  330        /// If the modal is shown already, closes it without trusting any worktree.
  331        ToggleWorktreeSecurity,
  332        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  333        /// Requires restart to take effect on already opened projects.
  334        ClearTrustedWorktrees,
  335        /// Stops following a collaborator.
  336        Unfollow,
  337        /// Restores the banner.
  338        RestoreBanner,
  339        /// Toggles expansion of the selected item.
  340        ToggleExpandItem,
  341    ]
  342);
  343
  344/// Activates a specific pane by its index.
  345#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  346#[action(namespace = workspace)]
  347pub struct ActivatePane(pub usize);
  348
  349/// Moves an item to a specific pane by index.
  350#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  351#[action(namespace = workspace)]
  352#[serde(deny_unknown_fields)]
  353pub struct MoveItemToPane {
  354    #[serde(default = "default_1")]
  355    pub destination: usize,
  356    #[serde(default = "default_true")]
  357    pub focus: bool,
  358    #[serde(default)]
  359    pub clone: bool,
  360}
  361
  362fn default_1() -> usize {
  363    1
  364}
  365
  366/// Moves an item to a pane in the specified direction.
  367#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  368#[action(namespace = workspace)]
  369#[serde(deny_unknown_fields)]
  370pub struct MoveItemToPaneInDirection {
  371    #[serde(default = "default_right")]
  372    pub direction: SplitDirection,
  373    #[serde(default = "default_true")]
  374    pub focus: bool,
  375    #[serde(default)]
  376    pub clone: bool,
  377}
  378
  379/// Creates a new file in a split of the desired direction.
  380#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  381#[action(namespace = workspace)]
  382#[serde(deny_unknown_fields)]
  383pub struct NewFileSplit(pub SplitDirection);
  384
  385fn default_right() -> SplitDirection {
  386    SplitDirection::Right
  387}
  388
  389/// Saves all open files in the workspace.
  390#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  391#[action(namespace = workspace)]
  392#[serde(deny_unknown_fields)]
  393pub struct SaveAll {
  394    #[serde(default)]
  395    pub save_intent: Option<SaveIntent>,
  396}
  397
  398/// Saves the current file with the specified options.
  399#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  400#[action(namespace = workspace)]
  401#[serde(deny_unknown_fields)]
  402pub struct Save {
  403    #[serde(default)]
  404    pub save_intent: Option<SaveIntent>,
  405}
  406
  407/// Moves Focus to the central panes in the workspace.
  408#[derive(Clone, Debug, PartialEq, Eq, Action)]
  409#[action(namespace = workspace)]
  410pub struct FocusCenterPane;
  411
  412///  Closes all items and panes in the workspace.
  413#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  414#[action(namespace = workspace)]
  415#[serde(deny_unknown_fields)]
  416pub struct CloseAllItemsAndPanes {
  417    #[serde(default)]
  418    pub save_intent: Option<SaveIntent>,
  419}
  420
  421/// Closes all inactive tabs and panes in the workspace.
  422#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  423#[action(namespace = workspace)]
  424#[serde(deny_unknown_fields)]
  425pub struct CloseInactiveTabsAndPanes {
  426    #[serde(default)]
  427    pub save_intent: Option<SaveIntent>,
  428}
  429
  430/// Closes the active item across all panes.
  431#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  432#[action(namespace = workspace)]
  433#[serde(deny_unknown_fields)]
  434pub struct CloseItemInAllPanes {
  435    #[serde(default)]
  436    pub save_intent: Option<SaveIntent>,
  437    #[serde(default)]
  438    pub close_pinned: bool,
  439}
  440
  441/// Sends a sequence of keystrokes to the active element.
  442#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  443#[action(namespace = workspace)]
  444pub struct SendKeystrokes(pub String);
  445
  446actions!(
  447    project_symbols,
  448    [
  449        /// Toggles the project symbols search.
  450        #[action(name = "Toggle")]
  451        ToggleProjectSymbols
  452    ]
  453);
  454
  455/// Toggles the file finder interface.
  456#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  457#[action(namespace = file_finder, name = "Toggle")]
  458#[serde(deny_unknown_fields)]
  459pub struct ToggleFileFinder {
  460    #[serde(default)]
  461    pub separate_history: bool,
  462}
  463
  464/// Opens a new terminal in the center.
  465#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  466#[action(namespace = workspace)]
  467#[serde(deny_unknown_fields)]
  468pub struct NewCenterTerminal {
  469    /// If true, creates a local terminal even in remote projects.
  470    #[serde(default)]
  471    pub local: bool,
  472}
  473
  474/// Opens a new terminal.
  475#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  476#[action(namespace = workspace)]
  477#[serde(deny_unknown_fields)]
  478pub struct NewTerminal {
  479    /// If true, creates a local terminal even in remote projects.
  480    #[serde(default)]
  481    pub local: bool,
  482}
  483
  484/// Increases size of a currently focused dock by a given amount of pixels.
  485#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  486#[action(namespace = workspace)]
  487#[serde(deny_unknown_fields)]
  488pub struct IncreaseActiveDockSize {
  489    /// For 0px parameter, uses UI font size value.
  490    #[serde(default)]
  491    pub px: u32,
  492}
  493
  494/// Decreases size of a currently focused dock by a given amount of pixels.
  495#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  496#[action(namespace = workspace)]
  497#[serde(deny_unknown_fields)]
  498pub struct DecreaseActiveDockSize {
  499    /// For 0px parameter, uses UI font size value.
  500    #[serde(default)]
  501    pub px: u32,
  502}
  503
  504/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  505#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  506#[action(namespace = workspace)]
  507#[serde(deny_unknown_fields)]
  508pub struct IncreaseOpenDocksSize {
  509    /// For 0px parameter, uses UI font size value.
  510    #[serde(default)]
  511    pub px: u32,
  512}
  513
  514/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  515#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  516#[action(namespace = workspace)]
  517#[serde(deny_unknown_fields)]
  518pub struct DecreaseOpenDocksSize {
  519    /// For 0px parameter, uses UI font size value.
  520    #[serde(default)]
  521    pub px: u32,
  522}
  523
  524actions!(
  525    workspace,
  526    [
  527        /// Activates the pane to the left.
  528        ActivatePaneLeft,
  529        /// Activates the pane to the right.
  530        ActivatePaneRight,
  531        /// Activates the pane above.
  532        ActivatePaneUp,
  533        /// Activates the pane below.
  534        ActivatePaneDown,
  535        /// Swaps the current pane with the one to the left.
  536        SwapPaneLeft,
  537        /// Swaps the current pane with the one to the right.
  538        SwapPaneRight,
  539        /// Swaps the current pane with the one above.
  540        SwapPaneUp,
  541        /// Swaps the current pane with the one below.
  542        SwapPaneDown,
  543        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  544        SwapPaneAdjacent,
  545        /// Move the current pane to be at the far left.
  546        MovePaneLeft,
  547        /// Move the current pane to be at the far right.
  548        MovePaneRight,
  549        /// Move the current pane to be at the very top.
  550        MovePaneUp,
  551        /// Move the current pane to be at the very bottom.
  552        MovePaneDown,
  553    ]
  554);
  555
  556#[derive(PartialEq, Eq, Debug)]
  557pub enum CloseIntent {
  558    /// Quit the program entirely.
  559    Quit,
  560    /// Close a window.
  561    CloseWindow,
  562    /// Replace the workspace in an existing window.
  563    ReplaceWindow,
  564}
  565
  566#[derive(Clone)]
  567pub struct Toast {
  568    id: NotificationId,
  569    msg: Cow<'static, str>,
  570    autohide: bool,
  571    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  572}
  573
  574impl Toast {
  575    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  576        Toast {
  577            id,
  578            msg: msg.into(),
  579            on_click: None,
  580            autohide: false,
  581        }
  582    }
  583
  584    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  585    where
  586        M: Into<Cow<'static, str>>,
  587        F: Fn(&mut Window, &mut App) + 'static,
  588    {
  589        self.on_click = Some((message.into(), Arc::new(on_click)));
  590        self
  591    }
  592
  593    pub fn autohide(mut self) -> Self {
  594        self.autohide = true;
  595        self
  596    }
  597}
  598
  599impl PartialEq for Toast {
  600    fn eq(&self, other: &Self) -> bool {
  601        self.id == other.id
  602            && self.msg == other.msg
  603            && self.on_click.is_some() == other.on_click.is_some()
  604    }
  605}
  606
  607/// Opens a new terminal with the specified working directory.
  608#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  609#[action(namespace = workspace)]
  610#[serde(deny_unknown_fields)]
  611pub struct OpenTerminal {
  612    pub working_directory: PathBuf,
  613    /// If true, creates a local terminal even in remote projects.
  614    #[serde(default)]
  615    pub local: bool,
  616}
  617
  618#[derive(
  619    Clone,
  620    Copy,
  621    Debug,
  622    Default,
  623    Hash,
  624    PartialEq,
  625    Eq,
  626    PartialOrd,
  627    Ord,
  628    serde::Serialize,
  629    serde::Deserialize,
  630)]
  631pub struct WorkspaceId(i64);
  632
  633impl WorkspaceId {
  634    pub fn from_i64(value: i64) -> Self {
  635        Self(value)
  636    }
  637}
  638
  639impl StaticColumnCount for WorkspaceId {}
  640impl Bind for WorkspaceId {
  641    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  642        self.0.bind(statement, start_index)
  643    }
  644}
  645impl Column for WorkspaceId {
  646    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  647        i64::column(statement, start_index)
  648            .map(|(i, next_index)| (Self(i), next_index))
  649            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  650    }
  651}
  652impl From<WorkspaceId> for i64 {
  653    fn from(val: WorkspaceId) -> Self {
  654        val.0
  655    }
  656}
  657
  658fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
  659    if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
  660        workspace_window
  661            .update(cx, |multi_workspace, window, cx| {
  662                let workspace = multi_workspace.workspace().clone();
  663                workspace.update(cx, |workspace, cx| {
  664                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  665                });
  666            })
  667            .ok();
  668    } else {
  669        let task = Workspace::new_local(
  670            Vec::new(),
  671            app_state.clone(),
  672            None,
  673            None,
  674            None,
  675            OpenMode::Replace,
  676            cx,
  677        );
  678        cx.spawn(async move |cx| {
  679            let OpenResult { window, .. } = task.await?;
  680            window.update(cx, |multi_workspace, window, cx| {
  681                window.activate_window();
  682                let workspace = multi_workspace.workspace().clone();
  683                workspace.update(cx, |workspace, cx| {
  684                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  685                });
  686            })?;
  687            anyhow::Ok(())
  688        })
  689        .detach_and_log_err(cx);
  690    }
  691}
  692
  693pub fn prompt_for_open_path_and_open(
  694    workspace: &mut Workspace,
  695    app_state: Arc<AppState>,
  696    options: PathPromptOptions,
  697    create_new_window: bool,
  698    window: &mut Window,
  699    cx: &mut Context<Workspace>,
  700) {
  701    let paths = workspace.prompt_for_open_path(
  702        options,
  703        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  704        window,
  705        cx,
  706    );
  707    let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
  708    cx.spawn_in(window, async move |this, cx| {
  709        let Some(paths) = paths.await.log_err().flatten() else {
  710            return;
  711        };
  712        if !create_new_window {
  713            if let Some(handle) = multi_workspace_handle {
  714                if let Some(task) = handle
  715                    .update(cx, |multi_workspace, window, cx| {
  716                        multi_workspace.open_project(paths, OpenMode::Replace, window, cx)
  717                    })
  718                    .log_err()
  719                {
  720                    task.await.log_err();
  721                }
  722                return;
  723            }
  724        }
  725        if let Some(task) = this
  726            .update_in(cx, |this, window, cx| {
  727                this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
  728            })
  729            .log_err()
  730        {
  731            task.await.log_err();
  732        }
  733    })
  734    .detach();
  735}
  736
  737pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  738    component::init();
  739    theme_preview::init(cx);
  740    toast_layer::init(cx);
  741    history_manager::init(app_state.fs.clone(), cx);
  742
  743    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  744        .on_action(|_: &Reload, cx| reload(cx))
  745        .on_action(|_: &Open, cx: &mut App| {
  746            let app_state = AppState::global(cx);
  747            prompt_and_open_paths(
  748                app_state,
  749                PathPromptOptions {
  750                    files: true,
  751                    directories: true,
  752                    multiple: true,
  753                    prompt: None,
  754                },
  755                cx,
  756            );
  757        })
  758        .on_action(|_: &OpenFiles, cx: &mut App| {
  759            let directories = cx.can_select_mixed_files_and_dirs();
  760            let app_state = AppState::global(cx);
  761            prompt_and_open_paths(
  762                app_state,
  763                PathPromptOptions {
  764                    files: true,
  765                    directories,
  766                    multiple: true,
  767                    prompt: None,
  768                },
  769                cx,
  770            );
  771        });
  772}
  773
  774type BuildProjectItemFn =
  775    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  776
  777type BuildProjectItemForPathFn =
  778    fn(
  779        &Entity<Project>,
  780        &ProjectPath,
  781        &mut Window,
  782        &mut App,
  783    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  784
  785#[derive(Clone, Default)]
  786struct ProjectItemRegistry {
  787    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  788    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  789}
  790
  791impl ProjectItemRegistry {
  792    fn register<T: ProjectItem>(&mut self) {
  793        self.build_project_item_fns_by_type.insert(
  794            TypeId::of::<T::Item>(),
  795            |item, project, pane, window, cx| {
  796                let item = item.downcast().unwrap();
  797                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  798                    as Box<dyn ItemHandle>
  799            },
  800        );
  801        self.build_project_item_for_path_fns
  802            .push(|project, project_path, window, cx| {
  803                let project_path = project_path.clone();
  804                let is_file = project
  805                    .read(cx)
  806                    .entry_for_path(&project_path, cx)
  807                    .is_some_and(|entry| entry.is_file());
  808                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  809                let is_local = project.read(cx).is_local();
  810                let project_item =
  811                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  812                let project = project.clone();
  813                Some(window.spawn(cx, async move |cx| {
  814                    match project_item.await.with_context(|| {
  815                        format!(
  816                            "opening project path {:?}",
  817                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  818                        )
  819                    }) {
  820                        Ok(project_item) => {
  821                            let project_item = project_item;
  822                            let project_entry_id: Option<ProjectEntryId> =
  823                                project_item.read_with(cx, project::ProjectItem::entry_id);
  824                            let build_workspace_item = Box::new(
  825                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  826                                    Box::new(cx.new(|cx| {
  827                                        T::for_project_item(
  828                                            project,
  829                                            Some(pane),
  830                                            project_item,
  831                                            window,
  832                                            cx,
  833                                        )
  834                                    })) as Box<dyn ItemHandle>
  835                                },
  836                            ) as Box<_>;
  837                            Ok((project_entry_id, build_workspace_item))
  838                        }
  839                        Err(e) => {
  840                            log::warn!("Failed to open a project item: {e:#}");
  841                            if e.error_code() == ErrorCode::Internal {
  842                                if let Some(abs_path) =
  843                                    entry_abs_path.as_deref().filter(|_| is_file)
  844                                {
  845                                    if let Some(broken_project_item_view) =
  846                                        cx.update(|window, cx| {
  847                                            T::for_broken_project_item(
  848                                                abs_path, is_local, &e, window, cx,
  849                                            )
  850                                        })?
  851                                    {
  852                                        let build_workspace_item = Box::new(
  853                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  854                                                cx.new(|_| broken_project_item_view).boxed_clone()
  855                                            },
  856                                        )
  857                                        as Box<_>;
  858                                        return Ok((None, build_workspace_item));
  859                                    }
  860                                }
  861                            }
  862                            Err(e)
  863                        }
  864                    }
  865                }))
  866            });
  867    }
  868
  869    fn open_path(
  870        &self,
  871        project: &Entity<Project>,
  872        path: &ProjectPath,
  873        window: &mut Window,
  874        cx: &mut App,
  875    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  876        let Some(open_project_item) = self
  877            .build_project_item_for_path_fns
  878            .iter()
  879            .rev()
  880            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  881        else {
  882            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  883        };
  884        open_project_item
  885    }
  886
  887    fn build_item<T: project::ProjectItem>(
  888        &self,
  889        item: Entity<T>,
  890        project: Entity<Project>,
  891        pane: Option<&Pane>,
  892        window: &mut Window,
  893        cx: &mut App,
  894    ) -> Option<Box<dyn ItemHandle>> {
  895        let build = self
  896            .build_project_item_fns_by_type
  897            .get(&TypeId::of::<T>())?;
  898        Some(build(item.into_any(), project, pane, window, cx))
  899    }
  900}
  901
  902type WorkspaceItemBuilder =
  903    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  904
  905impl Global for ProjectItemRegistry {}
  906
  907/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  908/// items will get a chance to open the file, starting from the project item that
  909/// was added last.
  910pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  911    cx.default_global::<ProjectItemRegistry>().register::<I>();
  912}
  913
  914#[derive(Default)]
  915pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  916
  917struct FollowableViewDescriptor {
  918    from_state_proto: fn(
  919        Entity<Workspace>,
  920        ViewId,
  921        &mut Option<proto::view::Variant>,
  922        &mut Window,
  923        &mut App,
  924    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  925    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  926}
  927
  928impl Global for FollowableViewRegistry {}
  929
  930impl FollowableViewRegistry {
  931    pub fn register<I: FollowableItem>(cx: &mut App) {
  932        cx.default_global::<Self>().0.insert(
  933            TypeId::of::<I>(),
  934            FollowableViewDescriptor {
  935                from_state_proto: |workspace, id, state, window, cx| {
  936                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  937                        cx.foreground_executor()
  938                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  939                    })
  940                },
  941                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  942            },
  943        );
  944    }
  945
  946    pub fn from_state_proto(
  947        workspace: Entity<Workspace>,
  948        view_id: ViewId,
  949        mut state: Option<proto::view::Variant>,
  950        window: &mut Window,
  951        cx: &mut App,
  952    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  953        cx.update_default_global(|this: &mut Self, cx| {
  954            this.0.values().find_map(|descriptor| {
  955                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  956            })
  957        })
  958    }
  959
  960    pub fn to_followable_view(
  961        view: impl Into<AnyView>,
  962        cx: &App,
  963    ) -> Option<Box<dyn FollowableItemHandle>> {
  964        let this = cx.try_global::<Self>()?;
  965        let view = view.into();
  966        let descriptor = this.0.get(&view.entity_type())?;
  967        Some((descriptor.to_followable_view)(&view))
  968    }
  969}
  970
  971#[derive(Copy, Clone)]
  972struct SerializableItemDescriptor {
  973    deserialize: fn(
  974        Entity<Project>,
  975        WeakEntity<Workspace>,
  976        WorkspaceId,
  977        ItemId,
  978        &mut Window,
  979        &mut Context<Pane>,
  980    ) -> Task<Result<Box<dyn ItemHandle>>>,
  981    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  982    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  983}
  984
  985#[derive(Default)]
  986struct SerializableItemRegistry {
  987    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  988    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  989}
  990
  991impl Global for SerializableItemRegistry {}
  992
  993impl SerializableItemRegistry {
  994    fn deserialize(
  995        item_kind: &str,
  996        project: Entity<Project>,
  997        workspace: WeakEntity<Workspace>,
  998        workspace_id: WorkspaceId,
  999        item_item: ItemId,
 1000        window: &mut Window,
 1001        cx: &mut Context<Pane>,
 1002    ) -> Task<Result<Box<dyn ItemHandle>>> {
 1003        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1004            return Task::ready(Err(anyhow!(
 1005                "cannot deserialize {}, descriptor not found",
 1006                item_kind
 1007            )));
 1008        };
 1009
 1010        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
 1011    }
 1012
 1013    fn cleanup(
 1014        item_kind: &str,
 1015        workspace_id: WorkspaceId,
 1016        loaded_items: Vec<ItemId>,
 1017        window: &mut Window,
 1018        cx: &mut App,
 1019    ) -> Task<Result<()>> {
 1020        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1021            return Task::ready(Err(anyhow!(
 1022                "cannot cleanup {}, descriptor not found",
 1023                item_kind
 1024            )));
 1025        };
 1026
 1027        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
 1028    }
 1029
 1030    fn view_to_serializable_item_handle(
 1031        view: AnyView,
 1032        cx: &App,
 1033    ) -> Option<Box<dyn SerializableItemHandle>> {
 1034        let this = cx.try_global::<Self>()?;
 1035        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
 1036        Some((descriptor.view_to_serializable_item)(view))
 1037    }
 1038
 1039    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
 1040        let this = cx.try_global::<Self>()?;
 1041        this.descriptors_by_kind.get(item_kind).copied()
 1042    }
 1043}
 1044
 1045pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
 1046    let serialized_item_kind = I::serialized_item_kind();
 1047
 1048    let registry = cx.default_global::<SerializableItemRegistry>();
 1049    let descriptor = SerializableItemDescriptor {
 1050        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
 1051            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
 1052            cx.foreground_executor()
 1053                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 1054        },
 1055        cleanup: |workspace_id, loaded_items, window, cx| {
 1056            I::cleanup(workspace_id, loaded_items, window, cx)
 1057        },
 1058        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1059    };
 1060    registry
 1061        .descriptors_by_kind
 1062        .insert(Arc::from(serialized_item_kind), descriptor);
 1063    registry
 1064        .descriptors_by_type
 1065        .insert(TypeId::of::<I>(), descriptor);
 1066}
 1067
 1068pub struct AppState {
 1069    pub languages: Arc<LanguageRegistry>,
 1070    pub client: Arc<Client>,
 1071    pub user_store: Entity<UserStore>,
 1072    pub workspace_store: Entity<WorkspaceStore>,
 1073    pub fs: Arc<dyn fs::Fs>,
 1074    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1075    pub node_runtime: NodeRuntime,
 1076    pub session: Entity<AppSession>,
 1077}
 1078
 1079struct GlobalAppState(Arc<AppState>);
 1080
 1081impl Global for GlobalAppState {}
 1082
 1083pub struct WorkspaceStore {
 1084    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1085    client: Arc<Client>,
 1086    _subscriptions: Vec<client::Subscription>,
 1087}
 1088
 1089#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1090pub enum CollaboratorId {
 1091    PeerId(PeerId),
 1092    Agent,
 1093}
 1094
 1095impl From<PeerId> for CollaboratorId {
 1096    fn from(peer_id: PeerId) -> Self {
 1097        CollaboratorId::PeerId(peer_id)
 1098    }
 1099}
 1100
 1101impl From<&PeerId> for CollaboratorId {
 1102    fn from(peer_id: &PeerId) -> Self {
 1103        CollaboratorId::PeerId(*peer_id)
 1104    }
 1105}
 1106
 1107#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1108struct Follower {
 1109    project_id: Option<u64>,
 1110    peer_id: PeerId,
 1111}
 1112
 1113impl AppState {
 1114    #[track_caller]
 1115    pub fn global(cx: &App) -> Arc<Self> {
 1116        cx.global::<GlobalAppState>().0.clone()
 1117    }
 1118    pub fn try_global(cx: &App) -> Option<Arc<Self>> {
 1119        cx.try_global::<GlobalAppState>()
 1120            .map(|state| state.0.clone())
 1121    }
 1122    pub fn set_global(state: Arc<AppState>, cx: &mut App) {
 1123        cx.set_global(GlobalAppState(state));
 1124    }
 1125
 1126    #[cfg(any(test, feature = "test-support"))]
 1127    pub fn test(cx: &mut App) -> Arc<Self> {
 1128        use fs::Fs;
 1129        use node_runtime::NodeRuntime;
 1130        use session::Session;
 1131        use settings::SettingsStore;
 1132
 1133        if !cx.has_global::<SettingsStore>() {
 1134            let settings_store = SettingsStore::test(cx);
 1135            cx.set_global(settings_store);
 1136        }
 1137
 1138        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1139        <dyn Fs>::set_global(fs.clone(), cx);
 1140        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1141        let clock = Arc::new(clock::FakeSystemClock::new());
 1142        let http_client = http_client::FakeHttpClient::with_404_response();
 1143        let client = Client::new(clock, http_client, cx);
 1144        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1145        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1146        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1147
 1148        theme_settings::init(theme::LoadThemes::JustBase, cx);
 1149        client::init(&client, cx);
 1150
 1151        Arc::new(Self {
 1152            client,
 1153            fs,
 1154            languages,
 1155            user_store,
 1156            workspace_store,
 1157            node_runtime: NodeRuntime::unavailable(),
 1158            build_window_options: |_, _| Default::default(),
 1159            session,
 1160        })
 1161    }
 1162}
 1163
 1164struct DelayedDebouncedEditAction {
 1165    task: Option<Task<()>>,
 1166    cancel_channel: Option<oneshot::Sender<()>>,
 1167}
 1168
 1169impl DelayedDebouncedEditAction {
 1170    fn new() -> DelayedDebouncedEditAction {
 1171        DelayedDebouncedEditAction {
 1172            task: None,
 1173            cancel_channel: None,
 1174        }
 1175    }
 1176
 1177    fn fire_new<F>(
 1178        &mut self,
 1179        delay: Duration,
 1180        window: &mut Window,
 1181        cx: &mut Context<Workspace>,
 1182        func: F,
 1183    ) where
 1184        F: 'static
 1185            + Send
 1186            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1187    {
 1188        if let Some(channel) = self.cancel_channel.take() {
 1189            _ = channel.send(());
 1190        }
 1191
 1192        let (sender, mut receiver) = oneshot::channel::<()>();
 1193        self.cancel_channel = Some(sender);
 1194
 1195        let previous_task = self.task.take();
 1196        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1197            let mut timer = cx.background_executor().timer(delay).fuse();
 1198            if let Some(previous_task) = previous_task {
 1199                previous_task.await;
 1200            }
 1201
 1202            futures::select_biased! {
 1203                _ = receiver => return,
 1204                    _ = timer => {}
 1205            }
 1206
 1207            if let Some(result) = workspace
 1208                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1209                .log_err()
 1210            {
 1211                result.await.log_err();
 1212            }
 1213        }));
 1214    }
 1215}
 1216
 1217pub enum Event {
 1218    PaneAdded(Entity<Pane>),
 1219    PaneRemoved,
 1220    ItemAdded {
 1221        item: Box<dyn ItemHandle>,
 1222    },
 1223    ActiveItemChanged,
 1224    ItemRemoved {
 1225        item_id: EntityId,
 1226    },
 1227    UserSavedItem {
 1228        pane: WeakEntity<Pane>,
 1229        item: Box<dyn WeakItemHandle>,
 1230        save_intent: SaveIntent,
 1231    },
 1232    ContactRequestedJoin(u64),
 1233    WorkspaceCreated(WeakEntity<Workspace>),
 1234    OpenBundledFile {
 1235        text: Cow<'static, str>,
 1236        title: &'static str,
 1237        language: &'static str,
 1238    },
 1239    ZoomChanged,
 1240    ModalOpened,
 1241    Activate,
 1242    PanelAdded(AnyView),
 1243}
 1244
 1245#[derive(Debug, Clone)]
 1246pub enum OpenVisible {
 1247    All,
 1248    None,
 1249    OnlyFiles,
 1250    OnlyDirectories,
 1251}
 1252
 1253enum WorkspaceLocation {
 1254    // Valid local paths or SSH project to serialize
 1255    Location(SerializedWorkspaceLocation, PathList),
 1256    // No valid location found hence clear session id
 1257    DetachFromSession,
 1258    // No valid location found to serialize
 1259    None,
 1260}
 1261
 1262type PromptForNewPath = Box<
 1263    dyn Fn(
 1264        &mut Workspace,
 1265        DirectoryLister,
 1266        Option<String>,
 1267        &mut Window,
 1268        &mut Context<Workspace>,
 1269    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1270>;
 1271
 1272type PromptForOpenPath = Box<
 1273    dyn Fn(
 1274        &mut Workspace,
 1275        DirectoryLister,
 1276        &mut Window,
 1277        &mut Context<Workspace>,
 1278    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1279>;
 1280
 1281#[derive(Default)]
 1282struct DispatchingKeystrokes {
 1283    dispatched: HashSet<Vec<Keystroke>>,
 1284    queue: VecDeque<Keystroke>,
 1285    task: Option<Shared<Task<()>>>,
 1286}
 1287
 1288/// Collects everything project-related for a certain window opened.
 1289/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1290///
 1291/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1292/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1293/// that can be used to register a global action to be triggered from any place in the window.
 1294pub struct Workspace {
 1295    weak_self: WeakEntity<Self>,
 1296    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1297    zoomed: Option<AnyWeakView>,
 1298    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1299    zoomed_position: Option<DockPosition>,
 1300    center: PaneGroup,
 1301    left_dock: Entity<Dock>,
 1302    bottom_dock: Entity<Dock>,
 1303    right_dock: Entity<Dock>,
 1304    panes: Vec<Entity<Pane>>,
 1305    active_worktree_override: Option<WorktreeId>,
 1306    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1307    active_pane: Entity<Pane>,
 1308    last_active_center_pane: Option<WeakEntity<Pane>>,
 1309    last_active_view_id: Option<proto::ViewId>,
 1310    status_bar: Entity<StatusBar>,
 1311    pub(crate) modal_layer: Entity<ModalLayer>,
 1312    toast_layer: Entity<ToastLayer>,
 1313    titlebar_item: Option<AnyView>,
 1314    notifications: Notifications,
 1315    suppressed_notifications: HashSet<NotificationId>,
 1316    project: Entity<Project>,
 1317    follower_states: HashMap<CollaboratorId, FollowerState>,
 1318    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1319    window_edited: bool,
 1320    last_window_title: Option<String>,
 1321    dirty_items: HashMap<EntityId, Subscription>,
 1322    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1323    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1324    database_id: Option<WorkspaceId>,
 1325    app_state: Arc<AppState>,
 1326    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1327    _subscriptions: Vec<Subscription>,
 1328    _apply_leader_updates: Task<Result<()>>,
 1329    _observe_current_user: Task<Result<()>>,
 1330    _schedule_serialize_workspace: Option<Task<()>>,
 1331    _serialize_workspace_task: Option<Task<()>>,
 1332    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1333    pane_history_timestamp: Arc<AtomicUsize>,
 1334    bounds: Bounds<Pixels>,
 1335    pub centered_layout: bool,
 1336    bounds_save_task_queued: Option<Task<()>>,
 1337    on_prompt_for_new_path: Option<PromptForNewPath>,
 1338    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1339    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1340    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1341    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1342    _items_serializer: Task<Result<()>>,
 1343    session_id: Option<String>,
 1344    scheduled_tasks: Vec<Task<()>>,
 1345    last_open_dock_positions: Vec<DockPosition>,
 1346    removing: bool,
 1347    _panels_task: Option<Task<Result<()>>>,
 1348    sidebar_focus_handle: Option<FocusHandle>,
 1349    multi_workspace: Option<WeakEntity<MultiWorkspace>>,
 1350}
 1351
 1352impl EventEmitter<Event> for Workspace {}
 1353
 1354#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1355pub struct ViewId {
 1356    pub creator: CollaboratorId,
 1357    pub id: u64,
 1358}
 1359
 1360pub struct FollowerState {
 1361    center_pane: Entity<Pane>,
 1362    dock_pane: Option<Entity<Pane>>,
 1363    active_view_id: Option<ViewId>,
 1364    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1365}
 1366
 1367struct FollowerView {
 1368    view: Box<dyn FollowableItemHandle>,
 1369    location: Option<proto::PanelId>,
 1370}
 1371
 1372#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
 1373pub enum OpenMode {
 1374    /// Open the workspace in a new window.
 1375    NewWindow,
 1376    /// Add to the window's multi workspace without activating it (used during deserialization).
 1377    Add,
 1378    /// Add to the window's multi workspace and activate it.
 1379    #[default]
 1380    Activate,
 1381    /// Replace the currently active workspace, and any of it's linked workspaces
 1382    Replace,
 1383}
 1384
 1385impl Workspace {
 1386    pub fn new(
 1387        workspace_id: Option<WorkspaceId>,
 1388        project: Entity<Project>,
 1389        app_state: Arc<AppState>,
 1390        window: &mut Window,
 1391        cx: &mut Context<Self>,
 1392    ) -> Self {
 1393        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1394            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1395                if let TrustedWorktreesEvent::Trusted(..) = e {
 1396                    // Do not persist auto trusted worktrees
 1397                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1398                        worktrees_store.update(cx, |worktrees_store, cx| {
 1399                            worktrees_store.schedule_serialization(
 1400                                cx,
 1401                                |new_trusted_worktrees, cx| {
 1402                                    let timeout =
 1403                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1404                                    let db = WorkspaceDb::global(cx);
 1405                                    cx.background_spawn(async move {
 1406                                        timeout.await;
 1407                                        db.save_trusted_worktrees(new_trusted_worktrees)
 1408                                            .await
 1409                                            .log_err();
 1410                                    })
 1411                                },
 1412                            )
 1413                        });
 1414                    }
 1415                }
 1416            })
 1417            .detach();
 1418
 1419            cx.observe_global::<SettingsStore>(|_, cx| {
 1420                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1421                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1422                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1423                            trusted_worktrees.auto_trust_all(cx);
 1424                        })
 1425                    }
 1426                }
 1427            })
 1428            .detach();
 1429        }
 1430
 1431        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1432            match event {
 1433                project::Event::RemoteIdChanged(_) => {
 1434                    this.update_window_title(window, cx);
 1435                }
 1436
 1437                project::Event::CollaboratorLeft(peer_id) => {
 1438                    this.collaborator_left(*peer_id, window, cx);
 1439                }
 1440
 1441                &project::Event::WorktreeRemoved(_) => {
 1442                    this.update_window_title(window, cx);
 1443                    this.serialize_workspace(window, cx);
 1444                    this.update_history(cx);
 1445                }
 1446
 1447                &project::Event::WorktreeAdded(id) => {
 1448                    this.update_window_title(window, cx);
 1449                    if this
 1450                        .project()
 1451                        .read(cx)
 1452                        .worktree_for_id(id, cx)
 1453                        .is_some_and(|wt| wt.read(cx).is_visible())
 1454                    {
 1455                        this.serialize_workspace(window, cx);
 1456                        this.update_history(cx);
 1457                    }
 1458                }
 1459                project::Event::WorktreeUpdatedEntries(..) => {
 1460                    this.update_window_title(window, cx);
 1461                    this.serialize_workspace(window, cx);
 1462                }
 1463
 1464                project::Event::DisconnectedFromHost => {
 1465                    this.update_window_edited(window, cx);
 1466                    let leaders_to_unfollow =
 1467                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1468                    for leader_id in leaders_to_unfollow {
 1469                        this.unfollow(leader_id, window, cx);
 1470                    }
 1471                }
 1472
 1473                project::Event::DisconnectedFromRemote {
 1474                    server_not_running: _,
 1475                } => {
 1476                    this.update_window_edited(window, cx);
 1477                }
 1478
 1479                project::Event::Closed => {
 1480                    window.remove_window();
 1481                }
 1482
 1483                project::Event::DeletedEntry(_, entry_id) => {
 1484                    for pane in this.panes.iter() {
 1485                        pane.update(cx, |pane, cx| {
 1486                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1487                        });
 1488                    }
 1489                }
 1490
 1491                project::Event::Toast {
 1492                    notification_id,
 1493                    message,
 1494                    link,
 1495                } => this.show_notification(
 1496                    NotificationId::named(notification_id.clone()),
 1497                    cx,
 1498                    |cx| {
 1499                        let mut notification = MessageNotification::new(message.clone(), cx);
 1500                        if let Some(link) = link {
 1501                            notification = notification
 1502                                .more_info_message(link.label)
 1503                                .more_info_url(link.url);
 1504                        }
 1505
 1506                        cx.new(|_| notification)
 1507                    },
 1508                ),
 1509
 1510                project::Event::HideToast { notification_id } => {
 1511                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1512                }
 1513
 1514                project::Event::LanguageServerPrompt(request) => {
 1515                    struct LanguageServerPrompt;
 1516
 1517                    this.show_notification(
 1518                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1519                        cx,
 1520                        |cx| {
 1521                            cx.new(|cx| {
 1522                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1523                            })
 1524                        },
 1525                    );
 1526                }
 1527
 1528                project::Event::AgentLocationChanged => {
 1529                    this.handle_agent_location_changed(window, cx)
 1530                }
 1531
 1532                _ => {}
 1533            }
 1534            cx.notify()
 1535        })
 1536        .detach();
 1537
 1538        cx.subscribe_in(
 1539            &project.read(cx).breakpoint_store(),
 1540            window,
 1541            |workspace, _, event, window, cx| match event {
 1542                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1543                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1544                    workspace.serialize_workspace(window, cx);
 1545                }
 1546                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1547            },
 1548        )
 1549        .detach();
 1550        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1551            cx.subscribe_in(
 1552                &toolchain_store,
 1553                window,
 1554                |workspace, _, event, window, cx| match event {
 1555                    ToolchainStoreEvent::CustomToolchainsModified => {
 1556                        workspace.serialize_workspace(window, cx);
 1557                    }
 1558                    _ => {}
 1559                },
 1560            )
 1561            .detach();
 1562        }
 1563
 1564        cx.on_focus_lost(window, |this, window, cx| {
 1565            let focus_handle = this.focus_handle(cx);
 1566            window.focus(&focus_handle, cx);
 1567        })
 1568        .detach();
 1569
 1570        let weak_handle = cx.entity().downgrade();
 1571        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1572
 1573        let center_pane = cx.new(|cx| {
 1574            let mut center_pane = Pane::new(
 1575                weak_handle.clone(),
 1576                project.clone(),
 1577                pane_history_timestamp.clone(),
 1578                None,
 1579                NewFile.boxed_clone(),
 1580                true,
 1581                window,
 1582                cx,
 1583            );
 1584            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1585            center_pane.set_should_display_welcome_page(true);
 1586            center_pane
 1587        });
 1588        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1589            .detach();
 1590
 1591        window.focus(&center_pane.focus_handle(cx), cx);
 1592
 1593        cx.emit(Event::PaneAdded(center_pane.clone()));
 1594
 1595        let any_window_handle = window.window_handle();
 1596        app_state.workspace_store.update(cx, |store, _| {
 1597            store
 1598                .workspaces
 1599                .insert((any_window_handle, weak_handle.clone()));
 1600        });
 1601
 1602        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1603        let mut connection_status = app_state.client.status();
 1604        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1605            current_user.next().await;
 1606            connection_status.next().await;
 1607            let mut stream =
 1608                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1609
 1610            while stream.recv().await.is_some() {
 1611                this.update(cx, |_, cx| cx.notify())?;
 1612            }
 1613            anyhow::Ok(())
 1614        });
 1615
 1616        // All leader updates are enqueued and then processed in a single task, so
 1617        // that each asynchronous operation can be run in order.
 1618        let (leader_updates_tx, mut leader_updates_rx) =
 1619            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1620        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1621            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1622                Self::process_leader_update(&this, leader_id, update, cx)
 1623                    .await
 1624                    .log_err();
 1625            }
 1626
 1627            Ok(())
 1628        });
 1629
 1630        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1631        let modal_layer = cx.new(|_| ModalLayer::new());
 1632        let toast_layer = cx.new(|_| ToastLayer::new());
 1633        cx.subscribe(
 1634            &modal_layer,
 1635            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1636                cx.emit(Event::ModalOpened);
 1637            },
 1638        )
 1639        .detach();
 1640
 1641        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1642        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1643        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1644        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1645        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1646        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1647        let multi_workspace = window
 1648            .root::<MultiWorkspace>()
 1649            .flatten()
 1650            .map(|mw| mw.downgrade());
 1651        let status_bar = cx.new(|cx| {
 1652            let mut status_bar =
 1653                StatusBar::new(&center_pane.clone(), multi_workspace.clone(), window, cx);
 1654            status_bar.add_left_item(left_dock_buttons, window, cx);
 1655            status_bar.add_right_item(right_dock_buttons, window, cx);
 1656            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1657            status_bar
 1658        });
 1659
 1660        let session_id = app_state.session.read(cx).id().to_owned();
 1661
 1662        let mut active_call = None;
 1663        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1664            let subscriptions =
 1665                vec![
 1666                    call.0
 1667                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1668                ];
 1669            active_call = Some((call, subscriptions));
 1670        }
 1671
 1672        let (serializable_items_tx, serializable_items_rx) =
 1673            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1674        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1675            Self::serialize_items(&this, serializable_items_rx, cx).await
 1676        });
 1677
 1678        let subscriptions = vec![
 1679            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1680            cx.observe_window_bounds(window, move |this, window, cx| {
 1681                if this.bounds_save_task_queued.is_some() {
 1682                    return;
 1683                }
 1684                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1685                    cx.background_executor()
 1686                        .timer(Duration::from_millis(100))
 1687                        .await;
 1688                    this.update_in(cx, |this, window, cx| {
 1689                        this.save_window_bounds(window, cx).detach();
 1690                        this.bounds_save_task_queued.take();
 1691                    })
 1692                    .ok();
 1693                }));
 1694                cx.notify();
 1695            }),
 1696            cx.observe_window_appearance(window, |_, window, cx| {
 1697                let window_appearance = window.appearance();
 1698
 1699                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1700
 1701                theme_settings::reload_theme(cx);
 1702                theme_settings::reload_icon_theme(cx);
 1703            }),
 1704            cx.on_release({
 1705                let weak_handle = weak_handle.clone();
 1706                move |this, cx| {
 1707                    this.app_state.workspace_store.update(cx, move |store, _| {
 1708                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1709                    })
 1710                }
 1711            }),
 1712        ];
 1713
 1714        cx.defer_in(window, move |this, window, cx| {
 1715            this.update_window_title(window, cx);
 1716            this.show_initial_notifications(cx);
 1717        });
 1718
 1719        let mut center = PaneGroup::new(center_pane.clone());
 1720        center.set_is_center(true);
 1721        center.mark_positions(cx);
 1722
 1723        Workspace {
 1724            weak_self: weak_handle.clone(),
 1725            zoomed: None,
 1726            zoomed_position: None,
 1727            previous_dock_drag_coordinates: None,
 1728            center,
 1729            panes: vec![center_pane.clone()],
 1730            panes_by_item: Default::default(),
 1731            active_pane: center_pane.clone(),
 1732            last_active_center_pane: Some(center_pane.downgrade()),
 1733            last_active_view_id: None,
 1734            status_bar,
 1735            modal_layer,
 1736            toast_layer,
 1737            titlebar_item: None,
 1738            active_worktree_override: None,
 1739            notifications: Notifications::default(),
 1740            suppressed_notifications: HashSet::default(),
 1741            left_dock,
 1742            bottom_dock,
 1743            right_dock,
 1744            _panels_task: None,
 1745            project: project.clone(),
 1746            follower_states: Default::default(),
 1747            last_leaders_by_pane: Default::default(),
 1748            dispatching_keystrokes: Default::default(),
 1749            window_edited: false,
 1750            last_window_title: None,
 1751            dirty_items: Default::default(),
 1752            active_call,
 1753            database_id: workspace_id,
 1754            app_state,
 1755            _observe_current_user,
 1756            _apply_leader_updates,
 1757            _schedule_serialize_workspace: None,
 1758            _serialize_workspace_task: None,
 1759            _schedule_serialize_ssh_paths: None,
 1760            leader_updates_tx,
 1761            _subscriptions: subscriptions,
 1762            pane_history_timestamp,
 1763            workspace_actions: Default::default(),
 1764            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1765            bounds: Default::default(),
 1766            centered_layout: false,
 1767            bounds_save_task_queued: None,
 1768            on_prompt_for_new_path: None,
 1769            on_prompt_for_open_path: None,
 1770            terminal_provider: None,
 1771            debugger_provider: None,
 1772            serializable_items_tx,
 1773            _items_serializer,
 1774            session_id: Some(session_id),
 1775
 1776            scheduled_tasks: Vec::new(),
 1777            last_open_dock_positions: Vec::new(),
 1778            removing: false,
 1779            sidebar_focus_handle: None,
 1780            multi_workspace,
 1781        }
 1782    }
 1783
 1784    pub fn new_local(
 1785        abs_paths: Vec<PathBuf>,
 1786        app_state: Arc<AppState>,
 1787        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1788        env: Option<HashMap<String, String>>,
 1789        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1790        open_mode: OpenMode,
 1791        cx: &mut App,
 1792    ) -> Task<anyhow::Result<OpenResult>> {
 1793        let project_handle = Project::local(
 1794            app_state.client.clone(),
 1795            app_state.node_runtime.clone(),
 1796            app_state.user_store.clone(),
 1797            app_state.languages.clone(),
 1798            app_state.fs.clone(),
 1799            env,
 1800            Default::default(),
 1801            cx,
 1802        );
 1803
 1804        let db = WorkspaceDb::global(cx);
 1805        let kvp = db::kvp::KeyValueStore::global(cx);
 1806        cx.spawn(async move |cx| {
 1807            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1808            for path in abs_paths.into_iter() {
 1809                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1810                    paths_to_open.push(canonical)
 1811                } else {
 1812                    paths_to_open.push(path)
 1813                }
 1814            }
 1815
 1816            let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
 1817
 1818            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1819                paths_to_open = paths.ordered_paths().cloned().collect();
 1820                if !paths.is_lexicographically_ordered() {
 1821                    project_handle.update(cx, |project, cx| {
 1822                        project.set_worktrees_reordered(true, cx);
 1823                    });
 1824                }
 1825            }
 1826
 1827            // Get project paths for all of the abs_paths
 1828            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1829                Vec::with_capacity(paths_to_open.len());
 1830
 1831            for path in paths_to_open.into_iter() {
 1832                if let Some((_, project_entry)) = cx
 1833                    .update(|cx| {
 1834                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1835                    })
 1836                    .await
 1837                    .log_err()
 1838                {
 1839                    project_paths.push((path, Some(project_entry)));
 1840                } else {
 1841                    project_paths.push((path, None));
 1842                }
 1843            }
 1844
 1845            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1846                serialized_workspace.id
 1847            } else {
 1848                db.next_id().await.unwrap_or_else(|_| Default::default())
 1849            };
 1850
 1851            let toolchains = db.toolchains(workspace_id).await?;
 1852
 1853            for (toolchain, worktree_path, path) in toolchains {
 1854                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1855                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1856                    this.find_worktree(&worktree_path, cx)
 1857                        .and_then(|(worktree, rel_path)| {
 1858                            if rel_path.is_empty() {
 1859                                Some(worktree.read(cx).id())
 1860                            } else {
 1861                                None
 1862                            }
 1863                        })
 1864                }) else {
 1865                    // We did not find a worktree with a given path, but that's whatever.
 1866                    continue;
 1867                };
 1868                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1869                    continue;
 1870                }
 1871
 1872                project_handle
 1873                    .update(cx, |this, cx| {
 1874                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1875                    })
 1876                    .await;
 1877            }
 1878            if let Some(workspace) = serialized_workspace.as_ref() {
 1879                project_handle.update(cx, |this, cx| {
 1880                    for (scope, toolchains) in &workspace.user_toolchains {
 1881                        for toolchain in toolchains {
 1882                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1883                        }
 1884                    }
 1885                });
 1886            }
 1887
 1888            let window_to_replace = match open_mode {
 1889                OpenMode::NewWindow => None,
 1890                _ => requesting_window,
 1891            };
 1892
 1893            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1894                if let Some(window) = window_to_replace {
 1895                    let centered_layout = serialized_workspace
 1896                        .as_ref()
 1897                        .map(|w| w.centered_layout)
 1898                        .unwrap_or(false);
 1899
 1900                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1901                        let workspace = cx.new(|cx| {
 1902                            let mut workspace = Workspace::new(
 1903                                Some(workspace_id),
 1904                                project_handle.clone(),
 1905                                app_state.clone(),
 1906                                window,
 1907                                cx,
 1908                            );
 1909
 1910                            workspace.centered_layout = centered_layout;
 1911
 1912                            // Call init callback to add items before window renders
 1913                            if let Some(init) = init {
 1914                                init(&mut workspace, window, cx);
 1915                            }
 1916
 1917                            workspace
 1918                        });
 1919                        match open_mode {
 1920                            OpenMode::Replace => {
 1921                                multi_workspace.replace(workspace.clone(), &*window, cx);
 1922                            }
 1923                            OpenMode::Activate => {
 1924                                multi_workspace.activate(workspace.clone(), window, cx);
 1925                            }
 1926                            OpenMode::Add => {
 1927                                multi_workspace.add(workspace.clone(), &*window, cx);
 1928                            }
 1929                            OpenMode::NewWindow => {
 1930                                unreachable!()
 1931                            }
 1932                        }
 1933                        workspace
 1934                    })?;
 1935                    (window, workspace)
 1936                } else {
 1937                    let window_bounds_override = window_bounds_env_override();
 1938
 1939                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1940                        (Some(WindowBounds::Windowed(bounds)), None)
 1941                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1942                        && let Some(display) = workspace.display
 1943                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1944                    {
 1945                        // Reopening an existing workspace - restore its saved bounds
 1946                        (Some(bounds.0), Some(display))
 1947                    } else if let Some((display, bounds)) =
 1948                        persistence::read_default_window_bounds(&kvp)
 1949                    {
 1950                        // New or empty workspace - use the last known window bounds
 1951                        (Some(bounds), Some(display))
 1952                    } else {
 1953                        // New window - let GPUI's default_bounds() handle cascading
 1954                        (None, None)
 1955                    };
 1956
 1957                    // Use the serialized workspace to construct the new window
 1958                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1959                    options.window_bounds = window_bounds;
 1960                    let centered_layout = serialized_workspace
 1961                        .as_ref()
 1962                        .map(|w| w.centered_layout)
 1963                        .unwrap_or(false);
 1964                    let window = cx.open_window(options, {
 1965                        let app_state = app_state.clone();
 1966                        let project_handle = project_handle.clone();
 1967                        move |window, cx| {
 1968                            let workspace = cx.new(|cx| {
 1969                                let mut workspace = Workspace::new(
 1970                                    Some(workspace_id),
 1971                                    project_handle,
 1972                                    app_state,
 1973                                    window,
 1974                                    cx,
 1975                                );
 1976                                workspace.centered_layout = centered_layout;
 1977
 1978                                // Call init callback to add items before window renders
 1979                                if let Some(init) = init {
 1980                                    init(&mut workspace, window, cx);
 1981                                }
 1982
 1983                                workspace
 1984                            });
 1985                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 1986                        }
 1987                    })?;
 1988                    let workspace =
 1989                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 1990                            multi_workspace.workspace().clone()
 1991                        })?;
 1992                    (window, workspace)
 1993                };
 1994
 1995            notify_if_database_failed(window, cx);
 1996            // Check if this is an empty workspace (no paths to open)
 1997            // An empty workspace is one where project_paths is empty
 1998            let is_empty_workspace = project_paths.is_empty();
 1999            // Check if serialized workspace has paths before it's moved
 2000            let serialized_workspace_has_paths = serialized_workspace
 2001                .as_ref()
 2002                .map(|ws| !ws.paths.is_empty())
 2003                .unwrap_or(false);
 2004
 2005            let opened_items = window
 2006                .update(cx, |_, window, cx| {
 2007                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 2008                        open_items(serialized_workspace, project_paths, window, cx)
 2009                    })
 2010                })?
 2011                .await
 2012                .unwrap_or_default();
 2013
 2014            // Restore default dock state for empty workspaces
 2015            // Only restore if:
 2016            // 1. This is an empty workspace (no paths), AND
 2017            // 2. The serialized workspace either doesn't exist or has no paths
 2018            if is_empty_workspace && !serialized_workspace_has_paths {
 2019                if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
 2020                    window
 2021                        .update(cx, |_, window, cx| {
 2022                            workspace.update(cx, |workspace, cx| {
 2023                                for (dock, serialized_dock) in [
 2024                                    (&workspace.right_dock, &default_docks.right),
 2025                                    (&workspace.left_dock, &default_docks.left),
 2026                                    (&workspace.bottom_dock, &default_docks.bottom),
 2027                                ] {
 2028                                    dock.update(cx, |dock, cx| {
 2029                                        dock.serialized_dock = Some(serialized_dock.clone());
 2030                                        dock.restore_state(window, cx);
 2031                                    });
 2032                                }
 2033                                cx.notify();
 2034                            });
 2035                        })
 2036                        .log_err();
 2037                }
 2038            }
 2039
 2040            window
 2041                .update(cx, |_, _window, cx| {
 2042                    workspace.update(cx, |this: &mut Workspace, cx| {
 2043                        this.update_history(cx);
 2044                    });
 2045                })
 2046                .log_err();
 2047            Ok(OpenResult {
 2048                window,
 2049                workspace,
 2050                opened_items,
 2051            })
 2052        })
 2053    }
 2054
 2055    pub fn weak_handle(&self) -> WeakEntity<Self> {
 2056        self.weak_self.clone()
 2057    }
 2058
 2059    pub fn left_dock(&self) -> &Entity<Dock> {
 2060        &self.left_dock
 2061    }
 2062
 2063    pub fn bottom_dock(&self) -> &Entity<Dock> {
 2064        &self.bottom_dock
 2065    }
 2066
 2067    pub fn set_bottom_dock_layout(
 2068        &mut self,
 2069        layout: BottomDockLayout,
 2070        window: &mut Window,
 2071        cx: &mut Context<Self>,
 2072    ) {
 2073        let fs = self.project().read(cx).fs();
 2074        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 2075            content.workspace.bottom_dock_layout = Some(layout);
 2076        });
 2077
 2078        cx.notify();
 2079        self.serialize_workspace(window, cx);
 2080    }
 2081
 2082    pub fn right_dock(&self) -> &Entity<Dock> {
 2083        &self.right_dock
 2084    }
 2085
 2086    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 2087        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 2088    }
 2089
 2090    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 2091        let left_dock = self.left_dock.read(cx);
 2092        let left_visible = left_dock.is_open();
 2093        let left_active_panel = left_dock
 2094            .active_panel()
 2095            .map(|panel| panel.persistent_name().to_string());
 2096        // `zoomed_position` is kept in sync with individual panel zoom state
 2097        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2098        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2099
 2100        let right_dock = self.right_dock.read(cx);
 2101        let right_visible = right_dock.is_open();
 2102        let right_active_panel = right_dock
 2103            .active_panel()
 2104            .map(|panel| panel.persistent_name().to_string());
 2105        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2106
 2107        let bottom_dock = self.bottom_dock.read(cx);
 2108        let bottom_visible = bottom_dock.is_open();
 2109        let bottom_active_panel = bottom_dock
 2110            .active_panel()
 2111            .map(|panel| panel.persistent_name().to_string());
 2112        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2113
 2114        DockStructure {
 2115            left: DockData {
 2116                visible: left_visible,
 2117                active_panel: left_active_panel,
 2118                zoom: left_dock_zoom,
 2119            },
 2120            right: DockData {
 2121                visible: right_visible,
 2122                active_panel: right_active_panel,
 2123                zoom: right_dock_zoom,
 2124            },
 2125            bottom: DockData {
 2126                visible: bottom_visible,
 2127                active_panel: bottom_active_panel,
 2128                zoom: bottom_dock_zoom,
 2129            },
 2130        }
 2131    }
 2132
 2133    pub fn set_dock_structure(
 2134        &self,
 2135        docks: DockStructure,
 2136        window: &mut Window,
 2137        cx: &mut Context<Self>,
 2138    ) {
 2139        for (dock, data) in [
 2140            (&self.left_dock, docks.left),
 2141            (&self.bottom_dock, docks.bottom),
 2142            (&self.right_dock, docks.right),
 2143        ] {
 2144            dock.update(cx, |dock, cx| {
 2145                dock.serialized_dock = Some(data);
 2146                dock.restore_state(window, cx);
 2147            });
 2148        }
 2149    }
 2150
 2151    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2152        self.items(cx)
 2153            .filter_map(|item| {
 2154                let project_path = item.project_path(cx)?;
 2155                self.project.read(cx).absolute_path(&project_path, cx)
 2156            })
 2157            .collect()
 2158    }
 2159
 2160    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2161        match position {
 2162            DockPosition::Left => &self.left_dock,
 2163            DockPosition::Bottom => &self.bottom_dock,
 2164            DockPosition::Right => &self.right_dock,
 2165        }
 2166    }
 2167
 2168    pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
 2169        self.all_docks().into_iter().find_map(|dock| {
 2170            let dock = dock.read(cx);
 2171            dock.has_agent_panel(cx).then_some(dock.position())
 2172        })
 2173    }
 2174
 2175    pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
 2176        self.all_docks().into_iter().find_map(|dock| {
 2177            let dock = dock.read(cx);
 2178            let panel = dock.panel::<T>()?;
 2179            dock.stored_panel_size_state(&panel)
 2180        })
 2181    }
 2182
 2183    pub fn persisted_panel_size_state(
 2184        &self,
 2185        panel_key: &'static str,
 2186        cx: &App,
 2187    ) -> Option<dock::PanelSizeState> {
 2188        dock::Dock::load_persisted_size_state(self, panel_key, cx)
 2189    }
 2190
 2191    pub fn persist_panel_size_state(
 2192        &self,
 2193        panel_key: &str,
 2194        size_state: dock::PanelSizeState,
 2195        cx: &mut App,
 2196    ) {
 2197        let Some(workspace_id) = self
 2198            .database_id()
 2199            .map(|id| i64::from(id).to_string())
 2200            .or(self.session_id())
 2201        else {
 2202            return;
 2203        };
 2204
 2205        let kvp = db::kvp::KeyValueStore::global(cx);
 2206        let panel_key = panel_key.to_string();
 2207        cx.background_spawn(async move {
 2208            let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
 2209            scope
 2210                .write(
 2211                    format!("{workspace_id}:{panel_key}"),
 2212                    serde_json::to_string(&size_state)?,
 2213                )
 2214                .await
 2215        })
 2216        .detach_and_log_err(cx);
 2217    }
 2218
 2219    pub fn set_panel_size_state<T: Panel>(
 2220        &mut self,
 2221        size_state: dock::PanelSizeState,
 2222        window: &mut Window,
 2223        cx: &mut Context<Self>,
 2224    ) -> bool {
 2225        let Some(panel) = self.panel::<T>(cx) else {
 2226            return false;
 2227        };
 2228
 2229        let dock = self.dock_at_position(panel.position(window, cx));
 2230        let did_set = dock.update(cx, |dock, cx| {
 2231            dock.set_panel_size_state(&panel, size_state, cx)
 2232        });
 2233
 2234        if did_set {
 2235            self.persist_panel_size_state(T::panel_key(), size_state, cx);
 2236        }
 2237
 2238        did_set
 2239    }
 2240
 2241    pub fn toggle_dock_panel_flexible_size(
 2242        &self,
 2243        dock: &Entity<Dock>,
 2244        panel: &dyn PanelHandle,
 2245        window: &mut Window,
 2246        cx: &mut App,
 2247    ) {
 2248        let position = dock.read(cx).position();
 2249        let current_size = self.dock_size(&dock.read(cx), window, cx);
 2250        let current_flex =
 2251            current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
 2252        dock.update(cx, |dock, cx| {
 2253            dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
 2254        });
 2255    }
 2256
 2257    fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
 2258        let panel = dock.active_panel()?;
 2259        let size_state = dock
 2260            .stored_panel_size_state(panel.as_ref())
 2261            .unwrap_or_default();
 2262        let position = dock.position();
 2263
 2264        let use_flex = panel.has_flexible_size(window, cx);
 2265
 2266        if position.axis() == Axis::Horizontal
 2267            && use_flex
 2268            && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
 2269        {
 2270            let workspace_width = self.bounds.size.width;
 2271            if workspace_width <= Pixels::ZERO {
 2272                return None;
 2273            }
 2274            let flex = flex.max(0.001);
 2275            let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2276            if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2277                // Both docks are flex items sharing the full workspace width.
 2278                let total_flex = flex + 1.0 + opposite_flex;
 2279                return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
 2280            } else {
 2281                // Opposite dock is fixed-width; flex items share (W - fixed).
 2282                let opposite_fixed = opposite
 2283                    .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2284                    .unwrap_or_default();
 2285                let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
 2286                return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
 2287            }
 2288        }
 2289
 2290        Some(
 2291            size_state
 2292                .size
 2293                .unwrap_or_else(|| panel.default_size(window, cx)),
 2294        )
 2295    }
 2296
 2297    pub fn dock_flex_for_size(
 2298        &self,
 2299        position: DockPosition,
 2300        size: Pixels,
 2301        window: &Window,
 2302        cx: &App,
 2303    ) -> Option<f32> {
 2304        if position.axis() != Axis::Horizontal {
 2305            return None;
 2306        }
 2307
 2308        let workspace_width = self.bounds.size.width;
 2309        if workspace_width <= Pixels::ZERO {
 2310            return None;
 2311        }
 2312
 2313        let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2314        if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2315            let size = size.clamp(px(0.), workspace_width - px(1.));
 2316            Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
 2317        } else {
 2318            let opposite_width = opposite
 2319                .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2320                .unwrap_or_default();
 2321            let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
 2322            let remaining = (available - size).max(px(1.));
 2323            Some((size / remaining).max(0.0))
 2324        }
 2325    }
 2326
 2327    fn opposite_dock_panel_and_size_state(
 2328        &self,
 2329        position: DockPosition,
 2330        window: &Window,
 2331        cx: &App,
 2332    ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
 2333        let opposite_position = match position {
 2334            DockPosition::Left => DockPosition::Right,
 2335            DockPosition::Right => DockPosition::Left,
 2336            DockPosition::Bottom => return None,
 2337        };
 2338
 2339        let opposite_dock = self.dock_at_position(opposite_position).read(cx);
 2340        let panel = opposite_dock.visible_panel()?;
 2341        let mut size_state = opposite_dock
 2342            .stored_panel_size_state(panel.as_ref())
 2343            .unwrap_or_default();
 2344        if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
 2345            size_state.flex = self.default_dock_flex(opposite_position);
 2346        }
 2347        Some((panel.clone(), size_state))
 2348    }
 2349
 2350    pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
 2351        if position.axis() != Axis::Horizontal {
 2352            return None;
 2353        }
 2354
 2355        let pane = self.last_active_center_pane.clone()?.upgrade()?;
 2356        Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
 2357    }
 2358
 2359    pub fn is_edited(&self) -> bool {
 2360        self.window_edited
 2361    }
 2362
 2363    pub fn add_panel<T: Panel>(
 2364        &mut self,
 2365        panel: Entity<T>,
 2366        window: &mut Window,
 2367        cx: &mut Context<Self>,
 2368    ) {
 2369        let focus_handle = panel.panel_focus_handle(cx);
 2370        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2371            .detach();
 2372
 2373        let dock_position = panel.position(window, cx);
 2374        let dock = self.dock_at_position(dock_position);
 2375        let any_panel = panel.to_any();
 2376        let persisted_size_state =
 2377            self.persisted_panel_size_state(T::panel_key(), cx)
 2378                .or_else(|| {
 2379                    load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
 2380                        let state = dock::PanelSizeState {
 2381                            size: Some(size),
 2382                            flex: None,
 2383                        };
 2384                        self.persist_panel_size_state(T::panel_key(), state, cx);
 2385                        state
 2386                    })
 2387                });
 2388
 2389        dock.update(cx, |dock, cx| {
 2390            let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
 2391            if let Some(size_state) = persisted_size_state {
 2392                dock.set_panel_size_state(&panel, size_state, cx);
 2393            }
 2394            index
 2395        });
 2396
 2397        cx.emit(Event::PanelAdded(any_panel));
 2398    }
 2399
 2400    pub fn remove_panel<T: Panel>(
 2401        &mut self,
 2402        panel: &Entity<T>,
 2403        window: &mut Window,
 2404        cx: &mut Context<Self>,
 2405    ) {
 2406        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2407            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2408        }
 2409    }
 2410
 2411    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2412        &self.status_bar
 2413    }
 2414
 2415    pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
 2416        self.sidebar_focus_handle = handle;
 2417    }
 2418
 2419    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2420        StatusBarSettings::get_global(cx).show
 2421    }
 2422
 2423    pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
 2424        self.multi_workspace.as_ref()
 2425    }
 2426
 2427    pub fn set_multi_workspace(
 2428        &mut self,
 2429        multi_workspace: WeakEntity<MultiWorkspace>,
 2430        cx: &mut App,
 2431    ) {
 2432        self.status_bar.update(cx, |status_bar, cx| {
 2433            status_bar.set_multi_workspace(multi_workspace.clone(), cx);
 2434        });
 2435        self.multi_workspace = Some(multi_workspace);
 2436    }
 2437
 2438    pub fn app_state(&self) -> &Arc<AppState> {
 2439        &self.app_state
 2440    }
 2441
 2442    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2443        self._panels_task = Some(task);
 2444    }
 2445
 2446    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2447        self._panels_task.take()
 2448    }
 2449
 2450    pub fn user_store(&self) -> &Entity<UserStore> {
 2451        &self.app_state.user_store
 2452    }
 2453
 2454    pub fn project(&self) -> &Entity<Project> {
 2455        &self.project
 2456    }
 2457
 2458    pub fn path_style(&self, cx: &App) -> PathStyle {
 2459        self.project.read(cx).path_style(cx)
 2460    }
 2461
 2462    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2463        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2464
 2465        for pane_handle in &self.panes {
 2466            let pane = pane_handle.read(cx);
 2467
 2468            for entry in pane.activation_history() {
 2469                history.insert(
 2470                    entry.entity_id,
 2471                    history
 2472                        .get(&entry.entity_id)
 2473                        .cloned()
 2474                        .unwrap_or(0)
 2475                        .max(entry.timestamp),
 2476                );
 2477            }
 2478        }
 2479
 2480        history
 2481    }
 2482
 2483    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2484        let mut recent_item: Option<Entity<T>> = None;
 2485        let mut recent_timestamp = 0;
 2486        for pane_handle in &self.panes {
 2487            let pane = pane_handle.read(cx);
 2488            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2489                pane.items().map(|item| (item.item_id(), item)).collect();
 2490            for entry in pane.activation_history() {
 2491                if entry.timestamp > recent_timestamp
 2492                    && let Some(&item) = item_map.get(&entry.entity_id)
 2493                    && let Some(typed_item) = item.act_as::<T>(cx)
 2494                {
 2495                    recent_timestamp = entry.timestamp;
 2496                    recent_item = Some(typed_item);
 2497                }
 2498            }
 2499        }
 2500        recent_item
 2501    }
 2502
 2503    pub fn recent_navigation_history_iter(
 2504        &self,
 2505        cx: &App,
 2506    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2507        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2508        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2509
 2510        for pane in &self.panes {
 2511            let pane = pane.read(cx);
 2512
 2513            pane.nav_history()
 2514                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2515                    if let Some(fs_path) = &fs_path {
 2516                        abs_paths_opened
 2517                            .entry(fs_path.clone())
 2518                            .or_default()
 2519                            .insert(project_path.clone());
 2520                    }
 2521                    let timestamp = entry.timestamp;
 2522                    match history.entry(project_path) {
 2523                        hash_map::Entry::Occupied(mut entry) => {
 2524                            let (_, old_timestamp) = entry.get();
 2525                            if &timestamp > old_timestamp {
 2526                                entry.insert((fs_path, timestamp));
 2527                            }
 2528                        }
 2529                        hash_map::Entry::Vacant(entry) => {
 2530                            entry.insert((fs_path, timestamp));
 2531                        }
 2532                    }
 2533                });
 2534
 2535            if let Some(item) = pane.active_item()
 2536                && let Some(project_path) = item.project_path(cx)
 2537            {
 2538                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2539
 2540                if let Some(fs_path) = &fs_path {
 2541                    abs_paths_opened
 2542                        .entry(fs_path.clone())
 2543                        .or_default()
 2544                        .insert(project_path.clone());
 2545                }
 2546
 2547                history.insert(project_path, (fs_path, std::usize::MAX));
 2548            }
 2549        }
 2550
 2551        history
 2552            .into_iter()
 2553            .sorted_by_key(|(_, (_, order))| *order)
 2554            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2555            .rev()
 2556            .filter(move |(history_path, abs_path)| {
 2557                let latest_project_path_opened = abs_path
 2558                    .as_ref()
 2559                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2560                    .and_then(|project_paths| {
 2561                        project_paths
 2562                            .iter()
 2563                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2564                    });
 2565
 2566                latest_project_path_opened.is_none_or(|path| path == history_path)
 2567            })
 2568    }
 2569
 2570    pub fn recent_navigation_history(
 2571        &self,
 2572        limit: Option<usize>,
 2573        cx: &App,
 2574    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2575        self.recent_navigation_history_iter(cx)
 2576            .take(limit.unwrap_or(usize::MAX))
 2577            .collect()
 2578    }
 2579
 2580    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2581        for pane in &self.panes {
 2582            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2583        }
 2584    }
 2585
 2586    fn navigate_history(
 2587        &mut self,
 2588        pane: WeakEntity<Pane>,
 2589        mode: NavigationMode,
 2590        window: &mut Window,
 2591        cx: &mut Context<Workspace>,
 2592    ) -> Task<Result<()>> {
 2593        self.navigate_history_impl(
 2594            pane,
 2595            mode,
 2596            window,
 2597            &mut |history, cx| history.pop(mode, cx),
 2598            cx,
 2599        )
 2600    }
 2601
 2602    fn navigate_tag_history(
 2603        &mut self,
 2604        pane: WeakEntity<Pane>,
 2605        mode: TagNavigationMode,
 2606        window: &mut Window,
 2607        cx: &mut Context<Workspace>,
 2608    ) -> Task<Result<()>> {
 2609        self.navigate_history_impl(
 2610            pane,
 2611            NavigationMode::Normal,
 2612            window,
 2613            &mut |history, _cx| history.pop_tag(mode),
 2614            cx,
 2615        )
 2616    }
 2617
 2618    fn navigate_history_impl(
 2619        &mut self,
 2620        pane: WeakEntity<Pane>,
 2621        mode: NavigationMode,
 2622        window: &mut Window,
 2623        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2624        cx: &mut Context<Workspace>,
 2625    ) -> Task<Result<()>> {
 2626        let to_load = if let Some(pane) = pane.upgrade() {
 2627            pane.update(cx, |pane, cx| {
 2628                window.focus(&pane.focus_handle(cx), cx);
 2629                loop {
 2630                    // Retrieve the weak item handle from the history.
 2631                    let entry = cb(pane.nav_history_mut(), cx)?;
 2632
 2633                    // If the item is still present in this pane, then activate it.
 2634                    if let Some(index) = entry
 2635                        .item
 2636                        .upgrade()
 2637                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2638                    {
 2639                        let prev_active_item_index = pane.active_item_index();
 2640                        pane.nav_history_mut().set_mode(mode);
 2641                        pane.activate_item(index, true, true, window, cx);
 2642                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2643
 2644                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2645                        if let Some(data) = entry.data {
 2646                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2647                        }
 2648
 2649                        if navigated {
 2650                            break None;
 2651                        }
 2652                    } else {
 2653                        // If the item is no longer present in this pane, then retrieve its
 2654                        // path info in order to reopen it.
 2655                        break pane
 2656                            .nav_history()
 2657                            .path_for_item(entry.item.id())
 2658                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2659                    }
 2660                }
 2661            })
 2662        } else {
 2663            None
 2664        };
 2665
 2666        if let Some((project_path, abs_path, entry)) = to_load {
 2667            // If the item was no longer present, then load it again from its previous path, first try the local path
 2668            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2669
 2670            cx.spawn_in(window, async move  |workspace, cx| {
 2671                let open_by_project_path = open_by_project_path.await;
 2672                let mut navigated = false;
 2673                match open_by_project_path
 2674                    .with_context(|| format!("Navigating to {project_path:?}"))
 2675                {
 2676                    Ok((project_entry_id, build_item)) => {
 2677                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2678                            pane.nav_history_mut().set_mode(mode);
 2679                            pane.active_item().map(|p| p.item_id())
 2680                        })?;
 2681
 2682                        pane.update_in(cx, |pane, window, cx| {
 2683                            let item = pane.open_item(
 2684                                project_entry_id,
 2685                                project_path,
 2686                                true,
 2687                                entry.is_preview,
 2688                                true,
 2689                                None,
 2690                                window, cx,
 2691                                build_item,
 2692                            );
 2693                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2694                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2695                            if let Some(data) = entry.data {
 2696                                navigated |= item.navigate(data, window, cx);
 2697                            }
 2698                        })?;
 2699                    }
 2700                    Err(open_by_project_path_e) => {
 2701                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2702                        // and its worktree is now dropped
 2703                        if let Some(abs_path) = abs_path {
 2704                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2705                                pane.nav_history_mut().set_mode(mode);
 2706                                pane.active_item().map(|p| p.item_id())
 2707                            })?;
 2708                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2709                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2710                            })?;
 2711                            match open_by_abs_path
 2712                                .await
 2713                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2714                            {
 2715                                Ok(item) => {
 2716                                    pane.update_in(cx, |pane, window, cx| {
 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_abs_path_e) => {
 2725                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2726                                }
 2727                            }
 2728                        }
 2729                    }
 2730                }
 2731
 2732                if !navigated {
 2733                    workspace
 2734                        .update_in(cx, |workspace, window, cx| {
 2735                            Self::navigate_history(workspace, pane, mode, window, cx)
 2736                        })?
 2737                        .await?;
 2738                }
 2739
 2740                Ok(())
 2741            })
 2742        } else {
 2743            Task::ready(Ok(()))
 2744        }
 2745    }
 2746
 2747    pub fn go_back(
 2748        &mut self,
 2749        pane: WeakEntity<Pane>,
 2750        window: &mut Window,
 2751        cx: &mut Context<Workspace>,
 2752    ) -> Task<Result<()>> {
 2753        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2754    }
 2755
 2756    pub fn go_forward(
 2757        &mut self,
 2758        pane: WeakEntity<Pane>,
 2759        window: &mut Window,
 2760        cx: &mut Context<Workspace>,
 2761    ) -> Task<Result<()>> {
 2762        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2763    }
 2764
 2765    pub fn reopen_closed_item(
 2766        &mut self,
 2767        window: &mut Window,
 2768        cx: &mut Context<Workspace>,
 2769    ) -> Task<Result<()>> {
 2770        self.navigate_history(
 2771            self.active_pane().downgrade(),
 2772            NavigationMode::ReopeningClosedItem,
 2773            window,
 2774            cx,
 2775        )
 2776    }
 2777
 2778    pub fn client(&self) -> &Arc<Client> {
 2779        &self.app_state.client
 2780    }
 2781
 2782    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2783        self.titlebar_item = Some(item);
 2784        cx.notify();
 2785    }
 2786
 2787    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2788        self.on_prompt_for_new_path = Some(prompt)
 2789    }
 2790
 2791    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2792        self.on_prompt_for_open_path = Some(prompt)
 2793    }
 2794
 2795    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2796        self.terminal_provider = Some(Box::new(provider));
 2797    }
 2798
 2799    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2800        self.debugger_provider = Some(Arc::new(provider));
 2801    }
 2802
 2803    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2804        self.debugger_provider.clone()
 2805    }
 2806
 2807    pub fn prompt_for_open_path(
 2808        &mut self,
 2809        path_prompt_options: PathPromptOptions,
 2810        lister: DirectoryLister,
 2811        window: &mut Window,
 2812        cx: &mut Context<Self>,
 2813    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2814        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2815            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2816            let rx = prompt(self, lister, window, cx);
 2817            self.on_prompt_for_open_path = Some(prompt);
 2818            rx
 2819        } else {
 2820            let (tx, rx) = oneshot::channel();
 2821            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2822
 2823            cx.spawn_in(window, async move |workspace, cx| {
 2824                let Ok(result) = abs_path.await else {
 2825                    return Ok(());
 2826                };
 2827
 2828                match result {
 2829                    Ok(result) => {
 2830                        tx.send(result).ok();
 2831                    }
 2832                    Err(err) => {
 2833                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2834                            workspace.show_portal_error(err.to_string(), cx);
 2835                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2836                            let rx = prompt(workspace, lister, window, cx);
 2837                            workspace.on_prompt_for_open_path = Some(prompt);
 2838                            rx
 2839                        })?;
 2840                        if let Ok(path) = rx.await {
 2841                            tx.send(path).ok();
 2842                        }
 2843                    }
 2844                };
 2845                anyhow::Ok(())
 2846            })
 2847            .detach();
 2848
 2849            rx
 2850        }
 2851    }
 2852
 2853    pub fn prompt_for_new_path(
 2854        &mut self,
 2855        lister: DirectoryLister,
 2856        suggested_name: Option<String>,
 2857        window: &mut Window,
 2858        cx: &mut Context<Self>,
 2859    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2860        if self.project.read(cx).is_via_collab()
 2861            || self.project.read(cx).is_via_remote_server()
 2862            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2863        {
 2864            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2865            let rx = prompt(self, lister, suggested_name, window, cx);
 2866            self.on_prompt_for_new_path = Some(prompt);
 2867            return rx;
 2868        }
 2869
 2870        let (tx, rx) = oneshot::channel();
 2871        cx.spawn_in(window, async move |workspace, cx| {
 2872            let abs_path = workspace.update(cx, |workspace, cx| {
 2873                let relative_to = workspace
 2874                    .most_recent_active_path(cx)
 2875                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2876                    .or_else(|| {
 2877                        let project = workspace.project.read(cx);
 2878                        project.visible_worktrees(cx).find_map(|worktree| {
 2879                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2880                        })
 2881                    })
 2882                    .or_else(std::env::home_dir)
 2883                    .unwrap_or_else(|| PathBuf::from(""));
 2884                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2885            })?;
 2886            let abs_path = match abs_path.await? {
 2887                Ok(path) => path,
 2888                Err(err) => {
 2889                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2890                        workspace.show_portal_error(err.to_string(), cx);
 2891
 2892                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2893                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2894                        workspace.on_prompt_for_new_path = Some(prompt);
 2895                        rx
 2896                    })?;
 2897                    if let Ok(path) = rx.await {
 2898                        tx.send(path).ok();
 2899                    }
 2900                    return anyhow::Ok(());
 2901                }
 2902            };
 2903
 2904            tx.send(abs_path.map(|path| vec![path])).ok();
 2905            anyhow::Ok(())
 2906        })
 2907        .detach();
 2908
 2909        rx
 2910    }
 2911
 2912    pub fn titlebar_item(&self) -> Option<AnyView> {
 2913        self.titlebar_item.clone()
 2914    }
 2915
 2916    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2917    /// When set, git-related operations should use this worktree instead of deriving
 2918    /// the active worktree from the focused file.
 2919    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2920        self.active_worktree_override
 2921    }
 2922
 2923    pub fn set_active_worktree_override(
 2924        &mut self,
 2925        worktree_id: Option<WorktreeId>,
 2926        cx: &mut Context<Self>,
 2927    ) {
 2928        self.active_worktree_override = worktree_id;
 2929        cx.notify();
 2930    }
 2931
 2932    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2933        self.active_worktree_override = None;
 2934        cx.notify();
 2935    }
 2936
 2937    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2938    ///
 2939    /// If the given workspace has a local project, then it will be passed
 2940    /// to the callback. Otherwise, a new empty window will be created.
 2941    pub fn with_local_workspace<T, F>(
 2942        &mut self,
 2943        window: &mut Window,
 2944        cx: &mut Context<Self>,
 2945        callback: F,
 2946    ) -> Task<Result<T>>
 2947    where
 2948        T: 'static,
 2949        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2950    {
 2951        if self.project.read(cx).is_local() {
 2952            Task::ready(Ok(callback(self, window, cx)))
 2953        } else {
 2954            let env = self.project.read(cx).cli_environment(cx);
 2955            let task = Self::new_local(
 2956                Vec::new(),
 2957                self.app_state.clone(),
 2958                None,
 2959                env,
 2960                None,
 2961                OpenMode::Activate,
 2962                cx,
 2963            );
 2964            cx.spawn_in(window, async move |_vh, cx| {
 2965                let OpenResult {
 2966                    window: multi_workspace_window,
 2967                    ..
 2968                } = task.await?;
 2969                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2970                    let workspace = multi_workspace.workspace().clone();
 2971                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2972                })
 2973            })
 2974        }
 2975    }
 2976
 2977    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2978    ///
 2979    /// If the given workspace has a local project, then it will be passed
 2980    /// to the callback. Otherwise, a new empty window will be created.
 2981    pub fn with_local_or_wsl_workspace<T, F>(
 2982        &mut self,
 2983        window: &mut Window,
 2984        cx: &mut Context<Self>,
 2985        callback: F,
 2986    ) -> Task<Result<T>>
 2987    where
 2988        T: 'static,
 2989        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2990    {
 2991        let project = self.project.read(cx);
 2992        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 2993            Task::ready(Ok(callback(self, window, cx)))
 2994        } else {
 2995            let env = self.project.read(cx).cli_environment(cx);
 2996            let task = Self::new_local(
 2997                Vec::new(),
 2998                self.app_state.clone(),
 2999                None,
 3000                env,
 3001                None,
 3002                OpenMode::Activate,
 3003                cx,
 3004            );
 3005            cx.spawn_in(window, async move |_vh, cx| {
 3006                let OpenResult {
 3007                    window: multi_workspace_window,
 3008                    ..
 3009                } = task.await?;
 3010                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 3011                    let workspace = multi_workspace.workspace().clone();
 3012                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 3013                })
 3014            })
 3015        }
 3016    }
 3017
 3018    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3019        self.project.read(cx).worktrees(cx)
 3020    }
 3021
 3022    pub fn visible_worktrees<'a>(
 3023        &self,
 3024        cx: &'a App,
 3025    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3026        self.project.read(cx).visible_worktrees(cx)
 3027    }
 3028
 3029    #[cfg(any(test, feature = "test-support"))]
 3030    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 3031        let futures = self
 3032            .worktrees(cx)
 3033            .filter_map(|worktree| worktree.read(cx).as_local())
 3034            .map(|worktree| worktree.scan_complete())
 3035            .collect::<Vec<_>>();
 3036        async move {
 3037            for future in futures {
 3038                future.await;
 3039            }
 3040        }
 3041    }
 3042
 3043    pub fn close_global(cx: &mut App) {
 3044        cx.defer(|cx| {
 3045            cx.windows().iter().find(|window| {
 3046                window
 3047                    .update(cx, |_, window, _| {
 3048                        if window.is_window_active() {
 3049                            //This can only get called when the window's project connection has been lost
 3050                            //so we don't need to prompt the user for anything and instead just close the window
 3051                            window.remove_window();
 3052                            true
 3053                        } else {
 3054                            false
 3055                        }
 3056                    })
 3057                    .unwrap_or(false)
 3058            });
 3059        });
 3060    }
 3061
 3062    pub fn move_focused_panel_to_next_position(
 3063        &mut self,
 3064        _: &MoveFocusedPanelToNextPosition,
 3065        window: &mut Window,
 3066        cx: &mut Context<Self>,
 3067    ) {
 3068        let docks = self.all_docks();
 3069        let active_dock = docks
 3070            .into_iter()
 3071            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 3072
 3073        if let Some(dock) = active_dock {
 3074            dock.update(cx, |dock, cx| {
 3075                let active_panel = dock
 3076                    .active_panel()
 3077                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 3078
 3079                if let Some(panel) = active_panel {
 3080                    panel.move_to_next_position(window, cx);
 3081                }
 3082            })
 3083        }
 3084    }
 3085
 3086    pub fn prepare_to_close(
 3087        &mut self,
 3088        close_intent: CloseIntent,
 3089        window: &mut Window,
 3090        cx: &mut Context<Self>,
 3091    ) -> Task<Result<bool>> {
 3092        let active_call = self.active_global_call();
 3093
 3094        cx.spawn_in(window, async move |this, cx| {
 3095            this.update(cx, |this, _| {
 3096                if close_intent == CloseIntent::CloseWindow {
 3097                    this.removing = true;
 3098                }
 3099            })?;
 3100
 3101            let workspace_count = cx.update(|_window, cx| {
 3102                cx.windows()
 3103                    .iter()
 3104                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 3105                    .count()
 3106            })?;
 3107
 3108            #[cfg(target_os = "macos")]
 3109            let save_last_workspace = false;
 3110
 3111            // On Linux and Windows, closing the last window should restore the last workspace.
 3112            #[cfg(not(target_os = "macos"))]
 3113            let save_last_workspace = {
 3114                let remaining_workspaces = cx.update(|_window, cx| {
 3115                    cx.windows()
 3116                        .iter()
 3117                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 3118                        .filter_map(|multi_workspace| {
 3119                            multi_workspace
 3120                                .update(cx, |multi_workspace, _, cx| {
 3121                                    multi_workspace.workspace().read(cx).removing
 3122                                })
 3123                                .ok()
 3124                        })
 3125                        .filter(|removing| !removing)
 3126                        .count()
 3127                })?;
 3128
 3129                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 3130            };
 3131
 3132            if let Some(active_call) = active_call
 3133                && workspace_count == 1
 3134                && cx
 3135                    .update(|_window, cx| active_call.0.is_in_room(cx))
 3136                    .unwrap_or(false)
 3137            {
 3138                if close_intent == CloseIntent::CloseWindow {
 3139                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3140                    let answer = cx.update(|window, cx| {
 3141                        window.prompt(
 3142                            PromptLevel::Warning,
 3143                            "Do you want to leave the current call?",
 3144                            None,
 3145                            &["Close window and hang up", "Cancel"],
 3146                            cx,
 3147                        )
 3148                    })?;
 3149
 3150                    if answer.await.log_err() == Some(1) {
 3151                        return anyhow::Ok(false);
 3152                    } else {
 3153                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 3154                            task.await.log_err();
 3155                        }
 3156                    }
 3157                }
 3158                if close_intent == CloseIntent::ReplaceWindow {
 3159                    _ = cx.update(|_window, cx| {
 3160                        let multi_workspace = cx
 3161                            .windows()
 3162                            .iter()
 3163                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 3164                            .next()
 3165                            .unwrap();
 3166                        let project = multi_workspace
 3167                            .read(cx)?
 3168                            .workspace()
 3169                            .read(cx)
 3170                            .project
 3171                            .clone();
 3172                        if project.read(cx).is_shared() {
 3173                            active_call.0.unshare_project(project, cx)?;
 3174                        }
 3175                        Ok::<_, anyhow::Error>(())
 3176                    });
 3177                }
 3178            }
 3179
 3180            let save_result = this
 3181                .update_in(cx, |this, window, cx| {
 3182                    this.save_all_internal(SaveIntent::Close, window, cx)
 3183                })?
 3184                .await;
 3185
 3186            // If we're not quitting, but closing, we remove the workspace from
 3187            // the current session.
 3188            if close_intent != CloseIntent::Quit
 3189                && !save_last_workspace
 3190                && save_result.as_ref().is_ok_and(|&res| res)
 3191            {
 3192                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 3193                    .await;
 3194            }
 3195
 3196            save_result
 3197        })
 3198    }
 3199
 3200    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 3201        self.save_all_internal(
 3202            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 3203            window,
 3204            cx,
 3205        )
 3206        .detach_and_log_err(cx);
 3207    }
 3208
 3209    fn send_keystrokes(
 3210        &mut self,
 3211        action: &SendKeystrokes,
 3212        window: &mut Window,
 3213        cx: &mut Context<Self>,
 3214    ) {
 3215        let keystrokes: Vec<Keystroke> = action
 3216            .0
 3217            .split(' ')
 3218            .flat_map(|k| Keystroke::parse(k).log_err())
 3219            .map(|k| {
 3220                cx.keyboard_mapper()
 3221                    .map_key_equivalent(k, false)
 3222                    .inner()
 3223                    .clone()
 3224            })
 3225            .collect();
 3226        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 3227    }
 3228
 3229    pub fn send_keystrokes_impl(
 3230        &mut self,
 3231        keystrokes: Vec<Keystroke>,
 3232        window: &mut Window,
 3233        cx: &mut Context<Self>,
 3234    ) -> Shared<Task<()>> {
 3235        let mut state = self.dispatching_keystrokes.borrow_mut();
 3236        if !state.dispatched.insert(keystrokes.clone()) {
 3237            cx.propagate();
 3238            return state.task.clone().unwrap();
 3239        }
 3240
 3241        state.queue.extend(keystrokes);
 3242
 3243        let keystrokes = self.dispatching_keystrokes.clone();
 3244        if state.task.is_none() {
 3245            state.task = Some(
 3246                window
 3247                    .spawn(cx, async move |cx| {
 3248                        // limit to 100 keystrokes to avoid infinite recursion.
 3249                        for _ in 0..100 {
 3250                            let keystroke = {
 3251                                let mut state = keystrokes.borrow_mut();
 3252                                let Some(keystroke) = state.queue.pop_front() else {
 3253                                    state.dispatched.clear();
 3254                                    state.task.take();
 3255                                    return;
 3256                                };
 3257                                keystroke
 3258                            };
 3259                            cx.update(|window, cx| {
 3260                                let focused = window.focused(cx);
 3261                                window.dispatch_keystroke(keystroke.clone(), cx);
 3262                                if window.focused(cx) != focused {
 3263                                    // dispatch_keystroke may cause the focus to change.
 3264                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3265                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 3266                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 3267                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3268                                    // )
 3269                                    window.draw(cx).clear();
 3270                                }
 3271                            })
 3272                            .ok();
 3273
 3274                            // Yield between synthetic keystrokes so deferred focus and
 3275                            // other effects can settle before dispatching the next key.
 3276                            yield_now().await;
 3277                        }
 3278
 3279                        *keystrokes.borrow_mut() = Default::default();
 3280                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3281                    })
 3282                    .shared(),
 3283            );
 3284        }
 3285        state.task.clone().unwrap()
 3286    }
 3287
 3288    fn save_all_internal(
 3289        &mut self,
 3290        mut save_intent: SaveIntent,
 3291        window: &mut Window,
 3292        cx: &mut Context<Self>,
 3293    ) -> Task<Result<bool>> {
 3294        if self.project.read(cx).is_disconnected(cx) {
 3295            return Task::ready(Ok(true));
 3296        }
 3297        let dirty_items = self
 3298            .panes
 3299            .iter()
 3300            .flat_map(|pane| {
 3301                pane.read(cx).items().filter_map(|item| {
 3302                    if item.is_dirty(cx) {
 3303                        item.tab_content_text(0, cx);
 3304                        Some((pane.downgrade(), item.boxed_clone()))
 3305                    } else {
 3306                        None
 3307                    }
 3308                })
 3309            })
 3310            .collect::<Vec<_>>();
 3311
 3312        let project = self.project.clone();
 3313        cx.spawn_in(window, async move |workspace, cx| {
 3314            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3315                let (serialize_tasks, remaining_dirty_items) =
 3316                    workspace.update_in(cx, |workspace, window, cx| {
 3317                        let mut remaining_dirty_items = Vec::new();
 3318                        let mut serialize_tasks = Vec::new();
 3319                        for (pane, item) in dirty_items {
 3320                            if let Some(task) = item
 3321                                .to_serializable_item_handle(cx)
 3322                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3323                            {
 3324                                serialize_tasks.push(task);
 3325                            } else {
 3326                                remaining_dirty_items.push((pane, item));
 3327                            }
 3328                        }
 3329                        (serialize_tasks, remaining_dirty_items)
 3330                    })?;
 3331
 3332                futures::future::try_join_all(serialize_tasks).await?;
 3333
 3334                if !remaining_dirty_items.is_empty() {
 3335                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3336                }
 3337
 3338                if remaining_dirty_items.len() > 1 {
 3339                    let answer = workspace.update_in(cx, |_, window, cx| {
 3340                        let detail = Pane::file_names_for_prompt(
 3341                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3342                            cx,
 3343                        );
 3344                        window.prompt(
 3345                            PromptLevel::Warning,
 3346                            "Do you want to save all changes in the following files?",
 3347                            Some(&detail),
 3348                            &["Save all", "Discard all", "Cancel"],
 3349                            cx,
 3350                        )
 3351                    })?;
 3352                    match answer.await.log_err() {
 3353                        Some(0) => save_intent = SaveIntent::SaveAll,
 3354                        Some(1) => save_intent = SaveIntent::Skip,
 3355                        Some(2) => return Ok(false),
 3356                        _ => {}
 3357                    }
 3358                }
 3359
 3360                remaining_dirty_items
 3361            } else {
 3362                dirty_items
 3363            };
 3364
 3365            for (pane, item) in dirty_items {
 3366                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3367                    (
 3368                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3369                        item.project_entry_ids(cx),
 3370                    )
 3371                })?;
 3372                if (singleton || !project_entry_ids.is_empty())
 3373                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3374                {
 3375                    return Ok(false);
 3376                }
 3377            }
 3378            Ok(true)
 3379        })
 3380    }
 3381
 3382    pub fn open_workspace_for_paths(
 3383        &mut self,
 3384        // replace_current_window: bool,
 3385        mut open_mode: OpenMode,
 3386        paths: Vec<PathBuf>,
 3387        window: &mut Window,
 3388        cx: &mut Context<Self>,
 3389    ) -> Task<Result<Entity<Workspace>>> {
 3390        let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
 3391        let is_remote = self.project.read(cx).is_via_collab();
 3392        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3393        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3394
 3395        let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
 3396        if workspace_is_empty {
 3397            open_mode = OpenMode::Replace;
 3398        }
 3399
 3400        let app_state = self.app_state.clone();
 3401
 3402        cx.spawn(async move |_, cx| {
 3403            let OpenResult { workspace, .. } = cx
 3404                .update(|cx| {
 3405                    open_paths(
 3406                        &paths,
 3407                        app_state,
 3408                        OpenOptions {
 3409                            requesting_window,
 3410                            open_mode,
 3411                            ..Default::default()
 3412                        },
 3413                        cx,
 3414                    )
 3415                })
 3416                .await?;
 3417            Ok(workspace)
 3418        })
 3419    }
 3420
 3421    #[allow(clippy::type_complexity)]
 3422    pub fn open_paths(
 3423        &mut self,
 3424        mut abs_paths: Vec<PathBuf>,
 3425        options: OpenOptions,
 3426        pane: Option<WeakEntity<Pane>>,
 3427        window: &mut Window,
 3428        cx: &mut Context<Self>,
 3429    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3430        let fs = self.app_state.fs.clone();
 3431
 3432        let caller_ordered_abs_paths = abs_paths.clone();
 3433
 3434        // Sort the paths to ensure we add worktrees for parents before their children.
 3435        abs_paths.sort_unstable();
 3436        cx.spawn_in(window, async move |this, cx| {
 3437            let mut tasks = Vec::with_capacity(abs_paths.len());
 3438
 3439            for abs_path in &abs_paths {
 3440                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3441                    OpenVisible::All => Some(true),
 3442                    OpenVisible::None => Some(false),
 3443                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3444                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3445                        Some(None) => Some(true),
 3446                        None => None,
 3447                    },
 3448                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3449                        Some(Some(metadata)) => Some(metadata.is_dir),
 3450                        Some(None) => Some(false),
 3451                        None => None,
 3452                    },
 3453                };
 3454                let project_path = match visible {
 3455                    Some(visible) => match this
 3456                        .update(cx, |this, cx| {
 3457                            Workspace::project_path_for_path(
 3458                                this.project.clone(),
 3459                                abs_path,
 3460                                visible,
 3461                                cx,
 3462                            )
 3463                        })
 3464                        .log_err()
 3465                    {
 3466                        Some(project_path) => project_path.await.log_err(),
 3467                        None => None,
 3468                    },
 3469                    None => None,
 3470                };
 3471
 3472                let this = this.clone();
 3473                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3474                let fs = fs.clone();
 3475                let pane = pane.clone();
 3476                let task = cx.spawn(async move |cx| {
 3477                    let (_worktree, project_path) = project_path?;
 3478                    if fs.is_dir(&abs_path).await {
 3479                        // Opening a directory should not race to update the active entry.
 3480                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3481                        None
 3482                    } else {
 3483                        Some(
 3484                            this.update_in(cx, |this, window, cx| {
 3485                                this.open_path(
 3486                                    project_path,
 3487                                    pane,
 3488                                    options.focus.unwrap_or(true),
 3489                                    window,
 3490                                    cx,
 3491                                )
 3492                            })
 3493                            .ok()?
 3494                            .await,
 3495                        )
 3496                    }
 3497                });
 3498                tasks.push(task);
 3499            }
 3500
 3501            let results = futures::future::join_all(tasks).await;
 3502
 3503            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3504            let mut winner: Option<(PathBuf, bool)> = None;
 3505            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3506                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3507                    if !metadata.is_dir {
 3508                        winner = Some((abs_path, false));
 3509                        break;
 3510                    }
 3511                    if winner.is_none() {
 3512                        winner = Some((abs_path, true));
 3513                    }
 3514                } else if winner.is_none() {
 3515                    winner = Some((abs_path, false));
 3516                }
 3517            }
 3518
 3519            // Compute the winner entry id on the foreground thread and emit once, after all
 3520            // paths finish opening. This avoids races between concurrently-opening paths
 3521            // (directories in particular) and makes the resulting project panel selection
 3522            // deterministic.
 3523            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3524                'emit_winner: {
 3525                    let winner_abs_path: Arc<Path> =
 3526                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3527
 3528                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3529                        OpenVisible::All => true,
 3530                        OpenVisible::None => false,
 3531                        OpenVisible::OnlyFiles => !winner_is_dir,
 3532                        OpenVisible::OnlyDirectories => winner_is_dir,
 3533                    };
 3534
 3535                    let Some(worktree_task) = this
 3536                        .update(cx, |workspace, cx| {
 3537                            workspace.project.update(cx, |project, cx| {
 3538                                project.find_or_create_worktree(
 3539                                    winner_abs_path.as_ref(),
 3540                                    visible,
 3541                                    cx,
 3542                                )
 3543                            })
 3544                        })
 3545                        .ok()
 3546                    else {
 3547                        break 'emit_winner;
 3548                    };
 3549
 3550                    let Ok((worktree, _)) = worktree_task.await else {
 3551                        break 'emit_winner;
 3552                    };
 3553
 3554                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3555                        let worktree = worktree.read(cx);
 3556                        let worktree_abs_path = worktree.abs_path();
 3557                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3558                            worktree.root_entry()
 3559                        } else {
 3560                            winner_abs_path
 3561                                .strip_prefix(worktree_abs_path.as_ref())
 3562                                .ok()
 3563                                .and_then(|relative_path| {
 3564                                    let relative_path =
 3565                                        RelPath::new(relative_path, PathStyle::local())
 3566                                            .log_err()?;
 3567                                    worktree.entry_for_path(&relative_path)
 3568                                })
 3569                        }?;
 3570                        Some(entry.id)
 3571                    }) else {
 3572                        break 'emit_winner;
 3573                    };
 3574
 3575                    this.update(cx, |workspace, cx| {
 3576                        workspace.project.update(cx, |_, cx| {
 3577                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3578                        });
 3579                    })
 3580                    .ok();
 3581                }
 3582            }
 3583
 3584            results
 3585        })
 3586    }
 3587
 3588    pub fn open_resolved_path(
 3589        &mut self,
 3590        path: ResolvedPath,
 3591        window: &mut Window,
 3592        cx: &mut Context<Self>,
 3593    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3594        match path {
 3595            ResolvedPath::ProjectPath { project_path, .. } => {
 3596                self.open_path(project_path, None, true, window, cx)
 3597            }
 3598            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3599                PathBuf::from(path),
 3600                OpenOptions {
 3601                    visible: Some(OpenVisible::None),
 3602                    ..Default::default()
 3603                },
 3604                window,
 3605                cx,
 3606            ),
 3607        }
 3608    }
 3609
 3610    pub fn absolute_path_of_worktree(
 3611        &self,
 3612        worktree_id: WorktreeId,
 3613        cx: &mut Context<Self>,
 3614    ) -> Option<PathBuf> {
 3615        self.project
 3616            .read(cx)
 3617            .worktree_for_id(worktree_id, cx)
 3618            // TODO: use `abs_path` or `root_dir`
 3619            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3620    }
 3621
 3622    pub fn add_folder_to_project(
 3623        &mut self,
 3624        _: &AddFolderToProject,
 3625        window: &mut Window,
 3626        cx: &mut Context<Self>,
 3627    ) {
 3628        let project = self.project.read(cx);
 3629        if project.is_via_collab() {
 3630            self.show_error(
 3631                &anyhow!("You cannot add folders to someone else's project"),
 3632                cx,
 3633            );
 3634            return;
 3635        }
 3636        let paths = self.prompt_for_open_path(
 3637            PathPromptOptions {
 3638                files: false,
 3639                directories: true,
 3640                multiple: true,
 3641                prompt: None,
 3642            },
 3643            DirectoryLister::Project(self.project.clone()),
 3644            window,
 3645            cx,
 3646        );
 3647        cx.spawn_in(window, async move |this, cx| {
 3648            if let Some(paths) = paths.await.log_err().flatten() {
 3649                let results = this
 3650                    .update_in(cx, |this, window, cx| {
 3651                        this.open_paths(
 3652                            paths,
 3653                            OpenOptions {
 3654                                visible: Some(OpenVisible::All),
 3655                                ..Default::default()
 3656                            },
 3657                            None,
 3658                            window,
 3659                            cx,
 3660                        )
 3661                    })?
 3662                    .await;
 3663                for result in results.into_iter().flatten() {
 3664                    result.log_err();
 3665                }
 3666            }
 3667            anyhow::Ok(())
 3668        })
 3669        .detach_and_log_err(cx);
 3670    }
 3671
 3672    pub fn project_path_for_path(
 3673        project: Entity<Project>,
 3674        abs_path: &Path,
 3675        visible: bool,
 3676        cx: &mut App,
 3677    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3678        let entry = project.update(cx, |project, cx| {
 3679            project.find_or_create_worktree(abs_path, visible, cx)
 3680        });
 3681        cx.spawn(async move |cx| {
 3682            let (worktree, path) = entry.await?;
 3683            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3684            Ok((worktree, ProjectPath { worktree_id, path }))
 3685        })
 3686    }
 3687
 3688    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3689        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3690    }
 3691
 3692    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3693        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3694    }
 3695
 3696    pub fn items_of_type<'a, T: Item>(
 3697        &'a self,
 3698        cx: &'a App,
 3699    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3700        self.panes
 3701            .iter()
 3702            .flat_map(|pane| pane.read(cx).items_of_type())
 3703    }
 3704
 3705    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3706        self.active_pane().read(cx).active_item()
 3707    }
 3708
 3709    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3710        let item = self.active_item(cx)?;
 3711        item.to_any_view().downcast::<I>().ok()
 3712    }
 3713
 3714    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3715        self.active_item(cx).and_then(|item| item.project_path(cx))
 3716    }
 3717
 3718    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3719        self.recent_navigation_history_iter(cx)
 3720            .filter_map(|(path, abs_path)| {
 3721                let worktree = self
 3722                    .project
 3723                    .read(cx)
 3724                    .worktree_for_id(path.worktree_id, cx)?;
 3725                if worktree.read(cx).is_visible() {
 3726                    abs_path
 3727                } else {
 3728                    None
 3729                }
 3730            })
 3731            .next()
 3732    }
 3733
 3734    pub fn save_active_item(
 3735        &mut self,
 3736        save_intent: SaveIntent,
 3737        window: &mut Window,
 3738        cx: &mut App,
 3739    ) -> Task<Result<()>> {
 3740        let project = self.project.clone();
 3741        let pane = self.active_pane();
 3742        let item = pane.read(cx).active_item();
 3743        let pane = pane.downgrade();
 3744
 3745        window.spawn(cx, async move |cx| {
 3746            if let Some(item) = item {
 3747                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3748                    .await
 3749                    .map(|_| ())
 3750            } else {
 3751                Ok(())
 3752            }
 3753        })
 3754    }
 3755
 3756    pub fn close_inactive_items_and_panes(
 3757        &mut self,
 3758        action: &CloseInactiveTabsAndPanes,
 3759        window: &mut Window,
 3760        cx: &mut Context<Self>,
 3761    ) {
 3762        if let Some(task) = self.close_all_internal(
 3763            true,
 3764            action.save_intent.unwrap_or(SaveIntent::Close),
 3765            window,
 3766            cx,
 3767        ) {
 3768            task.detach_and_log_err(cx)
 3769        }
 3770    }
 3771
 3772    pub fn close_all_items_and_panes(
 3773        &mut self,
 3774        action: &CloseAllItemsAndPanes,
 3775        window: &mut Window,
 3776        cx: &mut Context<Self>,
 3777    ) {
 3778        if let Some(task) = self.close_all_internal(
 3779            false,
 3780            action.save_intent.unwrap_or(SaveIntent::Close),
 3781            window,
 3782            cx,
 3783        ) {
 3784            task.detach_and_log_err(cx)
 3785        }
 3786    }
 3787
 3788    /// Closes the active item across all panes.
 3789    pub fn close_item_in_all_panes(
 3790        &mut self,
 3791        action: &CloseItemInAllPanes,
 3792        window: &mut Window,
 3793        cx: &mut Context<Self>,
 3794    ) {
 3795        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3796            return;
 3797        };
 3798
 3799        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3800        let close_pinned = action.close_pinned;
 3801
 3802        if let Some(project_path) = active_item.project_path(cx) {
 3803            self.close_items_with_project_path(
 3804                &project_path,
 3805                save_intent,
 3806                close_pinned,
 3807                window,
 3808                cx,
 3809            );
 3810        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3811            let item_id = active_item.item_id();
 3812            self.active_pane().update(cx, |pane, cx| {
 3813                pane.close_item_by_id(item_id, save_intent, window, cx)
 3814                    .detach_and_log_err(cx);
 3815            });
 3816        }
 3817    }
 3818
 3819    /// Closes all items with the given project path across all panes.
 3820    pub fn close_items_with_project_path(
 3821        &mut self,
 3822        project_path: &ProjectPath,
 3823        save_intent: SaveIntent,
 3824        close_pinned: bool,
 3825        window: &mut Window,
 3826        cx: &mut Context<Self>,
 3827    ) {
 3828        let panes = self.panes().to_vec();
 3829        for pane in panes {
 3830            pane.update(cx, |pane, cx| {
 3831                pane.close_items_for_project_path(
 3832                    project_path,
 3833                    save_intent,
 3834                    close_pinned,
 3835                    window,
 3836                    cx,
 3837                )
 3838                .detach_and_log_err(cx);
 3839            });
 3840        }
 3841    }
 3842
 3843    fn close_all_internal(
 3844        &mut self,
 3845        retain_active_pane: bool,
 3846        save_intent: SaveIntent,
 3847        window: &mut Window,
 3848        cx: &mut Context<Self>,
 3849    ) -> Option<Task<Result<()>>> {
 3850        let current_pane = self.active_pane();
 3851
 3852        let mut tasks = Vec::new();
 3853
 3854        if retain_active_pane {
 3855            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3856                pane.close_other_items(
 3857                    &CloseOtherItems {
 3858                        save_intent: None,
 3859                        close_pinned: false,
 3860                    },
 3861                    None,
 3862                    window,
 3863                    cx,
 3864                )
 3865            });
 3866
 3867            tasks.push(current_pane_close);
 3868        }
 3869
 3870        for pane in self.panes() {
 3871            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3872                continue;
 3873            }
 3874
 3875            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3876                pane.close_all_items(
 3877                    &CloseAllItems {
 3878                        save_intent: Some(save_intent),
 3879                        close_pinned: false,
 3880                    },
 3881                    window,
 3882                    cx,
 3883                )
 3884            });
 3885
 3886            tasks.push(close_pane_items)
 3887        }
 3888
 3889        if tasks.is_empty() {
 3890            None
 3891        } else {
 3892            Some(cx.spawn_in(window, async move |_, _| {
 3893                for task in tasks {
 3894                    task.await?
 3895                }
 3896                Ok(())
 3897            }))
 3898        }
 3899    }
 3900
 3901    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3902        self.dock_at_position(position).read(cx).is_open()
 3903    }
 3904
 3905    pub fn toggle_dock(
 3906        &mut self,
 3907        dock_side: DockPosition,
 3908        window: &mut Window,
 3909        cx: &mut Context<Self>,
 3910    ) {
 3911        let mut focus_center = false;
 3912        let mut reveal_dock = false;
 3913
 3914        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3915        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3916
 3917        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3918            telemetry::event!(
 3919                "Panel Button Clicked",
 3920                name = panel.persistent_name(),
 3921                toggle_state = !was_visible
 3922            );
 3923        }
 3924        if was_visible {
 3925            self.save_open_dock_positions(cx);
 3926        }
 3927
 3928        let dock = self.dock_at_position(dock_side);
 3929        dock.update(cx, |dock, cx| {
 3930            dock.set_open(!was_visible, window, cx);
 3931
 3932            if dock.active_panel().is_none() {
 3933                let Some(panel_ix) = dock
 3934                    .first_enabled_panel_idx(cx)
 3935                    .log_with_level(log::Level::Info)
 3936                else {
 3937                    return;
 3938                };
 3939                dock.activate_panel(panel_ix, window, cx);
 3940            }
 3941
 3942            if let Some(active_panel) = dock.active_panel() {
 3943                if was_visible {
 3944                    if active_panel
 3945                        .panel_focus_handle(cx)
 3946                        .contains_focused(window, cx)
 3947                    {
 3948                        focus_center = true;
 3949                    }
 3950                } else {
 3951                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3952                    window.focus(focus_handle, cx);
 3953                    reveal_dock = true;
 3954                }
 3955            }
 3956        });
 3957
 3958        if reveal_dock {
 3959            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3960        }
 3961
 3962        if focus_center {
 3963            self.active_pane
 3964                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3965        }
 3966
 3967        cx.notify();
 3968        self.serialize_workspace(window, cx);
 3969    }
 3970
 3971    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3972        self.all_docks().into_iter().find(|&dock| {
 3973            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3974        })
 3975    }
 3976
 3977    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3978        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3979            self.save_open_dock_positions(cx);
 3980            dock.update(cx, |dock, cx| {
 3981                dock.set_open(false, window, cx);
 3982            });
 3983            return true;
 3984        }
 3985        false
 3986    }
 3987
 3988    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3989        self.save_open_dock_positions(cx);
 3990        for dock in self.all_docks() {
 3991            dock.update(cx, |dock, cx| {
 3992                dock.set_open(false, window, cx);
 3993            });
 3994        }
 3995
 3996        cx.focus_self(window);
 3997        cx.notify();
 3998        self.serialize_workspace(window, cx);
 3999    }
 4000
 4001    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 4002        self.all_docks()
 4003            .into_iter()
 4004            .filter_map(|dock| {
 4005                let dock_ref = dock.read(cx);
 4006                if dock_ref.is_open() {
 4007                    Some(dock_ref.position())
 4008                } else {
 4009                    None
 4010                }
 4011            })
 4012            .collect()
 4013    }
 4014
 4015    /// Saves the positions of currently open docks.
 4016    ///
 4017    /// Updates `last_open_dock_positions` with positions of all currently open
 4018    /// docks, to later be restored by the 'Toggle All Docks' action.
 4019    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 4020        let open_dock_positions = self.get_open_dock_positions(cx);
 4021        if !open_dock_positions.is_empty() {
 4022            self.last_open_dock_positions = open_dock_positions;
 4023        }
 4024    }
 4025
 4026    /// Toggles all docks between open and closed states.
 4027    ///
 4028    /// If any docks are open, closes all and remembers their positions. If all
 4029    /// docks are closed, restores the last remembered dock configuration.
 4030    fn toggle_all_docks(
 4031        &mut self,
 4032        _: &ToggleAllDocks,
 4033        window: &mut Window,
 4034        cx: &mut Context<Self>,
 4035    ) {
 4036        let open_dock_positions = self.get_open_dock_positions(cx);
 4037
 4038        if !open_dock_positions.is_empty() {
 4039            self.close_all_docks(window, cx);
 4040        } else if !self.last_open_dock_positions.is_empty() {
 4041            self.restore_last_open_docks(window, cx);
 4042        }
 4043    }
 4044
 4045    /// Reopens docks from the most recently remembered configuration.
 4046    ///
 4047    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 4048    /// and clears the stored positions.
 4049    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4050        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 4051
 4052        for position in positions_to_open {
 4053            let dock = self.dock_at_position(position);
 4054            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 4055        }
 4056
 4057        cx.focus_self(window);
 4058        cx.notify();
 4059        self.serialize_workspace(window, cx);
 4060    }
 4061
 4062    /// Transfer focus to the panel of the given type.
 4063    pub fn focus_panel<T: Panel>(
 4064        &mut self,
 4065        window: &mut Window,
 4066        cx: &mut Context<Self>,
 4067    ) -> Option<Entity<T>> {
 4068        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 4069        panel.to_any().downcast().ok()
 4070    }
 4071
 4072    /// Focus the panel of the given type if it isn't already focused. If it is
 4073    /// already focused, then transfer focus back to the workspace center.
 4074    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 4075    /// panel when transferring focus back to the center.
 4076    pub fn toggle_panel_focus<T: Panel>(
 4077        &mut self,
 4078        window: &mut Window,
 4079        cx: &mut Context<Self>,
 4080    ) -> bool {
 4081        let mut did_focus_panel = false;
 4082        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 4083            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 4084            did_focus_panel
 4085        });
 4086
 4087        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 4088            self.close_panel::<T>(window, cx);
 4089        }
 4090
 4091        telemetry::event!(
 4092            "Panel Button Clicked",
 4093            name = T::persistent_name(),
 4094            toggle_state = did_focus_panel
 4095        );
 4096
 4097        did_focus_panel
 4098    }
 4099
 4100    pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4101        if let Some(item) = self.active_item(cx) {
 4102            item.item_focus_handle(cx).focus(window, cx);
 4103        } else {
 4104            log::error!("Could not find a focus target when switching focus to the center panes",);
 4105        }
 4106    }
 4107
 4108    pub fn activate_panel_for_proto_id(
 4109        &mut self,
 4110        panel_id: PanelId,
 4111        window: &mut Window,
 4112        cx: &mut Context<Self>,
 4113    ) -> Option<Arc<dyn PanelHandle>> {
 4114        let mut panel = None;
 4115        for dock in self.all_docks() {
 4116            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 4117                panel = dock.update(cx, |dock, cx| {
 4118                    dock.activate_panel(panel_index, window, cx);
 4119                    dock.set_open(true, window, cx);
 4120                    dock.active_panel().cloned()
 4121                });
 4122                break;
 4123            }
 4124        }
 4125
 4126        if panel.is_some() {
 4127            cx.notify();
 4128            self.serialize_workspace(window, cx);
 4129        }
 4130
 4131        panel
 4132    }
 4133
 4134    /// Focus or unfocus the given panel type, depending on the given callback.
 4135    fn focus_or_unfocus_panel<T: Panel>(
 4136        &mut self,
 4137        window: &mut Window,
 4138        cx: &mut Context<Self>,
 4139        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 4140    ) -> Option<Arc<dyn PanelHandle>> {
 4141        let mut result_panel = None;
 4142        let mut serialize = false;
 4143        for dock in self.all_docks() {
 4144            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4145                let mut focus_center = false;
 4146                let panel = dock.update(cx, |dock, cx| {
 4147                    dock.activate_panel(panel_index, window, cx);
 4148
 4149                    let panel = dock.active_panel().cloned();
 4150                    if let Some(panel) = panel.as_ref() {
 4151                        if should_focus(&**panel, window, cx) {
 4152                            dock.set_open(true, window, cx);
 4153                            panel.panel_focus_handle(cx).focus(window, cx);
 4154                        } else {
 4155                            focus_center = true;
 4156                        }
 4157                    }
 4158                    panel
 4159                });
 4160
 4161                if focus_center {
 4162                    self.active_pane
 4163                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4164                }
 4165
 4166                result_panel = panel;
 4167                serialize = true;
 4168                break;
 4169            }
 4170        }
 4171
 4172        if serialize {
 4173            self.serialize_workspace(window, cx);
 4174        }
 4175
 4176        cx.notify();
 4177        result_panel
 4178    }
 4179
 4180    /// Open the panel of the given type
 4181    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4182        for dock in self.all_docks() {
 4183            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4184                dock.update(cx, |dock, cx| {
 4185                    dock.activate_panel(panel_index, window, cx);
 4186                    dock.set_open(true, window, cx);
 4187                });
 4188            }
 4189        }
 4190    }
 4191
 4192    /// Open the panel of the given type, dismissing any zoomed items that
 4193    /// would obscure it (e.g. a zoomed terminal).
 4194    pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4195        let dock_position = self.all_docks().iter().find_map(|dock| {
 4196            let dock = dock.read(cx);
 4197            dock.panel_index_for_type::<T>().map(|_| dock.position())
 4198        });
 4199        self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
 4200        self.open_panel::<T>(window, cx);
 4201    }
 4202
 4203    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 4204        for dock in self.all_docks().iter() {
 4205            dock.update(cx, |dock, cx| {
 4206                if dock.panel::<T>().is_some() {
 4207                    dock.set_open(false, window, cx)
 4208                }
 4209            })
 4210        }
 4211    }
 4212
 4213    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 4214        self.all_docks()
 4215            .iter()
 4216            .find_map(|dock| dock.read(cx).panel::<T>())
 4217    }
 4218
 4219    fn dismiss_zoomed_items_to_reveal(
 4220        &mut self,
 4221        dock_to_reveal: Option<DockPosition>,
 4222        window: &mut Window,
 4223        cx: &mut Context<Self>,
 4224    ) {
 4225        // If a center pane is zoomed, unzoom it.
 4226        for pane in &self.panes {
 4227            if pane != &self.active_pane || dock_to_reveal.is_some() {
 4228                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4229            }
 4230        }
 4231
 4232        // If another dock is zoomed, hide it.
 4233        let mut focus_center = false;
 4234        for dock in self.all_docks() {
 4235            dock.update(cx, |dock, cx| {
 4236                if Some(dock.position()) != dock_to_reveal
 4237                    && let Some(panel) = dock.active_panel()
 4238                    && panel.is_zoomed(window, cx)
 4239                {
 4240                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 4241                    dock.set_open(false, window, cx);
 4242                }
 4243            });
 4244        }
 4245
 4246        if focus_center {
 4247            self.active_pane
 4248                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4249        }
 4250
 4251        if self.zoomed_position != dock_to_reveal {
 4252            self.zoomed = None;
 4253            self.zoomed_position = None;
 4254            cx.emit(Event::ZoomChanged);
 4255        }
 4256
 4257        cx.notify();
 4258    }
 4259
 4260    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4261        let pane = cx.new(|cx| {
 4262            let mut pane = Pane::new(
 4263                self.weak_handle(),
 4264                self.project.clone(),
 4265                self.pane_history_timestamp.clone(),
 4266                None,
 4267                NewFile.boxed_clone(),
 4268                true,
 4269                window,
 4270                cx,
 4271            );
 4272            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4273            pane
 4274        });
 4275        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4276            .detach();
 4277        self.panes.push(pane.clone());
 4278
 4279        window.focus(&pane.focus_handle(cx), cx);
 4280
 4281        cx.emit(Event::PaneAdded(pane.clone()));
 4282        pane
 4283    }
 4284
 4285    pub fn add_item_to_center(
 4286        &mut self,
 4287        item: Box<dyn ItemHandle>,
 4288        window: &mut Window,
 4289        cx: &mut Context<Self>,
 4290    ) -> bool {
 4291        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4292            if let Some(center_pane) = center_pane.upgrade() {
 4293                center_pane.update(cx, |pane, cx| {
 4294                    pane.add_item(item, true, true, None, window, cx)
 4295                });
 4296                true
 4297            } else {
 4298                false
 4299            }
 4300        } else {
 4301            false
 4302        }
 4303    }
 4304
 4305    pub fn add_item_to_active_pane(
 4306        &mut self,
 4307        item: Box<dyn ItemHandle>,
 4308        destination_index: Option<usize>,
 4309        focus_item: bool,
 4310        window: &mut Window,
 4311        cx: &mut App,
 4312    ) {
 4313        self.add_item(
 4314            self.active_pane.clone(),
 4315            item,
 4316            destination_index,
 4317            false,
 4318            focus_item,
 4319            window,
 4320            cx,
 4321        )
 4322    }
 4323
 4324    pub fn add_item(
 4325        &mut self,
 4326        pane: Entity<Pane>,
 4327        item: Box<dyn ItemHandle>,
 4328        destination_index: Option<usize>,
 4329        activate_pane: bool,
 4330        focus_item: bool,
 4331        window: &mut Window,
 4332        cx: &mut App,
 4333    ) {
 4334        pane.update(cx, |pane, cx| {
 4335            pane.add_item(
 4336                item,
 4337                activate_pane,
 4338                focus_item,
 4339                destination_index,
 4340                window,
 4341                cx,
 4342            )
 4343        });
 4344    }
 4345
 4346    pub fn split_item(
 4347        &mut self,
 4348        split_direction: SplitDirection,
 4349        item: Box<dyn ItemHandle>,
 4350        window: &mut Window,
 4351        cx: &mut Context<Self>,
 4352    ) {
 4353        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4354        self.add_item(new_pane, item, None, true, true, window, cx);
 4355    }
 4356
 4357    pub fn open_abs_path(
 4358        &mut self,
 4359        abs_path: PathBuf,
 4360        options: OpenOptions,
 4361        window: &mut Window,
 4362        cx: &mut Context<Self>,
 4363    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4364        cx.spawn_in(window, async move |workspace, cx| {
 4365            let open_paths_task_result = workspace
 4366                .update_in(cx, |workspace, window, cx| {
 4367                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4368                })
 4369                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4370                .await;
 4371            anyhow::ensure!(
 4372                open_paths_task_result.len() == 1,
 4373                "open abs path {abs_path:?} task returned incorrect number of results"
 4374            );
 4375            match open_paths_task_result
 4376                .into_iter()
 4377                .next()
 4378                .expect("ensured single task result")
 4379            {
 4380                Some(open_result) => {
 4381                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4382                }
 4383                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4384            }
 4385        })
 4386    }
 4387
 4388    pub fn split_abs_path(
 4389        &mut self,
 4390        abs_path: PathBuf,
 4391        visible: bool,
 4392        window: &mut Window,
 4393        cx: &mut Context<Self>,
 4394    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4395        let project_path_task =
 4396            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4397        cx.spawn_in(window, async move |this, cx| {
 4398            let (_, path) = project_path_task.await?;
 4399            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4400                .await
 4401        })
 4402    }
 4403
 4404    pub fn open_path(
 4405        &mut self,
 4406        path: impl Into<ProjectPath>,
 4407        pane: Option<WeakEntity<Pane>>,
 4408        focus_item: bool,
 4409        window: &mut Window,
 4410        cx: &mut App,
 4411    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4412        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4413    }
 4414
 4415    pub fn open_path_preview(
 4416        &mut self,
 4417        path: impl Into<ProjectPath>,
 4418        pane: Option<WeakEntity<Pane>>,
 4419        focus_item: bool,
 4420        allow_preview: bool,
 4421        activate: bool,
 4422        window: &mut Window,
 4423        cx: &mut App,
 4424    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4425        let pane = pane.unwrap_or_else(|| {
 4426            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4427                self.panes
 4428                    .first()
 4429                    .expect("There must be an active pane")
 4430                    .downgrade()
 4431            })
 4432        });
 4433
 4434        let project_path = path.into();
 4435        let task = self.load_path(project_path.clone(), window, cx);
 4436        window.spawn(cx, async move |cx| {
 4437            let (project_entry_id, build_item) = task.await?;
 4438
 4439            pane.update_in(cx, |pane, window, cx| {
 4440                pane.open_item(
 4441                    project_entry_id,
 4442                    project_path,
 4443                    focus_item,
 4444                    allow_preview,
 4445                    activate,
 4446                    None,
 4447                    window,
 4448                    cx,
 4449                    build_item,
 4450                )
 4451            })
 4452        })
 4453    }
 4454
 4455    pub fn split_path(
 4456        &mut self,
 4457        path: impl Into<ProjectPath>,
 4458        window: &mut Window,
 4459        cx: &mut Context<Self>,
 4460    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4461        self.split_path_preview(path, false, None, window, cx)
 4462    }
 4463
 4464    pub fn split_path_preview(
 4465        &mut self,
 4466        path: impl Into<ProjectPath>,
 4467        allow_preview: bool,
 4468        split_direction: Option<SplitDirection>,
 4469        window: &mut Window,
 4470        cx: &mut Context<Self>,
 4471    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4472        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4473            self.panes
 4474                .first()
 4475                .expect("There must be an active pane")
 4476                .downgrade()
 4477        });
 4478
 4479        if let Member::Pane(center_pane) = &self.center.root
 4480            && center_pane.read(cx).items_len() == 0
 4481        {
 4482            return self.open_path(path, Some(pane), true, window, cx);
 4483        }
 4484
 4485        let project_path = path.into();
 4486        let task = self.load_path(project_path.clone(), window, cx);
 4487        cx.spawn_in(window, async move |this, cx| {
 4488            let (project_entry_id, build_item) = task.await?;
 4489            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4490                let pane = pane.upgrade()?;
 4491                let new_pane = this.split_pane(
 4492                    pane,
 4493                    split_direction.unwrap_or(SplitDirection::Right),
 4494                    window,
 4495                    cx,
 4496                );
 4497                new_pane.update(cx, |new_pane, cx| {
 4498                    Some(new_pane.open_item(
 4499                        project_entry_id,
 4500                        project_path,
 4501                        true,
 4502                        allow_preview,
 4503                        true,
 4504                        None,
 4505                        window,
 4506                        cx,
 4507                        build_item,
 4508                    ))
 4509                })
 4510            })
 4511            .map(|option| option.context("pane was dropped"))?
 4512        })
 4513    }
 4514
 4515    fn load_path(
 4516        &mut self,
 4517        path: ProjectPath,
 4518        window: &mut Window,
 4519        cx: &mut App,
 4520    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4521        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4522        registry.open_path(self.project(), &path, window, cx)
 4523    }
 4524
 4525    pub fn find_project_item<T>(
 4526        &self,
 4527        pane: &Entity<Pane>,
 4528        project_item: &Entity<T::Item>,
 4529        cx: &App,
 4530    ) -> Option<Entity<T>>
 4531    where
 4532        T: ProjectItem,
 4533    {
 4534        use project::ProjectItem as _;
 4535        let project_item = project_item.read(cx);
 4536        let entry_id = project_item.entry_id(cx);
 4537        let project_path = project_item.project_path(cx);
 4538
 4539        let mut item = None;
 4540        if let Some(entry_id) = entry_id {
 4541            item = pane.read(cx).item_for_entry(entry_id, cx);
 4542        }
 4543        if item.is_none()
 4544            && let Some(project_path) = project_path
 4545        {
 4546            item = pane.read(cx).item_for_path(project_path, cx);
 4547        }
 4548
 4549        item.and_then(|item| item.downcast::<T>())
 4550    }
 4551
 4552    pub fn is_project_item_open<T>(
 4553        &self,
 4554        pane: &Entity<Pane>,
 4555        project_item: &Entity<T::Item>,
 4556        cx: &App,
 4557    ) -> bool
 4558    where
 4559        T: ProjectItem,
 4560    {
 4561        self.find_project_item::<T>(pane, project_item, cx)
 4562            .is_some()
 4563    }
 4564
 4565    pub fn open_project_item<T>(
 4566        &mut self,
 4567        pane: Entity<Pane>,
 4568        project_item: Entity<T::Item>,
 4569        activate_pane: bool,
 4570        focus_item: bool,
 4571        keep_old_preview: bool,
 4572        allow_new_preview: bool,
 4573        window: &mut Window,
 4574        cx: &mut Context<Self>,
 4575    ) -> Entity<T>
 4576    where
 4577        T: ProjectItem,
 4578    {
 4579        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4580
 4581        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4582            if !keep_old_preview
 4583                && let Some(old_id) = old_item_id
 4584                && old_id != item.item_id()
 4585            {
 4586                // switching to a different item, so unpreview old active item
 4587                pane.update(cx, |pane, _| {
 4588                    pane.unpreview_item_if_preview(old_id);
 4589                });
 4590            }
 4591
 4592            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4593            if !allow_new_preview {
 4594                pane.update(cx, |pane, _| {
 4595                    pane.unpreview_item_if_preview(item.item_id());
 4596                });
 4597            }
 4598            return item;
 4599        }
 4600
 4601        let item = pane.update(cx, |pane, cx| {
 4602            cx.new(|cx| {
 4603                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4604            })
 4605        });
 4606        let mut destination_index = None;
 4607        pane.update(cx, |pane, cx| {
 4608            if !keep_old_preview && let Some(old_id) = old_item_id {
 4609                pane.unpreview_item_if_preview(old_id);
 4610            }
 4611            if allow_new_preview {
 4612                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4613            }
 4614        });
 4615
 4616        self.add_item(
 4617            pane,
 4618            Box::new(item.clone()),
 4619            destination_index,
 4620            activate_pane,
 4621            focus_item,
 4622            window,
 4623            cx,
 4624        );
 4625        item
 4626    }
 4627
 4628    pub fn open_shared_screen(
 4629        &mut self,
 4630        peer_id: PeerId,
 4631        window: &mut Window,
 4632        cx: &mut Context<Self>,
 4633    ) {
 4634        if let Some(shared_screen) =
 4635            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4636        {
 4637            self.active_pane.update(cx, |pane, cx| {
 4638                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4639            });
 4640        }
 4641    }
 4642
 4643    pub fn activate_item(
 4644        &mut self,
 4645        item: &dyn ItemHandle,
 4646        activate_pane: bool,
 4647        focus_item: bool,
 4648        window: &mut Window,
 4649        cx: &mut App,
 4650    ) -> bool {
 4651        let result = self.panes.iter().find_map(|pane| {
 4652            pane.read(cx)
 4653                .index_for_item(item)
 4654                .map(|ix| (pane.clone(), ix))
 4655        });
 4656        if let Some((pane, ix)) = result {
 4657            pane.update(cx, |pane, cx| {
 4658                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4659            });
 4660            true
 4661        } else {
 4662            false
 4663        }
 4664    }
 4665
 4666    fn activate_pane_at_index(
 4667        &mut self,
 4668        action: &ActivatePane,
 4669        window: &mut Window,
 4670        cx: &mut Context<Self>,
 4671    ) {
 4672        let panes = self.center.panes();
 4673        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4674            window.focus(&pane.focus_handle(cx), cx);
 4675        } else {
 4676            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4677                .detach();
 4678        }
 4679    }
 4680
 4681    fn move_item_to_pane_at_index(
 4682        &mut self,
 4683        action: &MoveItemToPane,
 4684        window: &mut Window,
 4685        cx: &mut Context<Self>,
 4686    ) {
 4687        let panes = self.center.panes();
 4688        let destination = match panes.get(action.destination) {
 4689            Some(&destination) => destination.clone(),
 4690            None => {
 4691                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4692                    return;
 4693                }
 4694                let direction = SplitDirection::Right;
 4695                let split_off_pane = self
 4696                    .find_pane_in_direction(direction, cx)
 4697                    .unwrap_or_else(|| self.active_pane.clone());
 4698                let new_pane = self.add_pane(window, cx);
 4699                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4700                new_pane
 4701            }
 4702        };
 4703
 4704        if action.clone {
 4705            if self
 4706                .active_pane
 4707                .read(cx)
 4708                .active_item()
 4709                .is_some_and(|item| item.can_split(cx))
 4710            {
 4711                clone_active_item(
 4712                    self.database_id(),
 4713                    &self.active_pane,
 4714                    &destination,
 4715                    action.focus,
 4716                    window,
 4717                    cx,
 4718                );
 4719                return;
 4720            }
 4721        }
 4722        move_active_item(
 4723            &self.active_pane,
 4724            &destination,
 4725            action.focus,
 4726            true,
 4727            window,
 4728            cx,
 4729        )
 4730    }
 4731
 4732    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4733        let panes = self.center.panes();
 4734        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4735            let next_ix = (ix + 1) % panes.len();
 4736            let next_pane = panes[next_ix].clone();
 4737            window.focus(&next_pane.focus_handle(cx), cx);
 4738        }
 4739    }
 4740
 4741    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4742        let panes = self.center.panes();
 4743        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4744            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4745            let prev_pane = panes[prev_ix].clone();
 4746            window.focus(&prev_pane.focus_handle(cx), cx);
 4747        }
 4748    }
 4749
 4750    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4751        let last_pane = self.center.last_pane();
 4752        window.focus(&last_pane.focus_handle(cx), cx);
 4753    }
 4754
 4755    pub fn activate_pane_in_direction(
 4756        &mut self,
 4757        direction: SplitDirection,
 4758        window: &mut Window,
 4759        cx: &mut App,
 4760    ) {
 4761        use ActivateInDirectionTarget as Target;
 4762        enum Origin {
 4763            Sidebar,
 4764            LeftDock,
 4765            RightDock,
 4766            BottomDock,
 4767            Center,
 4768        }
 4769
 4770        let origin: Origin = if self
 4771            .sidebar_focus_handle
 4772            .as_ref()
 4773            .is_some_and(|h| h.contains_focused(window, cx))
 4774        {
 4775            Origin::Sidebar
 4776        } else {
 4777            [
 4778                (&self.left_dock, Origin::LeftDock),
 4779                (&self.right_dock, Origin::RightDock),
 4780                (&self.bottom_dock, Origin::BottomDock),
 4781            ]
 4782            .into_iter()
 4783            .find_map(|(dock, origin)| {
 4784                if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4785                    Some(origin)
 4786                } else {
 4787                    None
 4788                }
 4789            })
 4790            .unwrap_or(Origin::Center)
 4791        };
 4792
 4793        let get_last_active_pane = || {
 4794            let pane = self
 4795                .last_active_center_pane
 4796                .clone()
 4797                .unwrap_or_else(|| {
 4798                    self.panes
 4799                        .first()
 4800                        .expect("There must be an active pane")
 4801                        .downgrade()
 4802                })
 4803                .upgrade()?;
 4804            (pane.read(cx).items_len() != 0).then_some(pane)
 4805        };
 4806
 4807        let try_dock =
 4808            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4809
 4810        let sidebar_target = self
 4811            .sidebar_focus_handle
 4812            .as_ref()
 4813            .map(|h| Target::Sidebar(h.clone()));
 4814
 4815        let target = match (origin, direction) {
 4816            // From the sidebar, only Right navigates into the workspace.
 4817            (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
 4818                .or_else(|| get_last_active_pane().map(Target::Pane))
 4819                .or_else(|| try_dock(&self.bottom_dock))
 4820                .or_else(|| try_dock(&self.right_dock)),
 4821
 4822            (Origin::Sidebar, _) => None,
 4823
 4824            // We're in the center, so we first try to go to a different pane,
 4825            // otherwise try to go to a dock.
 4826            (Origin::Center, direction) => {
 4827                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4828                    Some(Target::Pane(pane))
 4829                } else {
 4830                    match direction {
 4831                        SplitDirection::Up => None,
 4832                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4833                        SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
 4834                        SplitDirection::Right => try_dock(&self.right_dock),
 4835                    }
 4836                }
 4837            }
 4838
 4839            (Origin::LeftDock, SplitDirection::Right) => {
 4840                if let Some(last_active_pane) = get_last_active_pane() {
 4841                    Some(Target::Pane(last_active_pane))
 4842                } else {
 4843                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4844                }
 4845            }
 4846
 4847            (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
 4848
 4849            (Origin::LeftDock, SplitDirection::Down)
 4850            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4851
 4852            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4853            (Origin::BottomDock, SplitDirection::Left) => {
 4854                try_dock(&self.left_dock).or(sidebar_target)
 4855            }
 4856            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4857
 4858            (Origin::RightDock, SplitDirection::Left) => {
 4859                if let Some(last_active_pane) = get_last_active_pane() {
 4860                    Some(Target::Pane(last_active_pane))
 4861                } else {
 4862                    try_dock(&self.bottom_dock)
 4863                        .or_else(|| try_dock(&self.left_dock))
 4864                        .or(sidebar_target)
 4865                }
 4866            }
 4867
 4868            _ => None,
 4869        };
 4870
 4871        match target {
 4872            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4873                let pane = pane.read(cx);
 4874                if let Some(item) = pane.active_item() {
 4875                    item.item_focus_handle(cx).focus(window, cx);
 4876                } else {
 4877                    log::error!(
 4878                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4879                    );
 4880                }
 4881            }
 4882            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4883                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4884                window.defer(cx, move |window, cx| {
 4885                    let dock = dock.read(cx);
 4886                    if let Some(panel) = dock.active_panel() {
 4887                        panel.panel_focus_handle(cx).focus(window, cx);
 4888                    } else {
 4889                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4890                    }
 4891                })
 4892            }
 4893            Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
 4894                focus_handle.focus(window, cx);
 4895            }
 4896            None => {}
 4897        }
 4898    }
 4899
 4900    pub fn move_item_to_pane_in_direction(
 4901        &mut self,
 4902        action: &MoveItemToPaneInDirection,
 4903        window: &mut Window,
 4904        cx: &mut Context<Self>,
 4905    ) {
 4906        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4907            Some(destination) => destination,
 4908            None => {
 4909                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4910                    return;
 4911                }
 4912                let new_pane = self.add_pane(window, cx);
 4913                self.center
 4914                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4915                new_pane
 4916            }
 4917        };
 4918
 4919        if action.clone {
 4920            if self
 4921                .active_pane
 4922                .read(cx)
 4923                .active_item()
 4924                .is_some_and(|item| item.can_split(cx))
 4925            {
 4926                clone_active_item(
 4927                    self.database_id(),
 4928                    &self.active_pane,
 4929                    &destination,
 4930                    action.focus,
 4931                    window,
 4932                    cx,
 4933                );
 4934                return;
 4935            }
 4936        }
 4937        move_active_item(
 4938            &self.active_pane,
 4939            &destination,
 4940            action.focus,
 4941            true,
 4942            window,
 4943            cx,
 4944        );
 4945    }
 4946
 4947    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4948        self.center.bounding_box_for_pane(pane)
 4949    }
 4950
 4951    pub fn find_pane_in_direction(
 4952        &mut self,
 4953        direction: SplitDirection,
 4954        cx: &App,
 4955    ) -> Option<Entity<Pane>> {
 4956        self.center
 4957            .find_pane_in_direction(&self.active_pane, direction, cx)
 4958            .cloned()
 4959    }
 4960
 4961    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4962        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4963            self.center.swap(&self.active_pane, &to, cx);
 4964            cx.notify();
 4965        }
 4966    }
 4967
 4968    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4969        if self
 4970            .center
 4971            .move_to_border(&self.active_pane, direction, cx)
 4972            .unwrap()
 4973        {
 4974            cx.notify();
 4975        }
 4976    }
 4977
 4978    pub fn resize_pane(
 4979        &mut self,
 4980        axis: gpui::Axis,
 4981        amount: Pixels,
 4982        window: &mut Window,
 4983        cx: &mut Context<Self>,
 4984    ) {
 4985        let docks = self.all_docks();
 4986        let active_dock = docks
 4987            .into_iter()
 4988            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4989
 4990        if let Some(dock_entity) = active_dock {
 4991            let dock = dock_entity.read(cx);
 4992            let Some(panel_size) = self.dock_size(&dock, window, cx) else {
 4993                return;
 4994            };
 4995            match dock.position() {
 4996                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4997                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4998                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4999            }
 5000        } else {
 5001            self.center
 5002                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 5003        }
 5004        cx.notify();
 5005    }
 5006
 5007    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 5008        self.center.reset_pane_sizes(cx);
 5009        cx.notify();
 5010    }
 5011
 5012    fn handle_pane_focused(
 5013        &mut self,
 5014        pane: Entity<Pane>,
 5015        window: &mut Window,
 5016        cx: &mut Context<Self>,
 5017    ) {
 5018        // This is explicitly hoisted out of the following check for pane identity as
 5019        // terminal panel panes are not registered as a center panes.
 5020        self.status_bar.update(cx, |status_bar, cx| {
 5021            status_bar.set_active_pane(&pane, window, cx);
 5022        });
 5023        if self.active_pane != pane {
 5024            self.set_active_pane(&pane, window, cx);
 5025        }
 5026
 5027        if self.last_active_center_pane.is_none() {
 5028            self.last_active_center_pane = Some(pane.downgrade());
 5029        }
 5030
 5031        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 5032        // This prevents the dock from closing when focus events fire during window activation.
 5033        // We also preserve any dock whose active panel itself has focus — this covers
 5034        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 5035        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 5036            let dock_read = dock.read(cx);
 5037            if let Some(panel) = dock_read.active_panel() {
 5038                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 5039                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 5040                {
 5041                    return Some(dock_read.position());
 5042                }
 5043            }
 5044            None
 5045        });
 5046
 5047        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 5048        if pane.read(cx).is_zoomed() {
 5049            self.zoomed = Some(pane.downgrade().into());
 5050        } else {
 5051            self.zoomed = None;
 5052        }
 5053        self.zoomed_position = None;
 5054        cx.emit(Event::ZoomChanged);
 5055        self.update_active_view_for_followers(window, cx);
 5056        pane.update(cx, |pane, _| {
 5057            pane.track_alternate_file_items();
 5058        });
 5059
 5060        cx.notify();
 5061    }
 5062
 5063    fn set_active_pane(
 5064        &mut self,
 5065        pane: &Entity<Pane>,
 5066        window: &mut Window,
 5067        cx: &mut Context<Self>,
 5068    ) {
 5069        self.active_pane = pane.clone();
 5070        self.active_item_path_changed(true, window, cx);
 5071        self.last_active_center_pane = Some(pane.downgrade());
 5072    }
 5073
 5074    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5075        self.update_active_view_for_followers(window, cx);
 5076    }
 5077
 5078    fn handle_pane_event(
 5079        &mut self,
 5080        pane: &Entity<Pane>,
 5081        event: &pane::Event,
 5082        window: &mut Window,
 5083        cx: &mut Context<Self>,
 5084    ) {
 5085        let mut serialize_workspace = true;
 5086        match event {
 5087            pane::Event::AddItem { item } => {
 5088                item.added_to_pane(self, pane.clone(), window, cx);
 5089                cx.emit(Event::ItemAdded {
 5090                    item: item.boxed_clone(),
 5091                });
 5092            }
 5093            pane::Event::Split { direction, mode } => {
 5094                match mode {
 5095                    SplitMode::ClonePane => {
 5096                        self.split_and_clone(pane.clone(), *direction, window, cx)
 5097                            .detach();
 5098                    }
 5099                    SplitMode::EmptyPane => {
 5100                        self.split_pane(pane.clone(), *direction, window, cx);
 5101                    }
 5102                    SplitMode::MovePane => {
 5103                        self.split_and_move(pane.clone(), *direction, window, cx);
 5104                    }
 5105                };
 5106            }
 5107            pane::Event::JoinIntoNext => {
 5108                self.join_pane_into_next(pane.clone(), window, cx);
 5109            }
 5110            pane::Event::JoinAll => {
 5111                self.join_all_panes(window, cx);
 5112            }
 5113            pane::Event::Remove { focus_on_pane } => {
 5114                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 5115            }
 5116            pane::Event::ActivateItem {
 5117                local,
 5118                focus_changed,
 5119            } => {
 5120                window.invalidate_character_coordinates();
 5121
 5122                pane.update(cx, |pane, _| {
 5123                    pane.track_alternate_file_items();
 5124                });
 5125                if *local {
 5126                    self.unfollow_in_pane(pane, window, cx);
 5127                }
 5128                serialize_workspace = *focus_changed || pane != self.active_pane();
 5129                if pane == self.active_pane() {
 5130                    self.active_item_path_changed(*focus_changed, window, cx);
 5131                    self.update_active_view_for_followers(window, cx);
 5132                } else if *local {
 5133                    self.set_active_pane(pane, window, cx);
 5134                }
 5135            }
 5136            pane::Event::UserSavedItem { item, save_intent } => {
 5137                cx.emit(Event::UserSavedItem {
 5138                    pane: pane.downgrade(),
 5139                    item: item.boxed_clone(),
 5140                    save_intent: *save_intent,
 5141                });
 5142                serialize_workspace = false;
 5143            }
 5144            pane::Event::ChangeItemTitle => {
 5145                if *pane == self.active_pane {
 5146                    self.active_item_path_changed(false, window, cx);
 5147                }
 5148                serialize_workspace = false;
 5149            }
 5150            pane::Event::RemovedItem { item } => {
 5151                cx.emit(Event::ActiveItemChanged);
 5152                self.update_window_edited(window, cx);
 5153                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 5154                    && entry.get().entity_id() == pane.entity_id()
 5155                {
 5156                    entry.remove();
 5157                }
 5158                cx.emit(Event::ItemRemoved {
 5159                    item_id: item.item_id(),
 5160                });
 5161            }
 5162            pane::Event::Focus => {
 5163                window.invalidate_character_coordinates();
 5164                self.handle_pane_focused(pane.clone(), window, cx);
 5165            }
 5166            pane::Event::ZoomIn => {
 5167                if *pane == self.active_pane {
 5168                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 5169                    if pane.read(cx).has_focus(window, cx) {
 5170                        self.zoomed = Some(pane.downgrade().into());
 5171                        self.zoomed_position = None;
 5172                        cx.emit(Event::ZoomChanged);
 5173                    }
 5174                    cx.notify();
 5175                }
 5176            }
 5177            pane::Event::ZoomOut => {
 5178                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 5179                if self.zoomed_position.is_none() {
 5180                    self.zoomed = None;
 5181                    cx.emit(Event::ZoomChanged);
 5182                }
 5183                cx.notify();
 5184            }
 5185            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 5186        }
 5187
 5188        if serialize_workspace {
 5189            self.serialize_workspace(window, cx);
 5190        }
 5191    }
 5192
 5193    pub fn unfollow_in_pane(
 5194        &mut self,
 5195        pane: &Entity<Pane>,
 5196        window: &mut Window,
 5197        cx: &mut Context<Workspace>,
 5198    ) -> Option<CollaboratorId> {
 5199        let leader_id = self.leader_for_pane(pane)?;
 5200        self.unfollow(leader_id, window, cx);
 5201        Some(leader_id)
 5202    }
 5203
 5204    pub fn split_pane(
 5205        &mut self,
 5206        pane_to_split: Entity<Pane>,
 5207        split_direction: SplitDirection,
 5208        window: &mut Window,
 5209        cx: &mut Context<Self>,
 5210    ) -> Entity<Pane> {
 5211        let new_pane = self.add_pane(window, cx);
 5212        self.center
 5213            .split(&pane_to_split, &new_pane, split_direction, cx);
 5214        cx.notify();
 5215        new_pane
 5216    }
 5217
 5218    pub fn split_and_move(
 5219        &mut self,
 5220        pane: Entity<Pane>,
 5221        direction: SplitDirection,
 5222        window: &mut Window,
 5223        cx: &mut Context<Self>,
 5224    ) {
 5225        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 5226            return;
 5227        };
 5228        let new_pane = self.add_pane(window, cx);
 5229        new_pane.update(cx, |pane, cx| {
 5230            pane.add_item(item, true, true, None, window, cx)
 5231        });
 5232        self.center.split(&pane, &new_pane, direction, cx);
 5233        cx.notify();
 5234    }
 5235
 5236    pub fn split_and_clone(
 5237        &mut self,
 5238        pane: Entity<Pane>,
 5239        direction: SplitDirection,
 5240        window: &mut Window,
 5241        cx: &mut Context<Self>,
 5242    ) -> Task<Option<Entity<Pane>>> {
 5243        let Some(item) = pane.read(cx).active_item() else {
 5244            return Task::ready(None);
 5245        };
 5246        if !item.can_split(cx) {
 5247            return Task::ready(None);
 5248        }
 5249        let task = item.clone_on_split(self.database_id(), window, cx);
 5250        cx.spawn_in(window, async move |this, cx| {
 5251            if let Some(clone) = task.await {
 5252                this.update_in(cx, |this, window, cx| {
 5253                    let new_pane = this.add_pane(window, cx);
 5254                    let nav_history = pane.read(cx).fork_nav_history();
 5255                    new_pane.update(cx, |pane, cx| {
 5256                        pane.set_nav_history(nav_history, cx);
 5257                        pane.add_item(clone, true, true, None, window, cx)
 5258                    });
 5259                    this.center.split(&pane, &new_pane, direction, cx);
 5260                    cx.notify();
 5261                    new_pane
 5262                })
 5263                .ok()
 5264            } else {
 5265                None
 5266            }
 5267        })
 5268    }
 5269
 5270    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5271        let active_item = self.active_pane.read(cx).active_item();
 5272        for pane in &self.panes {
 5273            join_pane_into_active(&self.active_pane, pane, window, cx);
 5274        }
 5275        if let Some(active_item) = active_item {
 5276            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5277        }
 5278        cx.notify();
 5279    }
 5280
 5281    pub fn join_pane_into_next(
 5282        &mut self,
 5283        pane: Entity<Pane>,
 5284        window: &mut Window,
 5285        cx: &mut Context<Self>,
 5286    ) {
 5287        let next_pane = self
 5288            .find_pane_in_direction(SplitDirection::Right, cx)
 5289            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5290            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5291            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5292        let Some(next_pane) = next_pane else {
 5293            return;
 5294        };
 5295        move_all_items(&pane, &next_pane, window, cx);
 5296        cx.notify();
 5297    }
 5298
 5299    fn remove_pane(
 5300        &mut self,
 5301        pane: Entity<Pane>,
 5302        focus_on: Option<Entity<Pane>>,
 5303        window: &mut Window,
 5304        cx: &mut Context<Self>,
 5305    ) {
 5306        if self.center.remove(&pane, cx).unwrap() {
 5307            self.force_remove_pane(&pane, &focus_on, window, cx);
 5308            self.unfollow_in_pane(&pane, window, cx);
 5309            self.last_leaders_by_pane.remove(&pane.downgrade());
 5310            for removed_item in pane.read(cx).items() {
 5311                self.panes_by_item.remove(&removed_item.item_id());
 5312            }
 5313
 5314            cx.notify();
 5315        } else {
 5316            self.active_item_path_changed(true, window, cx);
 5317        }
 5318        cx.emit(Event::PaneRemoved);
 5319    }
 5320
 5321    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5322        &mut self.panes
 5323    }
 5324
 5325    pub fn panes(&self) -> &[Entity<Pane>] {
 5326        &self.panes
 5327    }
 5328
 5329    pub fn active_pane(&self) -> &Entity<Pane> {
 5330        &self.active_pane
 5331    }
 5332
 5333    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5334        for dock in self.all_docks() {
 5335            if dock.focus_handle(cx).contains_focused(window, cx)
 5336                && let Some(pane) = dock
 5337                    .read(cx)
 5338                    .active_panel()
 5339                    .and_then(|panel| panel.pane(cx))
 5340            {
 5341                return pane;
 5342            }
 5343        }
 5344        self.active_pane().clone()
 5345    }
 5346
 5347    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5348        self.find_pane_in_direction(SplitDirection::Right, cx)
 5349            .unwrap_or_else(|| {
 5350                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5351            })
 5352    }
 5353
 5354    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5355        self.pane_for_item_id(handle.item_id())
 5356    }
 5357
 5358    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5359        let weak_pane = self.panes_by_item.get(&item_id)?;
 5360        weak_pane.upgrade()
 5361    }
 5362
 5363    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5364        self.panes
 5365            .iter()
 5366            .find(|pane| pane.entity_id() == entity_id)
 5367            .cloned()
 5368    }
 5369
 5370    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5371        self.follower_states.retain(|leader_id, state| {
 5372            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5373                for item in state.items_by_leader_view_id.values() {
 5374                    item.view.set_leader_id(None, window, cx);
 5375                }
 5376                false
 5377            } else {
 5378                true
 5379            }
 5380        });
 5381        cx.notify();
 5382    }
 5383
 5384    pub fn start_following(
 5385        &mut self,
 5386        leader_id: impl Into<CollaboratorId>,
 5387        window: &mut Window,
 5388        cx: &mut Context<Self>,
 5389    ) -> Option<Task<Result<()>>> {
 5390        let leader_id = leader_id.into();
 5391        let pane = self.active_pane().clone();
 5392
 5393        self.last_leaders_by_pane
 5394            .insert(pane.downgrade(), leader_id);
 5395        self.unfollow(leader_id, window, cx);
 5396        self.unfollow_in_pane(&pane, window, cx);
 5397        self.follower_states.insert(
 5398            leader_id,
 5399            FollowerState {
 5400                center_pane: pane.clone(),
 5401                dock_pane: None,
 5402                active_view_id: None,
 5403                items_by_leader_view_id: Default::default(),
 5404            },
 5405        );
 5406        cx.notify();
 5407
 5408        match leader_id {
 5409            CollaboratorId::PeerId(leader_peer_id) => {
 5410                let room_id = self.active_call()?.room_id(cx)?;
 5411                let project_id = self.project.read(cx).remote_id();
 5412                let request = self.app_state.client.request(proto::Follow {
 5413                    room_id,
 5414                    project_id,
 5415                    leader_id: Some(leader_peer_id),
 5416                });
 5417
 5418                Some(cx.spawn_in(window, async move |this, cx| {
 5419                    let response = request.await?;
 5420                    this.update(cx, |this, _| {
 5421                        let state = this
 5422                            .follower_states
 5423                            .get_mut(&leader_id)
 5424                            .context("following interrupted")?;
 5425                        state.active_view_id = response
 5426                            .active_view
 5427                            .as_ref()
 5428                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5429                        anyhow::Ok(())
 5430                    })??;
 5431                    if let Some(view) = response.active_view {
 5432                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5433                    }
 5434                    this.update_in(cx, |this, window, cx| {
 5435                        this.leader_updated(leader_id, window, cx)
 5436                    })?;
 5437                    Ok(())
 5438                }))
 5439            }
 5440            CollaboratorId::Agent => {
 5441                self.leader_updated(leader_id, window, cx)?;
 5442                Some(Task::ready(Ok(())))
 5443            }
 5444        }
 5445    }
 5446
 5447    pub fn follow_next_collaborator(
 5448        &mut self,
 5449        _: &FollowNextCollaborator,
 5450        window: &mut Window,
 5451        cx: &mut Context<Self>,
 5452    ) {
 5453        let collaborators = self.project.read(cx).collaborators();
 5454        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5455            let mut collaborators = collaborators.keys().copied();
 5456            for peer_id in collaborators.by_ref() {
 5457                if CollaboratorId::PeerId(peer_id) == leader_id {
 5458                    break;
 5459                }
 5460            }
 5461            collaborators.next().map(CollaboratorId::PeerId)
 5462        } else if let Some(last_leader_id) =
 5463            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5464        {
 5465            match last_leader_id {
 5466                CollaboratorId::PeerId(peer_id) => {
 5467                    if collaborators.contains_key(peer_id) {
 5468                        Some(*last_leader_id)
 5469                    } else {
 5470                        None
 5471                    }
 5472                }
 5473                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5474            }
 5475        } else {
 5476            None
 5477        };
 5478
 5479        let pane = self.active_pane.clone();
 5480        let Some(leader_id) = next_leader_id.or_else(|| {
 5481            Some(CollaboratorId::PeerId(
 5482                collaborators.keys().copied().next()?,
 5483            ))
 5484        }) else {
 5485            return;
 5486        };
 5487        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5488            return;
 5489        }
 5490        if let Some(task) = self.start_following(leader_id, window, cx) {
 5491            task.detach_and_log_err(cx)
 5492        }
 5493    }
 5494
 5495    pub fn follow(
 5496        &mut self,
 5497        leader_id: impl Into<CollaboratorId>,
 5498        window: &mut Window,
 5499        cx: &mut Context<Self>,
 5500    ) {
 5501        let leader_id = leader_id.into();
 5502
 5503        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5504            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5505                return;
 5506            };
 5507            let Some(remote_participant) =
 5508                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5509            else {
 5510                return;
 5511            };
 5512
 5513            let project = self.project.read(cx);
 5514
 5515            let other_project_id = match remote_participant.location {
 5516                ParticipantLocation::External => None,
 5517                ParticipantLocation::UnsharedProject => None,
 5518                ParticipantLocation::SharedProject { project_id } => {
 5519                    if Some(project_id) == project.remote_id() {
 5520                        None
 5521                    } else {
 5522                        Some(project_id)
 5523                    }
 5524                }
 5525            };
 5526
 5527            // if they are active in another project, follow there.
 5528            if let Some(project_id) = other_project_id {
 5529                let app_state = self.app_state.clone();
 5530                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5531                    .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
 5532                        Some(format!("{error:#}"))
 5533                    });
 5534            }
 5535        }
 5536
 5537        // if you're already following, find the right pane and focus it.
 5538        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5539            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5540
 5541            return;
 5542        }
 5543
 5544        // Otherwise, follow.
 5545        if let Some(task) = self.start_following(leader_id, window, cx) {
 5546            task.detach_and_log_err(cx)
 5547        }
 5548    }
 5549
 5550    pub fn unfollow(
 5551        &mut self,
 5552        leader_id: impl Into<CollaboratorId>,
 5553        window: &mut Window,
 5554        cx: &mut Context<Self>,
 5555    ) -> Option<()> {
 5556        cx.notify();
 5557
 5558        let leader_id = leader_id.into();
 5559        let state = self.follower_states.remove(&leader_id)?;
 5560        for (_, item) in state.items_by_leader_view_id {
 5561            item.view.set_leader_id(None, window, cx);
 5562        }
 5563
 5564        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5565            let project_id = self.project.read(cx).remote_id();
 5566            let room_id = self.active_call()?.room_id(cx)?;
 5567            self.app_state
 5568                .client
 5569                .send(proto::Unfollow {
 5570                    room_id,
 5571                    project_id,
 5572                    leader_id: Some(leader_peer_id),
 5573                })
 5574                .log_err();
 5575        }
 5576
 5577        Some(())
 5578    }
 5579
 5580    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5581        self.follower_states.contains_key(&id.into())
 5582    }
 5583
 5584    fn active_item_path_changed(
 5585        &mut self,
 5586        focus_changed: bool,
 5587        window: &mut Window,
 5588        cx: &mut Context<Self>,
 5589    ) {
 5590        cx.emit(Event::ActiveItemChanged);
 5591        let active_entry = self.active_project_path(cx);
 5592        self.project.update(cx, |project, cx| {
 5593            project.set_active_path(active_entry.clone(), cx)
 5594        });
 5595
 5596        if focus_changed && let Some(project_path) = &active_entry {
 5597            let git_store_entity = self.project.read(cx).git_store().clone();
 5598            git_store_entity.update(cx, |git_store, cx| {
 5599                git_store.set_active_repo_for_path(project_path, cx);
 5600            });
 5601        }
 5602
 5603        self.update_window_title(window, cx);
 5604    }
 5605
 5606    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5607        let project = self.project().read(cx);
 5608        let mut title = String::new();
 5609
 5610        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5611            let name = {
 5612                let settings_location = SettingsLocation {
 5613                    worktree_id: worktree.read(cx).id(),
 5614                    path: RelPath::empty(),
 5615                };
 5616
 5617                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5618                match &settings.project_name {
 5619                    Some(name) => name.as_str(),
 5620                    None => worktree.read(cx).root_name_str(),
 5621                }
 5622            };
 5623            if i > 0 {
 5624                title.push_str(", ");
 5625            }
 5626            title.push_str(name);
 5627        }
 5628
 5629        if title.is_empty() {
 5630            title = "empty project".to_string();
 5631        }
 5632
 5633        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5634            let filename = path.path.file_name().or_else(|| {
 5635                Some(
 5636                    project
 5637                        .worktree_for_id(path.worktree_id, cx)?
 5638                        .read(cx)
 5639                        .root_name_str(),
 5640                )
 5641            });
 5642
 5643            if let Some(filename) = filename {
 5644                title.push_str("");
 5645                title.push_str(filename.as_ref());
 5646            }
 5647        }
 5648
 5649        if project.is_via_collab() {
 5650            title.push_str("");
 5651        } else if project.is_shared() {
 5652            title.push_str("");
 5653        }
 5654
 5655        if let Some(last_title) = self.last_window_title.as_ref()
 5656            && &title == last_title
 5657        {
 5658            return;
 5659        }
 5660        window.set_window_title(&title);
 5661        SystemWindowTabController::update_tab_title(
 5662            cx,
 5663            window.window_handle().window_id(),
 5664            SharedString::from(&title),
 5665        );
 5666        self.last_window_title = Some(title);
 5667    }
 5668
 5669    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5670        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5671        if is_edited != self.window_edited {
 5672            self.window_edited = is_edited;
 5673            window.set_window_edited(self.window_edited)
 5674        }
 5675    }
 5676
 5677    fn update_item_dirty_state(
 5678        &mut self,
 5679        item: &dyn ItemHandle,
 5680        window: &mut Window,
 5681        cx: &mut App,
 5682    ) {
 5683        let is_dirty = item.is_dirty(cx);
 5684        let item_id = item.item_id();
 5685        let was_dirty = self.dirty_items.contains_key(&item_id);
 5686        if is_dirty == was_dirty {
 5687            return;
 5688        }
 5689        if was_dirty {
 5690            self.dirty_items.remove(&item_id);
 5691            self.update_window_edited(window, cx);
 5692            return;
 5693        }
 5694
 5695        let workspace = self.weak_handle();
 5696        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5697            return;
 5698        };
 5699        let on_release_callback = Box::new(move |cx: &mut App| {
 5700            window_handle
 5701                .update(cx, |_, window, cx| {
 5702                    workspace
 5703                        .update(cx, |workspace, cx| {
 5704                            workspace.dirty_items.remove(&item_id);
 5705                            workspace.update_window_edited(window, cx)
 5706                        })
 5707                        .ok();
 5708                })
 5709                .ok();
 5710        });
 5711
 5712        let s = item.on_release(cx, on_release_callback);
 5713        self.dirty_items.insert(item_id, s);
 5714        self.update_window_edited(window, cx);
 5715    }
 5716
 5717    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5718        if self.notifications.is_empty() {
 5719            None
 5720        } else {
 5721            Some(
 5722                div()
 5723                    .absolute()
 5724                    .right_3()
 5725                    .bottom_3()
 5726                    .w_112()
 5727                    .h_full()
 5728                    .flex()
 5729                    .flex_col()
 5730                    .justify_end()
 5731                    .gap_2()
 5732                    .children(
 5733                        self.notifications
 5734                            .iter()
 5735                            .map(|(_, notification)| notification.clone().into_any()),
 5736                    ),
 5737            )
 5738        }
 5739    }
 5740
 5741    // RPC handlers
 5742
 5743    fn active_view_for_follower(
 5744        &self,
 5745        follower_project_id: Option<u64>,
 5746        window: &mut Window,
 5747        cx: &mut Context<Self>,
 5748    ) -> Option<proto::View> {
 5749        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5750        let item = item?;
 5751        let leader_id = self
 5752            .pane_for(&*item)
 5753            .and_then(|pane| self.leader_for_pane(&pane));
 5754        let leader_peer_id = match leader_id {
 5755            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5756            Some(CollaboratorId::Agent) | None => None,
 5757        };
 5758
 5759        let item_handle = item.to_followable_item_handle(cx)?;
 5760        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5761        let variant = item_handle.to_state_proto(window, cx)?;
 5762
 5763        if item_handle.is_project_item(window, cx)
 5764            && (follower_project_id.is_none()
 5765                || follower_project_id != self.project.read(cx).remote_id())
 5766        {
 5767            return None;
 5768        }
 5769
 5770        Some(proto::View {
 5771            id: id.to_proto(),
 5772            leader_id: leader_peer_id,
 5773            variant: Some(variant),
 5774            panel_id: panel_id.map(|id| id as i32),
 5775        })
 5776    }
 5777
 5778    fn handle_follow(
 5779        &mut self,
 5780        follower_project_id: Option<u64>,
 5781        window: &mut Window,
 5782        cx: &mut Context<Self>,
 5783    ) -> proto::FollowResponse {
 5784        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5785
 5786        cx.notify();
 5787        proto::FollowResponse {
 5788            views: active_view.iter().cloned().collect(),
 5789            active_view,
 5790        }
 5791    }
 5792
 5793    fn handle_update_followers(
 5794        &mut self,
 5795        leader_id: PeerId,
 5796        message: proto::UpdateFollowers,
 5797        _window: &mut Window,
 5798        _cx: &mut Context<Self>,
 5799    ) {
 5800        self.leader_updates_tx
 5801            .unbounded_send((leader_id, message))
 5802            .ok();
 5803    }
 5804
 5805    async fn process_leader_update(
 5806        this: &WeakEntity<Self>,
 5807        leader_id: PeerId,
 5808        update: proto::UpdateFollowers,
 5809        cx: &mut AsyncWindowContext,
 5810    ) -> Result<()> {
 5811        match update.variant.context("invalid update")? {
 5812            proto::update_followers::Variant::CreateView(view) => {
 5813                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5814                let should_add_view = this.update(cx, |this, _| {
 5815                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5816                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5817                    } else {
 5818                        anyhow::Ok(false)
 5819                    }
 5820                })??;
 5821
 5822                if should_add_view {
 5823                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5824                }
 5825            }
 5826            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5827                let should_add_view = this.update(cx, |this, _| {
 5828                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5829                        state.active_view_id = update_active_view
 5830                            .view
 5831                            .as_ref()
 5832                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5833
 5834                        if state.active_view_id.is_some_and(|view_id| {
 5835                            !state.items_by_leader_view_id.contains_key(&view_id)
 5836                        }) {
 5837                            anyhow::Ok(true)
 5838                        } else {
 5839                            anyhow::Ok(false)
 5840                        }
 5841                    } else {
 5842                        anyhow::Ok(false)
 5843                    }
 5844                })??;
 5845
 5846                if should_add_view && let Some(view) = update_active_view.view {
 5847                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5848                }
 5849            }
 5850            proto::update_followers::Variant::UpdateView(update_view) => {
 5851                let variant = update_view.variant.context("missing update view variant")?;
 5852                let id = update_view.id.context("missing update view id")?;
 5853                let mut tasks = Vec::new();
 5854                this.update_in(cx, |this, window, cx| {
 5855                    let project = this.project.clone();
 5856                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5857                        let view_id = ViewId::from_proto(id.clone())?;
 5858                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5859                            tasks.push(item.view.apply_update_proto(
 5860                                &project,
 5861                                variant.clone(),
 5862                                window,
 5863                                cx,
 5864                            ));
 5865                        }
 5866                    }
 5867                    anyhow::Ok(())
 5868                })??;
 5869                try_join_all(tasks).await.log_err();
 5870            }
 5871        }
 5872        this.update_in(cx, |this, window, cx| {
 5873            this.leader_updated(leader_id, window, cx)
 5874        })?;
 5875        Ok(())
 5876    }
 5877
 5878    async fn add_view_from_leader(
 5879        this: WeakEntity<Self>,
 5880        leader_id: PeerId,
 5881        view: &proto::View,
 5882        cx: &mut AsyncWindowContext,
 5883    ) -> Result<()> {
 5884        let this = this.upgrade().context("workspace dropped")?;
 5885
 5886        let Some(id) = view.id.clone() else {
 5887            anyhow::bail!("no id for view");
 5888        };
 5889        let id = ViewId::from_proto(id)?;
 5890        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5891
 5892        let pane = this.update(cx, |this, _cx| {
 5893            let state = this
 5894                .follower_states
 5895                .get(&leader_id.into())
 5896                .context("stopped following")?;
 5897            anyhow::Ok(state.pane().clone())
 5898        })?;
 5899        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5900            let client = this.read(cx).client().clone();
 5901            pane.items().find_map(|item| {
 5902                let item = item.to_followable_item_handle(cx)?;
 5903                if item.remote_id(&client, window, cx) == Some(id) {
 5904                    Some(item)
 5905                } else {
 5906                    None
 5907                }
 5908            })
 5909        })?;
 5910        let item = if let Some(existing_item) = existing_item {
 5911            existing_item
 5912        } else {
 5913            let variant = view.variant.clone();
 5914            anyhow::ensure!(variant.is_some(), "missing view variant");
 5915
 5916            let task = cx.update(|window, cx| {
 5917                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5918            })?;
 5919
 5920            let Some(task) = task else {
 5921                anyhow::bail!(
 5922                    "failed to construct view from leader (maybe from a different version of zed?)"
 5923                );
 5924            };
 5925
 5926            let mut new_item = task.await?;
 5927            pane.update_in(cx, |pane, window, cx| {
 5928                let mut item_to_remove = None;
 5929                for (ix, item) in pane.items().enumerate() {
 5930                    if let Some(item) = item.to_followable_item_handle(cx) {
 5931                        match new_item.dedup(item.as_ref(), window, cx) {
 5932                            Some(item::Dedup::KeepExisting) => {
 5933                                new_item =
 5934                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5935                                break;
 5936                            }
 5937                            Some(item::Dedup::ReplaceExisting) => {
 5938                                item_to_remove = Some((ix, item.item_id()));
 5939                                break;
 5940                            }
 5941                            None => {}
 5942                        }
 5943                    }
 5944                }
 5945
 5946                if let Some((ix, id)) = item_to_remove {
 5947                    pane.remove_item(id, false, false, window, cx);
 5948                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5949                }
 5950            })?;
 5951
 5952            new_item
 5953        };
 5954
 5955        this.update_in(cx, |this, window, cx| {
 5956            let state = this.follower_states.get_mut(&leader_id.into())?;
 5957            item.set_leader_id(Some(leader_id.into()), window, cx);
 5958            state.items_by_leader_view_id.insert(
 5959                id,
 5960                FollowerView {
 5961                    view: item,
 5962                    location: panel_id,
 5963                },
 5964            );
 5965
 5966            Some(())
 5967        })
 5968        .context("no follower state")?;
 5969
 5970        Ok(())
 5971    }
 5972
 5973    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5974        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5975            return;
 5976        };
 5977
 5978        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5979            let buffer_entity_id = agent_location.buffer.entity_id();
 5980            let view_id = ViewId {
 5981                creator: CollaboratorId::Agent,
 5982                id: buffer_entity_id.as_u64(),
 5983            };
 5984            follower_state.active_view_id = Some(view_id);
 5985
 5986            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5987                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5988                hash_map::Entry::Vacant(entry) => {
 5989                    let existing_view =
 5990                        follower_state
 5991                            .center_pane
 5992                            .read(cx)
 5993                            .items()
 5994                            .find_map(|item| {
 5995                                let item = item.to_followable_item_handle(cx)?;
 5996                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5997                                    && item.project_item_model_ids(cx).as_slice()
 5998                                        == [buffer_entity_id]
 5999                                {
 6000                                    Some(item)
 6001                                } else {
 6002                                    None
 6003                                }
 6004                            });
 6005                    let view = existing_view.or_else(|| {
 6006                        agent_location.buffer.upgrade().and_then(|buffer| {
 6007                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 6008                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 6009                            })?
 6010                            .to_followable_item_handle(cx)
 6011                        })
 6012                    });
 6013
 6014                    view.map(|view| {
 6015                        entry.insert(FollowerView {
 6016                            view,
 6017                            location: None,
 6018                        })
 6019                    })
 6020                }
 6021            };
 6022
 6023            if let Some(item) = item {
 6024                item.view
 6025                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 6026                item.view
 6027                    .update_agent_location(agent_location.position, window, cx);
 6028            }
 6029        } else {
 6030            follower_state.active_view_id = None;
 6031        }
 6032
 6033        self.leader_updated(CollaboratorId::Agent, window, cx);
 6034    }
 6035
 6036    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 6037        let mut is_project_item = true;
 6038        let mut update = proto::UpdateActiveView::default();
 6039        if window.is_window_active() {
 6040            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 6041
 6042            if let Some(item) = active_item
 6043                && item.item_focus_handle(cx).contains_focused(window, cx)
 6044            {
 6045                let leader_id = self
 6046                    .pane_for(&*item)
 6047                    .and_then(|pane| self.leader_for_pane(&pane));
 6048                let leader_peer_id = match leader_id {
 6049                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 6050                    Some(CollaboratorId::Agent) | None => None,
 6051                };
 6052
 6053                if let Some(item) = item.to_followable_item_handle(cx) {
 6054                    let id = item
 6055                        .remote_id(&self.app_state.client, window, cx)
 6056                        .map(|id| id.to_proto());
 6057
 6058                    if let Some(id) = id
 6059                        && let Some(variant) = item.to_state_proto(window, cx)
 6060                    {
 6061                        let view = Some(proto::View {
 6062                            id,
 6063                            leader_id: leader_peer_id,
 6064                            variant: Some(variant),
 6065                            panel_id: panel_id.map(|id| id as i32),
 6066                        });
 6067
 6068                        is_project_item = item.is_project_item(window, cx);
 6069                        update = proto::UpdateActiveView { view };
 6070                    };
 6071                }
 6072            }
 6073        }
 6074
 6075        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 6076        if active_view_id != self.last_active_view_id.as_ref() {
 6077            self.last_active_view_id = active_view_id.cloned();
 6078            self.update_followers(
 6079                is_project_item,
 6080                proto::update_followers::Variant::UpdateActiveView(update),
 6081                window,
 6082                cx,
 6083            );
 6084        }
 6085    }
 6086
 6087    fn active_item_for_followers(
 6088        &self,
 6089        window: &mut Window,
 6090        cx: &mut App,
 6091    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 6092        let mut active_item = None;
 6093        let mut panel_id = None;
 6094        for dock in self.all_docks() {
 6095            if dock.focus_handle(cx).contains_focused(window, cx)
 6096                && let Some(panel) = dock.read(cx).active_panel()
 6097                && let Some(pane) = panel.pane(cx)
 6098                && let Some(item) = pane.read(cx).active_item()
 6099            {
 6100                active_item = Some(item);
 6101                panel_id = panel.remote_id();
 6102                break;
 6103            }
 6104        }
 6105
 6106        if active_item.is_none() {
 6107            active_item = self.active_pane().read(cx).active_item();
 6108        }
 6109        (active_item, panel_id)
 6110    }
 6111
 6112    fn update_followers(
 6113        &self,
 6114        project_only: bool,
 6115        update: proto::update_followers::Variant,
 6116        _: &mut Window,
 6117        cx: &mut App,
 6118    ) -> Option<()> {
 6119        // If this update only applies to for followers in the current project,
 6120        // then skip it unless this project is shared. If it applies to all
 6121        // followers, regardless of project, then set `project_id` to none,
 6122        // indicating that it goes to all followers.
 6123        let project_id = if project_only {
 6124            Some(self.project.read(cx).remote_id()?)
 6125        } else {
 6126            None
 6127        };
 6128        self.app_state().workspace_store.update(cx, |store, cx| {
 6129            store.update_followers(project_id, update, cx)
 6130        })
 6131    }
 6132
 6133    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 6134        self.follower_states.iter().find_map(|(leader_id, state)| {
 6135            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 6136                Some(*leader_id)
 6137            } else {
 6138                None
 6139            }
 6140        })
 6141    }
 6142
 6143    fn leader_updated(
 6144        &mut self,
 6145        leader_id: impl Into<CollaboratorId>,
 6146        window: &mut Window,
 6147        cx: &mut Context<Self>,
 6148    ) -> Option<Box<dyn ItemHandle>> {
 6149        cx.notify();
 6150
 6151        let leader_id = leader_id.into();
 6152        let (panel_id, item) = match leader_id {
 6153            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 6154            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 6155        };
 6156
 6157        let state = self.follower_states.get(&leader_id)?;
 6158        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 6159        let pane;
 6160        if let Some(panel_id) = panel_id {
 6161            pane = self
 6162                .activate_panel_for_proto_id(panel_id, window, cx)?
 6163                .pane(cx)?;
 6164            let state = self.follower_states.get_mut(&leader_id)?;
 6165            state.dock_pane = Some(pane.clone());
 6166        } else {
 6167            pane = state.center_pane.clone();
 6168            let state = self.follower_states.get_mut(&leader_id)?;
 6169            if let Some(dock_pane) = state.dock_pane.take() {
 6170                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 6171            }
 6172        }
 6173
 6174        pane.update(cx, |pane, cx| {
 6175            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 6176            if let Some(index) = pane.index_for_item(item.as_ref()) {
 6177                pane.activate_item(index, false, false, window, cx);
 6178            } else {
 6179                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 6180            }
 6181
 6182            if focus_active_item {
 6183                pane.focus_active_item(window, cx)
 6184            }
 6185        });
 6186
 6187        Some(item)
 6188    }
 6189
 6190    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 6191        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 6192        let active_view_id = state.active_view_id?;
 6193        Some(
 6194            state
 6195                .items_by_leader_view_id
 6196                .get(&active_view_id)?
 6197                .view
 6198                .boxed_clone(),
 6199        )
 6200    }
 6201
 6202    fn active_item_for_peer(
 6203        &self,
 6204        peer_id: PeerId,
 6205        window: &mut Window,
 6206        cx: &mut Context<Self>,
 6207    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 6208        let call = self.active_call()?;
 6209        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 6210        let leader_in_this_app;
 6211        let leader_in_this_project;
 6212        match participant.location {
 6213            ParticipantLocation::SharedProject { project_id } => {
 6214                leader_in_this_app = true;
 6215                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 6216            }
 6217            ParticipantLocation::UnsharedProject => {
 6218                leader_in_this_app = true;
 6219                leader_in_this_project = false;
 6220            }
 6221            ParticipantLocation::External => {
 6222                leader_in_this_app = false;
 6223                leader_in_this_project = false;
 6224            }
 6225        };
 6226        let state = self.follower_states.get(&peer_id.into())?;
 6227        let mut item_to_activate = None;
 6228        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 6229            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 6230                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 6231            {
 6232                item_to_activate = Some((item.location, item.view.boxed_clone()));
 6233            }
 6234        } else if let Some(shared_screen) =
 6235            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 6236        {
 6237            item_to_activate = Some((None, Box::new(shared_screen)));
 6238        }
 6239        item_to_activate
 6240    }
 6241
 6242    fn shared_screen_for_peer(
 6243        &self,
 6244        peer_id: PeerId,
 6245        pane: &Entity<Pane>,
 6246        window: &mut Window,
 6247        cx: &mut App,
 6248    ) -> Option<Entity<SharedScreen>> {
 6249        self.active_call()?
 6250            .create_shared_screen(peer_id, pane, window, cx)
 6251    }
 6252
 6253    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6254        if window.is_window_active() {
 6255            self.update_active_view_for_followers(window, cx);
 6256
 6257            if let Some(database_id) = self.database_id {
 6258                let db = WorkspaceDb::global(cx);
 6259                cx.background_spawn(async move { db.update_timestamp(database_id).await })
 6260                    .detach();
 6261            }
 6262        } else {
 6263            for pane in &self.panes {
 6264                pane.update(cx, |pane, cx| {
 6265                    if let Some(item) = pane.active_item() {
 6266                        item.workspace_deactivated(window, cx);
 6267                    }
 6268                    for item in pane.items() {
 6269                        if matches!(
 6270                            item.workspace_settings(cx).autosave,
 6271                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6272                        ) {
 6273                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6274                                .detach_and_log_err(cx);
 6275                        }
 6276                    }
 6277                });
 6278            }
 6279        }
 6280    }
 6281
 6282    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6283        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6284    }
 6285
 6286    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6287        self.active_call.as_ref().map(|(call, _)| call.clone())
 6288    }
 6289
 6290    fn on_active_call_event(
 6291        &mut self,
 6292        event: &ActiveCallEvent,
 6293        window: &mut Window,
 6294        cx: &mut Context<Self>,
 6295    ) {
 6296        match event {
 6297            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6298            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6299                self.leader_updated(participant_id, window, cx);
 6300            }
 6301        }
 6302    }
 6303
 6304    pub fn database_id(&self) -> Option<WorkspaceId> {
 6305        self.database_id
 6306    }
 6307
 6308    #[cfg(any(test, feature = "test-support"))]
 6309    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6310        self.database_id = Some(id);
 6311    }
 6312
 6313    pub fn session_id(&self) -> Option<String> {
 6314        self.session_id.clone()
 6315    }
 6316
 6317    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6318        let Some(display) = window.display(cx) else {
 6319            return Task::ready(());
 6320        };
 6321        let Ok(display_uuid) = display.uuid() else {
 6322            return Task::ready(());
 6323        };
 6324
 6325        let window_bounds = window.inner_window_bounds();
 6326        let database_id = self.database_id;
 6327        let has_paths = !self.root_paths(cx).is_empty();
 6328        let db = WorkspaceDb::global(cx);
 6329        let kvp = db::kvp::KeyValueStore::global(cx);
 6330
 6331        cx.background_executor().spawn(async move {
 6332            if !has_paths {
 6333                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6334                    .await
 6335                    .log_err();
 6336            }
 6337            if let Some(database_id) = database_id {
 6338                db.set_window_open_status(
 6339                    database_id,
 6340                    SerializedWindowBounds(window_bounds),
 6341                    display_uuid,
 6342                )
 6343                .await
 6344                .log_err();
 6345            } else {
 6346                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6347                    .await
 6348                    .log_err();
 6349            }
 6350        })
 6351    }
 6352
 6353    /// Bypass the 200ms serialization throttle and write workspace state to
 6354    /// the DB immediately. Returns a task the caller can await to ensure the
 6355    /// write completes. Used by the quit handler so the most recent state
 6356    /// isn't lost to a pending throttle timer when the process exits.
 6357    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6358        self._schedule_serialize_workspace.take();
 6359        self._serialize_workspace_task.take();
 6360        self.bounds_save_task_queued.take();
 6361
 6362        let bounds_task = self.save_window_bounds(window, cx);
 6363        let serialize_task = self.serialize_workspace_internal(window, cx);
 6364        cx.spawn(async move |_| {
 6365            bounds_task.await;
 6366            serialize_task.await;
 6367        })
 6368    }
 6369
 6370    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6371        let project = self.project().read(cx);
 6372        project
 6373            .visible_worktrees(cx)
 6374            .map(|worktree| worktree.read(cx).abs_path())
 6375            .collect::<Vec<_>>()
 6376    }
 6377
 6378    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6379        match member {
 6380            Member::Axis(PaneAxis { members, .. }) => {
 6381                for child in members.iter() {
 6382                    self.remove_panes(child.clone(), window, cx)
 6383                }
 6384            }
 6385            Member::Pane(pane) => {
 6386                self.force_remove_pane(&pane, &None, window, cx);
 6387            }
 6388        }
 6389    }
 6390
 6391    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6392        self.session_id.take();
 6393        self.serialize_workspace_internal(window, cx)
 6394    }
 6395
 6396    fn force_remove_pane(
 6397        &mut self,
 6398        pane: &Entity<Pane>,
 6399        focus_on: &Option<Entity<Pane>>,
 6400        window: &mut Window,
 6401        cx: &mut Context<Workspace>,
 6402    ) {
 6403        self.panes.retain(|p| p != pane);
 6404        if let Some(focus_on) = focus_on {
 6405            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6406        } else if self.active_pane() == pane {
 6407            self.panes
 6408                .last()
 6409                .unwrap()
 6410                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6411        }
 6412        if self.last_active_center_pane == Some(pane.downgrade()) {
 6413            self.last_active_center_pane = None;
 6414        }
 6415        cx.notify();
 6416    }
 6417
 6418    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6419        if self._schedule_serialize_workspace.is_none() {
 6420            self._schedule_serialize_workspace =
 6421                Some(cx.spawn_in(window, async move |this, cx| {
 6422                    cx.background_executor()
 6423                        .timer(SERIALIZATION_THROTTLE_TIME)
 6424                        .await;
 6425                    this.update_in(cx, |this, window, cx| {
 6426                        this._serialize_workspace_task =
 6427                            Some(this.serialize_workspace_internal(window, cx));
 6428                        this._schedule_serialize_workspace.take();
 6429                    })
 6430                    .log_err();
 6431                }));
 6432        }
 6433    }
 6434
 6435    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6436        let Some(database_id) = self.database_id() else {
 6437            return Task::ready(());
 6438        };
 6439
 6440        fn serialize_pane_handle(
 6441            pane_handle: &Entity<Pane>,
 6442            window: &mut Window,
 6443            cx: &mut App,
 6444        ) -> SerializedPane {
 6445            let (items, active, pinned_count) = {
 6446                let pane = pane_handle.read(cx);
 6447                let active_item_id = pane.active_item().map(|item| item.item_id());
 6448                (
 6449                    pane.items()
 6450                        .filter_map(|handle| {
 6451                            let handle = handle.to_serializable_item_handle(cx)?;
 6452
 6453                            Some(SerializedItem {
 6454                                kind: Arc::from(handle.serialized_item_kind()),
 6455                                item_id: handle.item_id().as_u64(),
 6456                                active: Some(handle.item_id()) == active_item_id,
 6457                                preview: pane.is_active_preview_item(handle.item_id()),
 6458                            })
 6459                        })
 6460                        .collect::<Vec<_>>(),
 6461                    pane.has_focus(window, cx),
 6462                    pane.pinned_count(),
 6463                )
 6464            };
 6465
 6466            SerializedPane::new(items, active, pinned_count)
 6467        }
 6468
 6469        fn build_serialized_pane_group(
 6470            pane_group: &Member,
 6471            window: &mut Window,
 6472            cx: &mut App,
 6473        ) -> SerializedPaneGroup {
 6474            match pane_group {
 6475                Member::Axis(PaneAxis {
 6476                    axis,
 6477                    members,
 6478                    flexes,
 6479                    bounding_boxes: _,
 6480                }) => SerializedPaneGroup::Group {
 6481                    axis: SerializedAxis(*axis),
 6482                    children: members
 6483                        .iter()
 6484                        .map(|member| build_serialized_pane_group(member, window, cx))
 6485                        .collect::<Vec<_>>(),
 6486                    flexes: Some(flexes.lock().clone()),
 6487                },
 6488                Member::Pane(pane_handle) => {
 6489                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6490                }
 6491            }
 6492        }
 6493
 6494        fn build_serialized_docks(
 6495            this: &Workspace,
 6496            window: &mut Window,
 6497            cx: &mut App,
 6498        ) -> DockStructure {
 6499            this.capture_dock_state(window, cx)
 6500        }
 6501
 6502        match self.workspace_location(cx) {
 6503            WorkspaceLocation::Location(location, paths) => {
 6504                let breakpoints = self.project.update(cx, |project, cx| {
 6505                    project
 6506                        .breakpoint_store()
 6507                        .read(cx)
 6508                        .all_source_breakpoints(cx)
 6509                });
 6510                let user_toolchains = self
 6511                    .project
 6512                    .read(cx)
 6513                    .user_toolchains(cx)
 6514                    .unwrap_or_default();
 6515
 6516                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6517                let docks = build_serialized_docks(self, window, cx);
 6518                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6519
 6520                let serialized_workspace = SerializedWorkspace {
 6521                    id: database_id,
 6522                    location,
 6523                    paths,
 6524                    center_group,
 6525                    window_bounds,
 6526                    display: Default::default(),
 6527                    docks,
 6528                    centered_layout: self.centered_layout,
 6529                    session_id: self.session_id.clone(),
 6530                    breakpoints,
 6531                    window_id: Some(window.window_handle().window_id().as_u64()),
 6532                    user_toolchains,
 6533                };
 6534
 6535                let db = WorkspaceDb::global(cx);
 6536                window.spawn(cx, async move |_| {
 6537                    db.save_workspace(serialized_workspace).await;
 6538                })
 6539            }
 6540            WorkspaceLocation::DetachFromSession => {
 6541                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6542                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6543                // Save dock state for empty local workspaces
 6544                let docks = build_serialized_docks(self, window, cx);
 6545                let db = WorkspaceDb::global(cx);
 6546                let kvp = db::kvp::KeyValueStore::global(cx);
 6547                window.spawn(cx, async move |_| {
 6548                    db.set_window_open_status(
 6549                        database_id,
 6550                        window_bounds,
 6551                        display.unwrap_or_default(),
 6552                    )
 6553                    .await
 6554                    .log_err();
 6555                    db.set_session_id(database_id, None).await.log_err();
 6556                    persistence::write_default_dock_state(&kvp, docks)
 6557                        .await
 6558                        .log_err();
 6559                })
 6560            }
 6561            WorkspaceLocation::None => {
 6562                // Save dock state for empty non-local workspaces
 6563                let docks = build_serialized_docks(self, window, cx);
 6564                let kvp = db::kvp::KeyValueStore::global(cx);
 6565                window.spawn(cx, async move |_| {
 6566                    persistence::write_default_dock_state(&kvp, docks)
 6567                        .await
 6568                        .log_err();
 6569                })
 6570            }
 6571        }
 6572    }
 6573
 6574    fn has_any_items_open(&self, cx: &App) -> bool {
 6575        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6576    }
 6577
 6578    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6579        let paths = PathList::new(&self.root_paths(cx));
 6580        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6581            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6582        } else if self.project.read(cx).is_local() {
 6583            if !paths.is_empty() || self.has_any_items_open(cx) {
 6584                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6585            } else {
 6586                WorkspaceLocation::DetachFromSession
 6587            }
 6588        } else {
 6589            WorkspaceLocation::None
 6590        }
 6591    }
 6592
 6593    fn update_history(&self, cx: &mut App) {
 6594        let Some(id) = self.database_id() else {
 6595            return;
 6596        };
 6597        if !self.project.read(cx).is_local() {
 6598            return;
 6599        }
 6600        if let Some(manager) = HistoryManager::global(cx) {
 6601            let paths = PathList::new(&self.root_paths(cx));
 6602            manager.update(cx, |this, cx| {
 6603                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6604            });
 6605        }
 6606    }
 6607
 6608    async fn serialize_items(
 6609        this: &WeakEntity<Self>,
 6610        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6611        cx: &mut AsyncWindowContext,
 6612    ) -> Result<()> {
 6613        const CHUNK_SIZE: usize = 200;
 6614
 6615        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6616
 6617        while let Some(items_received) = serializable_items.next().await {
 6618            let unique_items =
 6619                items_received
 6620                    .into_iter()
 6621                    .fold(HashMap::default(), |mut acc, item| {
 6622                        acc.entry(item.item_id()).or_insert(item);
 6623                        acc
 6624                    });
 6625
 6626            // We use into_iter() here so that the references to the items are moved into
 6627            // the tasks and not kept alive while we're sleeping.
 6628            for (_, item) in unique_items.into_iter() {
 6629                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6630                    item.serialize(workspace, false, window, cx)
 6631                }) {
 6632                    cx.background_spawn(async move { task.await.log_err() })
 6633                        .detach();
 6634                }
 6635            }
 6636
 6637            cx.background_executor()
 6638                .timer(SERIALIZATION_THROTTLE_TIME)
 6639                .await;
 6640        }
 6641
 6642        Ok(())
 6643    }
 6644
 6645    pub(crate) fn enqueue_item_serialization(
 6646        &mut self,
 6647        item: Box<dyn SerializableItemHandle>,
 6648    ) -> Result<()> {
 6649        self.serializable_items_tx
 6650            .unbounded_send(item)
 6651            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6652    }
 6653
 6654    pub(crate) fn load_workspace(
 6655        serialized_workspace: SerializedWorkspace,
 6656        paths_to_open: Vec<Option<ProjectPath>>,
 6657        window: &mut Window,
 6658        cx: &mut Context<Workspace>,
 6659    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6660        cx.spawn_in(window, async move |workspace, cx| {
 6661            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6662
 6663            let mut center_group = None;
 6664            let mut center_items = None;
 6665
 6666            // Traverse the splits tree and add to things
 6667            if let Some((group, active_pane, items)) = serialized_workspace
 6668                .center_group
 6669                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6670                .await
 6671            {
 6672                center_items = Some(items);
 6673                center_group = Some((group, active_pane))
 6674            }
 6675
 6676            let mut items_by_project_path = HashMap::default();
 6677            let mut item_ids_by_kind = HashMap::default();
 6678            let mut all_deserialized_items = Vec::default();
 6679            cx.update(|_, cx| {
 6680                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6681                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6682                        item_ids_by_kind
 6683                            .entry(serializable_item_handle.serialized_item_kind())
 6684                            .or_insert(Vec::new())
 6685                            .push(item.item_id().as_u64() as ItemId);
 6686                    }
 6687
 6688                    if let Some(project_path) = item.project_path(cx) {
 6689                        items_by_project_path.insert(project_path, item.clone());
 6690                    }
 6691                    all_deserialized_items.push(item);
 6692                }
 6693            })?;
 6694
 6695            let opened_items = paths_to_open
 6696                .into_iter()
 6697                .map(|path_to_open| {
 6698                    path_to_open
 6699                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6700                })
 6701                .collect::<Vec<_>>();
 6702
 6703            // Remove old panes from workspace panes list
 6704            workspace.update_in(cx, |workspace, window, cx| {
 6705                if let Some((center_group, active_pane)) = center_group {
 6706                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6707
 6708                    // Swap workspace center group
 6709                    workspace.center = PaneGroup::with_root(center_group);
 6710                    workspace.center.set_is_center(true);
 6711                    workspace.center.mark_positions(cx);
 6712
 6713                    if let Some(active_pane) = active_pane {
 6714                        workspace.set_active_pane(&active_pane, window, cx);
 6715                        cx.focus_self(window);
 6716                    } else {
 6717                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6718                    }
 6719                }
 6720
 6721                let docks = serialized_workspace.docks;
 6722
 6723                for (dock, serialized_dock) in [
 6724                    (&mut workspace.right_dock, docks.right),
 6725                    (&mut workspace.left_dock, docks.left),
 6726                    (&mut workspace.bottom_dock, docks.bottom),
 6727                ]
 6728                .iter_mut()
 6729                {
 6730                    dock.update(cx, |dock, cx| {
 6731                        dock.serialized_dock = Some(serialized_dock.clone());
 6732                        dock.restore_state(window, cx);
 6733                    });
 6734                }
 6735
 6736                cx.notify();
 6737            })?;
 6738
 6739            let _ = project
 6740                .update(cx, |project, cx| {
 6741                    project
 6742                        .breakpoint_store()
 6743                        .update(cx, |breakpoint_store, cx| {
 6744                            breakpoint_store
 6745                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6746                        })
 6747                })
 6748                .await;
 6749
 6750            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6751            // after loading the items, we might have different items and in order to avoid
 6752            // the database filling up, we delete items that haven't been loaded now.
 6753            //
 6754            // The items that have been loaded, have been saved after they've been added to the workspace.
 6755            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6756                item_ids_by_kind
 6757                    .into_iter()
 6758                    .map(|(item_kind, loaded_items)| {
 6759                        SerializableItemRegistry::cleanup(
 6760                            item_kind,
 6761                            serialized_workspace.id,
 6762                            loaded_items,
 6763                            window,
 6764                            cx,
 6765                        )
 6766                        .log_err()
 6767                    })
 6768                    .collect::<Vec<_>>()
 6769            })?;
 6770
 6771            futures::future::join_all(clean_up_tasks).await;
 6772
 6773            workspace
 6774                .update_in(cx, |workspace, window, cx| {
 6775                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6776                    workspace.serialize_workspace_internal(window, cx).detach();
 6777
 6778                    // Ensure that we mark the window as edited if we did load dirty items
 6779                    workspace.update_window_edited(window, cx);
 6780                })
 6781                .ok();
 6782
 6783            Ok(opened_items)
 6784        })
 6785    }
 6786
 6787    pub fn key_context(&self, cx: &App) -> KeyContext {
 6788        let mut context = KeyContext::new_with_defaults();
 6789        context.add("Workspace");
 6790        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6791        if let Some(status) = self
 6792            .debugger_provider
 6793            .as_ref()
 6794            .and_then(|provider| provider.active_thread_state(cx))
 6795        {
 6796            match status {
 6797                ThreadStatus::Running | ThreadStatus::Stepping => {
 6798                    context.add("debugger_running");
 6799                }
 6800                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6801                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6802            }
 6803        }
 6804
 6805        if self.left_dock.read(cx).is_open() {
 6806            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6807                context.set("left_dock", active_panel.panel_key());
 6808            }
 6809        }
 6810
 6811        if self.right_dock.read(cx).is_open() {
 6812            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6813                context.set("right_dock", active_panel.panel_key());
 6814            }
 6815        }
 6816
 6817        if self.bottom_dock.read(cx).is_open() {
 6818            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6819                context.set("bottom_dock", active_panel.panel_key());
 6820            }
 6821        }
 6822
 6823        context
 6824    }
 6825
 6826    /// Multiworkspace uses this to add workspace action handling to itself
 6827    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6828        self.add_workspace_actions_listeners(div, window, cx)
 6829            .on_action(cx.listener(
 6830                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6831                    for action in &action_sequence.0 {
 6832                        window.dispatch_action(action.boxed_clone(), cx);
 6833                    }
 6834                },
 6835            ))
 6836            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6837            .on_action(cx.listener(Self::close_all_items_and_panes))
 6838            .on_action(cx.listener(Self::close_item_in_all_panes))
 6839            .on_action(cx.listener(Self::save_all))
 6840            .on_action(cx.listener(Self::send_keystrokes))
 6841            .on_action(cx.listener(Self::add_folder_to_project))
 6842            .on_action(cx.listener(Self::follow_next_collaborator))
 6843            .on_action(cx.listener(Self::activate_pane_at_index))
 6844            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6845            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6846            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6847            .on_action(cx.listener(Self::toggle_theme_mode))
 6848            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6849                let pane = workspace.active_pane().clone();
 6850                workspace.unfollow_in_pane(&pane, window, cx);
 6851            }))
 6852            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6853                workspace
 6854                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6855                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6856            }))
 6857            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6858                workspace
 6859                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6860                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6861            }))
 6862            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6863                workspace
 6864                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6865                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6866            }))
 6867            .on_action(
 6868                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6869                    workspace.activate_previous_pane(window, cx)
 6870                }),
 6871            )
 6872            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6873                workspace.activate_next_pane(window, cx)
 6874            }))
 6875            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6876                workspace.activate_last_pane(window, cx)
 6877            }))
 6878            .on_action(
 6879                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6880                    workspace.activate_next_window(cx)
 6881                }),
 6882            )
 6883            .on_action(
 6884                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6885                    workspace.activate_previous_window(cx)
 6886                }),
 6887            )
 6888            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6889                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6890            }))
 6891            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6892                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6893            }))
 6894            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6895                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6896            }))
 6897            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6898                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6899            }))
 6900            .on_action(cx.listener(
 6901                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6902                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6903                },
 6904            ))
 6905            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6906                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6907            }))
 6908            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6909                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6910            }))
 6911            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6912                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6913            }))
 6914            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6915                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6916            }))
 6917            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6918                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6919                    SplitDirection::Down,
 6920                    SplitDirection::Up,
 6921                    SplitDirection::Right,
 6922                    SplitDirection::Left,
 6923                ];
 6924                for dir in DIRECTION_PRIORITY {
 6925                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6926                        workspace.swap_pane_in_direction(dir, cx);
 6927                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6928                        break;
 6929                    }
 6930                }
 6931            }))
 6932            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6933                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6934            }))
 6935            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6936                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6937            }))
 6938            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6939                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6940            }))
 6941            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6942                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6943            }))
 6944            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6945                this.toggle_dock(DockPosition::Left, window, cx);
 6946            }))
 6947            .on_action(cx.listener(
 6948                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6949                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6950                },
 6951            ))
 6952            .on_action(cx.listener(
 6953                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6954                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6955                },
 6956            ))
 6957            .on_action(cx.listener(
 6958                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6959                    if !workspace.close_active_dock(window, cx) {
 6960                        cx.propagate();
 6961                    }
 6962                },
 6963            ))
 6964            .on_action(
 6965                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6966                    workspace.close_all_docks(window, cx);
 6967                }),
 6968            )
 6969            .on_action(cx.listener(Self::toggle_all_docks))
 6970            .on_action(cx.listener(
 6971                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6972                    workspace.clear_all_notifications(cx);
 6973                },
 6974            ))
 6975            .on_action(cx.listener(
 6976                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6977                    workspace.clear_navigation_history(window, cx);
 6978                },
 6979            ))
 6980            .on_action(cx.listener(
 6981                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6982                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6983                        workspace.suppress_notification(&notification_id, cx);
 6984                    }
 6985                },
 6986            ))
 6987            .on_action(cx.listener(
 6988                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6989                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6990                },
 6991            ))
 6992            .on_action(
 6993                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6994                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6995                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6996                            trusted_worktrees.clear_trusted_paths()
 6997                        });
 6998                        let db = WorkspaceDb::global(cx);
 6999                        cx.spawn(async move |_, cx| {
 7000                            if db.clear_trusted_worktrees().await.log_err().is_some() {
 7001                                cx.update(|cx| reload(cx));
 7002                            }
 7003                        })
 7004                        .detach();
 7005                    }
 7006                }),
 7007            )
 7008            .on_action(cx.listener(
 7009                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 7010                    workspace.reopen_closed_item(window, cx).detach();
 7011                },
 7012            ))
 7013            .on_action(cx.listener(
 7014                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 7015                    for dock in workspace.all_docks() {
 7016                        if dock.focus_handle(cx).contains_focused(window, cx) {
 7017                            let panel = dock.read(cx).active_panel().cloned();
 7018                            if let Some(panel) = panel {
 7019                                dock.update(cx, |dock, cx| {
 7020                                    dock.set_panel_size_state(
 7021                                        panel.as_ref(),
 7022                                        dock::PanelSizeState::default(),
 7023                                        cx,
 7024                                    );
 7025                                });
 7026                            }
 7027                            return;
 7028                        }
 7029                    }
 7030                },
 7031            ))
 7032            .on_action(cx.listener(
 7033                |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
 7034                    for dock in workspace.all_docks() {
 7035                        let panel = dock.read(cx).visible_panel().cloned();
 7036                        if let Some(panel) = panel {
 7037                            dock.update(cx, |dock, cx| {
 7038                                dock.set_panel_size_state(
 7039                                    panel.as_ref(),
 7040                                    dock::PanelSizeState::default(),
 7041                                    cx,
 7042                                );
 7043                            });
 7044                        }
 7045                    }
 7046                },
 7047            ))
 7048            .on_action(cx.listener(
 7049                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 7050                    adjust_active_dock_size_by_px(
 7051                        px_with_ui_font_fallback(act.px, cx),
 7052                        workspace,
 7053                        window,
 7054                        cx,
 7055                    );
 7056                },
 7057            ))
 7058            .on_action(cx.listener(
 7059                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 7060                    adjust_active_dock_size_by_px(
 7061                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7062                        workspace,
 7063                        window,
 7064                        cx,
 7065                    );
 7066                },
 7067            ))
 7068            .on_action(cx.listener(
 7069                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 7070                    adjust_open_docks_size_by_px(
 7071                        px_with_ui_font_fallback(act.px, cx),
 7072                        workspace,
 7073                        window,
 7074                        cx,
 7075                    );
 7076                },
 7077            ))
 7078            .on_action(cx.listener(
 7079                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 7080                    adjust_open_docks_size_by_px(
 7081                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7082                        workspace,
 7083                        window,
 7084                        cx,
 7085                    );
 7086                },
 7087            ))
 7088            .on_action(cx.listener(Workspace::toggle_centered_layout))
 7089            .on_action(cx.listener(
 7090                |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
 7091                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7092                        let dock = active_dock.read(cx);
 7093                        if let Some(active_panel) = dock.active_panel() {
 7094                            if active_panel.pane(cx).is_none() {
 7095                                let mut recent_pane: Option<Entity<Pane>> = None;
 7096                                let mut recent_timestamp = 0;
 7097                                for pane_handle in workspace.panes() {
 7098                                    let pane = pane_handle.read(cx);
 7099                                    for entry in pane.activation_history() {
 7100                                        if entry.timestamp > recent_timestamp {
 7101                                            recent_timestamp = entry.timestamp;
 7102                                            recent_pane = Some(pane_handle.clone());
 7103                                        }
 7104                                    }
 7105                                }
 7106
 7107                                if let Some(pane) = recent_pane {
 7108                                    let wrap_around = action.wrap_around;
 7109                                    pane.update(cx, |pane, cx| {
 7110                                        let current_index = pane.active_item_index();
 7111                                        let items_len = pane.items_len();
 7112                                        if items_len > 0 {
 7113                                            let next_index = if current_index + 1 < items_len {
 7114                                                current_index + 1
 7115                                            } else if wrap_around {
 7116                                                0
 7117                                            } else {
 7118                                                return;
 7119                                            };
 7120                                            pane.activate_item(
 7121                                                next_index, false, false, window, cx,
 7122                                            );
 7123                                        }
 7124                                    });
 7125                                    return;
 7126                                }
 7127                            }
 7128                        }
 7129                    }
 7130                    cx.propagate();
 7131                },
 7132            ))
 7133            .on_action(cx.listener(
 7134                |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
 7135                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7136                        let dock = active_dock.read(cx);
 7137                        if let Some(active_panel) = dock.active_panel() {
 7138                            if active_panel.pane(cx).is_none() {
 7139                                let mut recent_pane: Option<Entity<Pane>> = None;
 7140                                let mut recent_timestamp = 0;
 7141                                for pane_handle in workspace.panes() {
 7142                                    let pane = pane_handle.read(cx);
 7143                                    for entry in pane.activation_history() {
 7144                                        if entry.timestamp > recent_timestamp {
 7145                                            recent_timestamp = entry.timestamp;
 7146                                            recent_pane = Some(pane_handle.clone());
 7147                                        }
 7148                                    }
 7149                                }
 7150
 7151                                if let Some(pane) = recent_pane {
 7152                                    let wrap_around = action.wrap_around;
 7153                                    pane.update(cx, |pane, cx| {
 7154                                        let current_index = pane.active_item_index();
 7155                                        let items_len = pane.items_len();
 7156                                        if items_len > 0 {
 7157                                            let prev_index = if current_index > 0 {
 7158                                                current_index - 1
 7159                                            } else if wrap_around {
 7160                                                items_len.saturating_sub(1)
 7161                                            } else {
 7162                                                return;
 7163                                            };
 7164                                            pane.activate_item(
 7165                                                prev_index, false, false, window, cx,
 7166                                            );
 7167                                        }
 7168                                    });
 7169                                    return;
 7170                                }
 7171                            }
 7172                        }
 7173                    }
 7174                    cx.propagate();
 7175                },
 7176            ))
 7177            .on_action(cx.listener(
 7178                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 7179                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7180                        let dock = active_dock.read(cx);
 7181                        if let Some(active_panel) = dock.active_panel() {
 7182                            if active_panel.pane(cx).is_none() {
 7183                                let active_pane = workspace.active_pane().clone();
 7184                                active_pane.update(cx, |pane, cx| {
 7185                                    pane.close_active_item(action, window, cx)
 7186                                        .detach_and_log_err(cx);
 7187                                });
 7188                                return;
 7189                            }
 7190                        }
 7191                    }
 7192                    cx.propagate();
 7193                },
 7194            ))
 7195            .on_action(
 7196                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 7197                    let pane = workspace.active_pane().clone();
 7198                    if let Some(item) = pane.read(cx).active_item() {
 7199                        item.toggle_read_only(window, cx);
 7200                    }
 7201                }),
 7202            )
 7203            .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
 7204                workspace.focus_center_pane(window, cx);
 7205            }))
 7206            .on_action(cx.listener(Workspace::cancel))
 7207    }
 7208
 7209    #[cfg(any(test, feature = "test-support"))]
 7210    pub fn set_random_database_id(&mut self) {
 7211        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 7212    }
 7213
 7214    #[cfg(any(test, feature = "test-support"))]
 7215    pub(crate) fn test_new(
 7216        project: Entity<Project>,
 7217        window: &mut Window,
 7218        cx: &mut Context<Self>,
 7219    ) -> Self {
 7220        use node_runtime::NodeRuntime;
 7221        use session::Session;
 7222
 7223        let client = project.read(cx).client();
 7224        let user_store = project.read(cx).user_store();
 7225        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 7226        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 7227        window.activate_window();
 7228        let app_state = Arc::new(AppState {
 7229            languages: project.read(cx).languages().clone(),
 7230            workspace_store,
 7231            client,
 7232            user_store,
 7233            fs: project.read(cx).fs().clone(),
 7234            build_window_options: |_, _| Default::default(),
 7235            node_runtime: NodeRuntime::unavailable(),
 7236            session,
 7237        });
 7238        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 7239        workspace
 7240            .active_pane
 7241            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 7242        workspace
 7243    }
 7244
 7245    pub fn register_action<A: Action>(
 7246        &mut self,
 7247        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 7248    ) -> &mut Self {
 7249        let callback = Arc::new(callback);
 7250
 7251        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 7252            let callback = callback.clone();
 7253            div.on_action(cx.listener(move |workspace, event, window, cx| {
 7254                (callback)(workspace, event, window, cx)
 7255            }))
 7256        }));
 7257        self
 7258    }
 7259    pub fn register_action_renderer(
 7260        &mut self,
 7261        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 7262    ) -> &mut Self {
 7263        self.workspace_actions.push(Box::new(callback));
 7264        self
 7265    }
 7266
 7267    fn add_workspace_actions_listeners(
 7268        &self,
 7269        mut div: Div,
 7270        window: &mut Window,
 7271        cx: &mut Context<Self>,
 7272    ) -> Div {
 7273        for action in self.workspace_actions.iter() {
 7274            div = (action)(div, self, window, cx)
 7275        }
 7276        div
 7277    }
 7278
 7279    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 7280        self.modal_layer.read(cx).has_active_modal()
 7281    }
 7282
 7283    pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
 7284        self.modal_layer
 7285            .read(cx)
 7286            .is_active_modal_command_palette(cx)
 7287    }
 7288
 7289    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7290        self.modal_layer.read(cx).active_modal()
 7291    }
 7292
 7293    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7294    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7295    /// If no modal is active, the new modal will be shown.
 7296    ///
 7297    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7298    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7299    /// will not be shown.
 7300    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7301    where
 7302        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7303    {
 7304        self.modal_layer.update(cx, |modal_layer, cx| {
 7305            modal_layer.toggle_modal(window, cx, build)
 7306        })
 7307    }
 7308
 7309    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7310        self.modal_layer
 7311            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7312    }
 7313
 7314    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7315        self.toast_layer
 7316            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7317    }
 7318
 7319    pub fn toggle_centered_layout(
 7320        &mut self,
 7321        _: &ToggleCenteredLayout,
 7322        _: &mut Window,
 7323        cx: &mut Context<Self>,
 7324    ) {
 7325        self.centered_layout = !self.centered_layout;
 7326        if let Some(database_id) = self.database_id() {
 7327            let db = WorkspaceDb::global(cx);
 7328            let centered_layout = self.centered_layout;
 7329            cx.background_spawn(async move {
 7330                db.set_centered_layout(database_id, centered_layout).await
 7331            })
 7332            .detach_and_log_err(cx);
 7333        }
 7334        cx.notify();
 7335    }
 7336
 7337    fn adjust_padding(padding: Option<f32>) -> f32 {
 7338        padding
 7339            .unwrap_or(CenteredPaddingSettings::default().0)
 7340            .clamp(
 7341                CenteredPaddingSettings::MIN_PADDING,
 7342                CenteredPaddingSettings::MAX_PADDING,
 7343            )
 7344    }
 7345
 7346    fn render_dock(
 7347        &self,
 7348        position: DockPosition,
 7349        dock: &Entity<Dock>,
 7350        window: &mut Window,
 7351        cx: &mut App,
 7352    ) -> Option<Div> {
 7353        if self.zoomed_position == Some(position) {
 7354            return None;
 7355        }
 7356
 7357        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7358            let pane = panel.pane(cx)?;
 7359            let follower_states = &self.follower_states;
 7360            leader_border_for_pane(follower_states, &pane, window, cx)
 7361        });
 7362
 7363        let mut container = div()
 7364            .flex()
 7365            .overflow_hidden()
 7366            .flex_none()
 7367            .child(dock.clone())
 7368            .children(leader_border);
 7369
 7370        // Apply sizing only when the dock is open. When closed the dock is still
 7371        // included in the element tree so its focus handle remains mounted — without
 7372        // this, toggle_panel_focus cannot focus the panel when the dock is closed.
 7373        let dock = dock.read(cx);
 7374        if let Some(panel) = dock.visible_panel() {
 7375            let size_state = dock.stored_panel_size_state(panel.as_ref());
 7376            if position.axis() == Axis::Horizontal {
 7377                let use_flexible = panel.has_flexible_size(window, cx);
 7378                let flex_grow = if use_flexible {
 7379                    size_state
 7380                        .and_then(|state| state.flex)
 7381                        .or_else(|| self.default_dock_flex(position))
 7382                } else {
 7383                    None
 7384                };
 7385                if let Some(grow) = flex_grow {
 7386                    let grow = grow.max(0.001);
 7387                    let style = container.style();
 7388                    style.flex_grow = Some(grow);
 7389                    style.flex_shrink = Some(1.0);
 7390                    style.flex_basis = Some(relative(0.).into());
 7391                } else {
 7392                    let size = size_state
 7393                        .and_then(|state| state.size)
 7394                        .unwrap_or_else(|| panel.default_size(window, cx));
 7395                    container = container.w(size);
 7396                }
 7397            } else {
 7398                let size = size_state
 7399                    .and_then(|state| state.size)
 7400                    .unwrap_or_else(|| panel.default_size(window, cx));
 7401                container = container.h(size);
 7402            }
 7403        }
 7404
 7405        Some(container)
 7406    }
 7407
 7408    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7409        window
 7410            .root::<MultiWorkspace>()
 7411            .flatten()
 7412            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7413    }
 7414
 7415    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7416        self.zoomed.as_ref()
 7417    }
 7418
 7419    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7420        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7421            return;
 7422        };
 7423        let windows = cx.windows();
 7424        let next_window =
 7425            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7426                || {
 7427                    windows
 7428                        .iter()
 7429                        .cycle()
 7430                        .skip_while(|window| window.window_id() != current_window_id)
 7431                        .nth(1)
 7432                },
 7433            );
 7434
 7435        if let Some(window) = next_window {
 7436            window
 7437                .update(cx, |_, window, _| window.activate_window())
 7438                .ok();
 7439        }
 7440    }
 7441
 7442    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7443        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7444            return;
 7445        };
 7446        let windows = cx.windows();
 7447        let prev_window =
 7448            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7449                || {
 7450                    windows
 7451                        .iter()
 7452                        .rev()
 7453                        .cycle()
 7454                        .skip_while(|window| window.window_id() != current_window_id)
 7455                        .nth(1)
 7456                },
 7457            );
 7458
 7459        if let Some(window) = prev_window {
 7460            window
 7461                .update(cx, |_, window, _| window.activate_window())
 7462                .ok();
 7463        }
 7464    }
 7465
 7466    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7467        if cx.stop_active_drag(window) {
 7468        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7469            dismiss_app_notification(&notification_id, cx);
 7470        } else {
 7471            cx.propagate();
 7472        }
 7473    }
 7474
 7475    fn resize_dock(
 7476        &mut self,
 7477        dock_pos: DockPosition,
 7478        new_size: Pixels,
 7479        window: &mut Window,
 7480        cx: &mut Context<Self>,
 7481    ) {
 7482        match dock_pos {
 7483            DockPosition::Left => self.resize_left_dock(new_size, window, cx),
 7484            DockPosition::Right => self.resize_right_dock(new_size, window, cx),
 7485            DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
 7486        }
 7487    }
 7488
 7489    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7490        let workspace_width = self.bounds.size.width;
 7491        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7492
 7493        self.right_dock.read_with(cx, |right_dock, cx| {
 7494            let right_dock_size = right_dock
 7495                .stored_active_panel_size(window, cx)
 7496                .unwrap_or(Pixels::ZERO);
 7497            if right_dock_size + size > workspace_width {
 7498                size = workspace_width - right_dock_size
 7499            }
 7500        });
 7501
 7502        let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
 7503        self.left_dock.update(cx, |left_dock, cx| {
 7504            if WorkspaceSettings::get_global(cx)
 7505                .resize_all_panels_in_dock
 7506                .contains(&DockPosition::Left)
 7507            {
 7508                left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7509            } else {
 7510                left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7511            }
 7512        });
 7513    }
 7514
 7515    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7516        let workspace_width = self.bounds.size.width;
 7517        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7518        self.left_dock.read_with(cx, |left_dock, cx| {
 7519            let left_dock_size = left_dock
 7520                .stored_active_panel_size(window, cx)
 7521                .unwrap_or(Pixels::ZERO);
 7522            if left_dock_size + size > workspace_width {
 7523                size = workspace_width - left_dock_size
 7524            }
 7525        });
 7526        let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
 7527        self.right_dock.update(cx, |right_dock, cx| {
 7528            if WorkspaceSettings::get_global(cx)
 7529                .resize_all_panels_in_dock
 7530                .contains(&DockPosition::Right)
 7531            {
 7532                right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7533            } else {
 7534                right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7535            }
 7536        });
 7537    }
 7538
 7539    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7540        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7541        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7542            if WorkspaceSettings::get_global(cx)
 7543                .resize_all_panels_in_dock
 7544                .contains(&DockPosition::Bottom)
 7545            {
 7546                bottom_dock.resize_all_panels(Some(size), None, window, cx);
 7547            } else {
 7548                bottom_dock.resize_active_panel(Some(size), None, window, cx);
 7549            }
 7550        });
 7551    }
 7552
 7553    fn toggle_edit_predictions_all_files(
 7554        &mut self,
 7555        _: &ToggleEditPrediction,
 7556        _window: &mut Window,
 7557        cx: &mut Context<Self>,
 7558    ) {
 7559        let fs = self.project().read(cx).fs().clone();
 7560        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7561        update_settings_file(fs, cx, move |file, _| {
 7562            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7563        });
 7564    }
 7565
 7566    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7567        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7568        let next_mode = match current_mode {
 7569            Some(theme_settings::ThemeAppearanceMode::Light) => {
 7570                theme_settings::ThemeAppearanceMode::Dark
 7571            }
 7572            Some(theme_settings::ThemeAppearanceMode::Dark) => {
 7573                theme_settings::ThemeAppearanceMode::Light
 7574            }
 7575            Some(theme_settings::ThemeAppearanceMode::System) | None => {
 7576                match cx.theme().appearance() {
 7577                    theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
 7578                    theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
 7579                }
 7580            }
 7581        };
 7582
 7583        let fs = self.project().read(cx).fs().clone();
 7584        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7585            theme_settings::set_mode(settings, next_mode);
 7586        });
 7587    }
 7588
 7589    pub fn show_worktree_trust_security_modal(
 7590        &mut self,
 7591        toggle: bool,
 7592        window: &mut Window,
 7593        cx: &mut Context<Self>,
 7594    ) {
 7595        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7596            if toggle {
 7597                security_modal.update(cx, |security_modal, cx| {
 7598                    security_modal.dismiss(cx);
 7599                })
 7600            } else {
 7601                security_modal.update(cx, |security_modal, cx| {
 7602                    security_modal.refresh_restricted_paths(cx);
 7603                });
 7604            }
 7605        } else {
 7606            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7607                .map(|trusted_worktrees| {
 7608                    trusted_worktrees
 7609                        .read(cx)
 7610                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7611                })
 7612                .unwrap_or(false);
 7613            if has_restricted_worktrees {
 7614                let project = self.project().read(cx);
 7615                let remote_host = project
 7616                    .remote_connection_options(cx)
 7617                    .map(RemoteHostLocation::from);
 7618                let worktree_store = project.worktree_store().downgrade();
 7619                self.toggle_modal(window, cx, |_, cx| {
 7620                    SecurityModal::new(worktree_store, remote_host, cx)
 7621                });
 7622            }
 7623        }
 7624    }
 7625}
 7626
 7627pub trait AnyActiveCall {
 7628    fn entity(&self) -> AnyEntity;
 7629    fn is_in_room(&self, _: &App) -> bool;
 7630    fn room_id(&self, _: &App) -> Option<u64>;
 7631    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7632    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7633    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7634    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7635    fn is_sharing_project(&self, _: &App) -> bool;
 7636    fn has_remote_participants(&self, _: &App) -> bool;
 7637    fn local_participant_is_guest(&self, _: &App) -> bool;
 7638    fn client(&self, _: &App) -> Arc<Client>;
 7639    fn share_on_join(&self, _: &App) -> bool;
 7640    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7641    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7642    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7643    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7644    fn join_project(
 7645        &self,
 7646        _: u64,
 7647        _: Arc<LanguageRegistry>,
 7648        _: Arc<dyn Fs>,
 7649        _: &mut App,
 7650    ) -> Task<Result<Entity<Project>>>;
 7651    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7652    fn subscribe(
 7653        &self,
 7654        _: &mut Window,
 7655        _: &mut Context<Workspace>,
 7656        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7657    ) -> Subscription;
 7658    fn create_shared_screen(
 7659        &self,
 7660        _: PeerId,
 7661        _: &Entity<Pane>,
 7662        _: &mut Window,
 7663        _: &mut App,
 7664    ) -> Option<Entity<SharedScreen>>;
 7665}
 7666
 7667#[derive(Clone)]
 7668pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7669impl Global for GlobalAnyActiveCall {}
 7670
 7671impl GlobalAnyActiveCall {
 7672    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7673        cx.try_global()
 7674    }
 7675
 7676    pub(crate) fn global(cx: &App) -> &Self {
 7677        cx.global()
 7678    }
 7679}
 7680
 7681pub fn merge_conflict_notification_id() -> NotificationId {
 7682    struct MergeConflictNotification;
 7683    NotificationId::unique::<MergeConflictNotification>()
 7684}
 7685
 7686/// Workspace-local view of a remote participant's location.
 7687#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7688pub enum ParticipantLocation {
 7689    SharedProject { project_id: u64 },
 7690    UnsharedProject,
 7691    External,
 7692}
 7693
 7694impl ParticipantLocation {
 7695    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7696        match location
 7697            .and_then(|l| l.variant)
 7698            .context("participant location was not provided")?
 7699        {
 7700            proto::participant_location::Variant::SharedProject(project) => {
 7701                Ok(Self::SharedProject {
 7702                    project_id: project.id,
 7703                })
 7704            }
 7705            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7706            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7707        }
 7708    }
 7709}
 7710/// Workspace-local view of a remote collaborator's state.
 7711/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7712#[derive(Clone)]
 7713pub struct RemoteCollaborator {
 7714    pub user: Arc<User>,
 7715    pub peer_id: PeerId,
 7716    pub location: ParticipantLocation,
 7717    pub participant_index: ParticipantIndex,
 7718}
 7719
 7720pub enum ActiveCallEvent {
 7721    ParticipantLocationChanged { participant_id: PeerId },
 7722    RemoteVideoTracksChanged { participant_id: PeerId },
 7723}
 7724
 7725fn leader_border_for_pane(
 7726    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7727    pane: &Entity<Pane>,
 7728    _: &Window,
 7729    cx: &App,
 7730) -> Option<Div> {
 7731    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7732        if state.pane() == pane {
 7733            Some((*leader_id, state))
 7734        } else {
 7735            None
 7736        }
 7737    })?;
 7738
 7739    let mut leader_color = match leader_id {
 7740        CollaboratorId::PeerId(leader_peer_id) => {
 7741            let leader = GlobalAnyActiveCall::try_global(cx)?
 7742                .0
 7743                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7744
 7745            cx.theme()
 7746                .players()
 7747                .color_for_participant(leader.participant_index.0)
 7748                .cursor
 7749        }
 7750        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7751    };
 7752    leader_color.fade_out(0.3);
 7753    Some(
 7754        div()
 7755            .absolute()
 7756            .size_full()
 7757            .left_0()
 7758            .top_0()
 7759            .border_2()
 7760            .border_color(leader_color),
 7761    )
 7762}
 7763
 7764fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7765    ZED_WINDOW_POSITION
 7766        .zip(*ZED_WINDOW_SIZE)
 7767        .map(|(position, size)| Bounds {
 7768            origin: position,
 7769            size,
 7770        })
 7771}
 7772
 7773fn open_items(
 7774    serialized_workspace: Option<SerializedWorkspace>,
 7775    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7776    window: &mut Window,
 7777    cx: &mut Context<Workspace>,
 7778) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7779    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7780        Workspace::load_workspace(
 7781            serialized_workspace,
 7782            project_paths_to_open
 7783                .iter()
 7784                .map(|(_, project_path)| project_path)
 7785                .cloned()
 7786                .collect(),
 7787            window,
 7788            cx,
 7789        )
 7790    });
 7791
 7792    cx.spawn_in(window, async move |workspace, cx| {
 7793        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7794
 7795        if let Some(restored_items) = restored_items {
 7796            let restored_items = restored_items.await?;
 7797
 7798            let restored_project_paths = restored_items
 7799                .iter()
 7800                .filter_map(|item| {
 7801                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7802                        .ok()
 7803                        .flatten()
 7804                })
 7805                .collect::<HashSet<_>>();
 7806
 7807            for restored_item in restored_items {
 7808                opened_items.push(restored_item.map(Ok));
 7809            }
 7810
 7811            project_paths_to_open
 7812                .iter_mut()
 7813                .for_each(|(_, project_path)| {
 7814                    if let Some(project_path_to_open) = project_path
 7815                        && restored_project_paths.contains(project_path_to_open)
 7816                    {
 7817                        *project_path = None;
 7818                    }
 7819                });
 7820        } else {
 7821            for _ in 0..project_paths_to_open.len() {
 7822                opened_items.push(None);
 7823            }
 7824        }
 7825        assert!(opened_items.len() == project_paths_to_open.len());
 7826
 7827        let tasks =
 7828            project_paths_to_open
 7829                .into_iter()
 7830                .enumerate()
 7831                .map(|(ix, (abs_path, project_path))| {
 7832                    let workspace = workspace.clone();
 7833                    cx.spawn(async move |cx| {
 7834                        let file_project_path = project_path?;
 7835                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7836                            workspace.project().update(cx, |project, cx| {
 7837                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7838                            })
 7839                        });
 7840
 7841                        // We only want to open file paths here. If one of the items
 7842                        // here is a directory, it was already opened further above
 7843                        // with a `find_or_create_worktree`.
 7844                        if let Ok(task) = abs_path_task
 7845                            && task.await.is_none_or(|p| p.is_file())
 7846                        {
 7847                            return Some((
 7848                                ix,
 7849                                workspace
 7850                                    .update_in(cx, |workspace, window, cx| {
 7851                                        workspace.open_path(
 7852                                            file_project_path,
 7853                                            None,
 7854                                            true,
 7855                                            window,
 7856                                            cx,
 7857                                        )
 7858                                    })
 7859                                    .log_err()?
 7860                                    .await,
 7861                            ));
 7862                        }
 7863                        None
 7864                    })
 7865                });
 7866
 7867        let tasks = tasks.collect::<Vec<_>>();
 7868
 7869        let tasks = futures::future::join_all(tasks);
 7870        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7871            opened_items[ix] = Some(path_open_result);
 7872        }
 7873
 7874        Ok(opened_items)
 7875    })
 7876}
 7877
 7878#[derive(Clone)]
 7879enum ActivateInDirectionTarget {
 7880    Pane(Entity<Pane>),
 7881    Dock(Entity<Dock>),
 7882    Sidebar(FocusHandle),
 7883}
 7884
 7885fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7886    window
 7887        .update(cx, |multi_workspace, _, cx| {
 7888            let workspace = multi_workspace.workspace().clone();
 7889            workspace.update(cx, |workspace, cx| {
 7890                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7891                    struct DatabaseFailedNotification;
 7892
 7893                    workspace.show_notification(
 7894                        NotificationId::unique::<DatabaseFailedNotification>(),
 7895                        cx,
 7896                        |cx| {
 7897                            cx.new(|cx| {
 7898                                MessageNotification::new("Failed to load the database file.", cx)
 7899                                    .primary_message("File an Issue")
 7900                                    .primary_icon(IconName::Plus)
 7901                                    .primary_on_click(|window, cx| {
 7902                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7903                                    })
 7904                            })
 7905                        },
 7906                    );
 7907                }
 7908            });
 7909        })
 7910        .log_err();
 7911}
 7912
 7913fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7914    if val == 0 {
 7915        ThemeSettings::get_global(cx).ui_font_size(cx)
 7916    } else {
 7917        px(val as f32)
 7918    }
 7919}
 7920
 7921fn adjust_active_dock_size_by_px(
 7922    px: Pixels,
 7923    workspace: &mut Workspace,
 7924    window: &mut Window,
 7925    cx: &mut Context<Workspace>,
 7926) {
 7927    let Some(active_dock) = workspace
 7928        .all_docks()
 7929        .into_iter()
 7930        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7931    else {
 7932        return;
 7933    };
 7934    let dock = active_dock.read(cx);
 7935    let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
 7936        return;
 7937    };
 7938    workspace.resize_dock(dock.position(), panel_size + px, window, cx);
 7939}
 7940
 7941fn adjust_open_docks_size_by_px(
 7942    px: Pixels,
 7943    workspace: &mut Workspace,
 7944    window: &mut Window,
 7945    cx: &mut Context<Workspace>,
 7946) {
 7947    let docks = workspace
 7948        .all_docks()
 7949        .into_iter()
 7950        .filter_map(|dock_entity| {
 7951            let dock = dock_entity.read(cx);
 7952            if dock.is_open() {
 7953                let dock_pos = dock.position();
 7954                let panel_size = workspace.dock_size(&dock, window, cx)?;
 7955                Some((dock_pos, panel_size + px))
 7956            } else {
 7957                None
 7958            }
 7959        })
 7960        .collect::<Vec<_>>();
 7961
 7962    for (position, new_size) in docks {
 7963        workspace.resize_dock(position, new_size, window, cx);
 7964    }
 7965}
 7966
 7967impl Focusable for Workspace {
 7968    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7969        self.active_pane.focus_handle(cx)
 7970    }
 7971}
 7972
 7973#[derive(Clone)]
 7974struct DraggedDock(DockPosition);
 7975
 7976impl Render for DraggedDock {
 7977    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7978        gpui::Empty
 7979    }
 7980}
 7981
 7982impl Render for Workspace {
 7983    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 7984        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 7985        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 7986            log::info!("Rendered first frame");
 7987        }
 7988
 7989        let centered_layout = self.centered_layout
 7990            && self.center.panes().len() == 1
 7991            && self.active_item(cx).is_some();
 7992        let render_padding = |size| {
 7993            (size > 0.0).then(|| {
 7994                div()
 7995                    .h_full()
 7996                    .w(relative(size))
 7997                    .bg(cx.theme().colors().editor_background)
 7998                    .border_color(cx.theme().colors().pane_group_border)
 7999            })
 8000        };
 8001        let paddings = if centered_layout {
 8002            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 8003            (
 8004                render_padding(Self::adjust_padding(
 8005                    settings.left_padding.map(|padding| padding.0),
 8006                )),
 8007                render_padding(Self::adjust_padding(
 8008                    settings.right_padding.map(|padding| padding.0),
 8009                )),
 8010            )
 8011        } else {
 8012            (None, None)
 8013        };
 8014        let ui_font = theme_settings::setup_ui_font(window, cx);
 8015
 8016        let theme = cx.theme().clone();
 8017        let colors = theme.colors();
 8018        let notification_entities = self
 8019            .notifications
 8020            .iter()
 8021            .map(|(_, notification)| notification.entity_id())
 8022            .collect::<Vec<_>>();
 8023        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 8024
 8025        div()
 8026            .relative()
 8027            .size_full()
 8028            .flex()
 8029            .flex_col()
 8030            .font(ui_font)
 8031            .gap_0()
 8032                .justify_start()
 8033                .items_start()
 8034                .text_color(colors.text)
 8035                .overflow_hidden()
 8036                .children(self.titlebar_item.clone())
 8037                .on_modifiers_changed(move |_, _, cx| {
 8038                    for &id in &notification_entities {
 8039                        cx.notify(id);
 8040                    }
 8041                })
 8042                .child(
 8043                    div()
 8044                        .size_full()
 8045                        .relative()
 8046                        .flex_1()
 8047                        .flex()
 8048                        .flex_col()
 8049                        .child(
 8050                            div()
 8051                                .id("workspace")
 8052                                .bg(colors.background)
 8053                                .relative()
 8054                                .flex_1()
 8055                                .w_full()
 8056                                .flex()
 8057                                .flex_col()
 8058                                .overflow_hidden()
 8059                                .border_t_1()
 8060                                .border_b_1()
 8061                                .border_color(colors.border)
 8062                                .child({
 8063                                    let this = cx.entity();
 8064                                    canvas(
 8065                                        move |bounds, window, cx| {
 8066                                            this.update(cx, |this, cx| {
 8067                                                let bounds_changed = this.bounds != bounds;
 8068                                                this.bounds = bounds;
 8069
 8070                                                if bounds_changed {
 8071                                                    this.left_dock.update(cx, |dock, cx| {
 8072                                                        dock.clamp_panel_size(
 8073                                                            bounds.size.width,
 8074                                                            window,
 8075                                                            cx,
 8076                                                        )
 8077                                                    });
 8078
 8079                                                    this.right_dock.update(cx, |dock, cx| {
 8080                                                        dock.clamp_panel_size(
 8081                                                            bounds.size.width,
 8082                                                            window,
 8083                                                            cx,
 8084                                                        )
 8085                                                    });
 8086
 8087                                                    this.bottom_dock.update(cx, |dock, cx| {
 8088                                                        dock.clamp_panel_size(
 8089                                                            bounds.size.height,
 8090                                                            window,
 8091                                                            cx,
 8092                                                        )
 8093                                                    });
 8094                                                }
 8095                                            })
 8096                                        },
 8097                                        |_, _, _, _| {},
 8098                                    )
 8099                                    .absolute()
 8100                                    .size_full()
 8101                                })
 8102                                .when(self.zoomed.is_none(), |this| {
 8103                                    this.on_drag_move(cx.listener(
 8104                                        move |workspace,
 8105                                              e: &DragMoveEvent<DraggedDock>,
 8106                                              window,
 8107                                              cx| {
 8108                                            if workspace.previous_dock_drag_coordinates
 8109                                                != Some(e.event.position)
 8110                                            {
 8111                                                workspace.previous_dock_drag_coordinates =
 8112                                                    Some(e.event.position);
 8113
 8114                                                match e.drag(cx).0 {
 8115                                                    DockPosition::Left => {
 8116                                                        workspace.resize_left_dock(
 8117                                                            e.event.position.x
 8118                                                                - workspace.bounds.left(),
 8119                                                            window,
 8120                                                            cx,
 8121                                                        );
 8122                                                    }
 8123                                                    DockPosition::Right => {
 8124                                                        workspace.resize_right_dock(
 8125                                                            workspace.bounds.right()
 8126                                                                - e.event.position.x,
 8127                                                            window,
 8128                                                            cx,
 8129                                                        );
 8130                                                    }
 8131                                                    DockPosition::Bottom => {
 8132                                                        workspace.resize_bottom_dock(
 8133                                                            workspace.bounds.bottom()
 8134                                                                - e.event.position.y,
 8135                                                            window,
 8136                                                            cx,
 8137                                                        );
 8138                                                    }
 8139                                                };
 8140                                                workspace.serialize_workspace(window, cx);
 8141                                            }
 8142                                        },
 8143                                    ))
 8144
 8145                                })
 8146                                .child({
 8147                                    match bottom_dock_layout {
 8148                                        BottomDockLayout::Full => div()
 8149                                            .flex()
 8150                                            .flex_col()
 8151                                            .h_full()
 8152                                            .child(
 8153                                                div()
 8154                                                    .flex()
 8155                                                    .flex_row()
 8156                                                    .flex_1()
 8157                                                    .overflow_hidden()
 8158                                                    .children(self.render_dock(
 8159                                                        DockPosition::Left,
 8160                                                        &self.left_dock,
 8161                                                        window,
 8162                                                        cx,
 8163                                                    ))
 8164
 8165                                                    .child(
 8166                                                        div()
 8167                                                            .flex()
 8168                                                            .flex_col()
 8169                                                            .flex_1()
 8170                                                            .overflow_hidden()
 8171                                                            .child(
 8172                                                                h_flex()
 8173                                                                    .flex_1()
 8174                                                                    .when_some(
 8175                                                                        paddings.0,
 8176                                                                        |this, p| {
 8177                                                                            this.child(
 8178                                                                                p.border_r_1(),
 8179                                                                            )
 8180                                                                        },
 8181                                                                    )
 8182                                                                    .child(self.center.render(
 8183                                                                        self.zoomed.as_ref(),
 8184                                                                        &PaneRenderContext {
 8185                                                                            follower_states:
 8186                                                                                &self.follower_states,
 8187                                                                            active_call: self.active_call(),
 8188                                                                            active_pane: &self.active_pane,
 8189                                                                            app_state: &self.app_state,
 8190                                                                            project: &self.project,
 8191                                                                            workspace: &self.weak_self,
 8192                                                                        },
 8193                                                                        window,
 8194                                                                        cx,
 8195                                                                    ))
 8196                                                                    .when_some(
 8197                                                                        paddings.1,
 8198                                                                        |this, p| {
 8199                                                                            this.child(
 8200                                                                                p.border_l_1(),
 8201                                                                            )
 8202                                                                        },
 8203                                                                    ),
 8204                                                            ),
 8205                                                    )
 8206
 8207                                                    .children(self.render_dock(
 8208                                                        DockPosition::Right,
 8209                                                        &self.right_dock,
 8210                                                        window,
 8211                                                        cx,
 8212                                                    )),
 8213                                            )
 8214                                            .child(div().w_full().children(self.render_dock(
 8215                                                DockPosition::Bottom,
 8216                                                &self.bottom_dock,
 8217                                                window,
 8218                                                cx
 8219                                            ))),
 8220
 8221                                        BottomDockLayout::LeftAligned => div()
 8222                                            .flex()
 8223                                            .flex_row()
 8224                                            .h_full()
 8225                                            .child(
 8226                                                div()
 8227                                                    .flex()
 8228                                                    .flex_col()
 8229                                                    .flex_1()
 8230                                                    .h_full()
 8231                                                    .child(
 8232                                                        div()
 8233                                                            .flex()
 8234                                                            .flex_row()
 8235                                                            .flex_1()
 8236                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 8237
 8238                                                            .child(
 8239                                                                div()
 8240                                                                    .flex()
 8241                                                                    .flex_col()
 8242                                                                    .flex_1()
 8243                                                                    .overflow_hidden()
 8244                                                                    .child(
 8245                                                                        h_flex()
 8246                                                                            .flex_1()
 8247                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8248                                                                            .child(self.center.render(
 8249                                                                                self.zoomed.as_ref(),
 8250                                                                                &PaneRenderContext {
 8251                                                                                    follower_states:
 8252                                                                                        &self.follower_states,
 8253                                                                                    active_call: self.active_call(),
 8254                                                                                    active_pane: &self.active_pane,
 8255                                                                                    app_state: &self.app_state,
 8256                                                                                    project: &self.project,
 8257                                                                                    workspace: &self.weak_self,
 8258                                                                                },
 8259                                                                                window,
 8260                                                                                cx,
 8261                                                                            ))
 8262                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8263                                                                    )
 8264                                                            )
 8265
 8266                                                    )
 8267                                                    .child(
 8268                                                        div()
 8269                                                            .w_full()
 8270                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8271                                                    ),
 8272                                            )
 8273                                            .children(self.render_dock(
 8274                                                DockPosition::Right,
 8275                                                &self.right_dock,
 8276                                                window,
 8277                                                cx,
 8278                                            )),
 8279                                        BottomDockLayout::RightAligned => div()
 8280                                            .flex()
 8281                                            .flex_row()
 8282                                            .h_full()
 8283                                            .children(self.render_dock(
 8284                                                DockPosition::Left,
 8285                                                &self.left_dock,
 8286                                                window,
 8287                                                cx,
 8288                                            ))
 8289
 8290                                            .child(
 8291                                                div()
 8292                                                    .flex()
 8293                                                    .flex_col()
 8294                                                    .flex_1()
 8295                                                    .h_full()
 8296                                                    .child(
 8297                                                        div()
 8298                                                            .flex()
 8299                                                            .flex_row()
 8300                                                            .flex_1()
 8301                                                            .child(
 8302                                                                div()
 8303                                                                    .flex()
 8304                                                                    .flex_col()
 8305                                                                    .flex_1()
 8306                                                                    .overflow_hidden()
 8307                                                                    .child(
 8308                                                                        h_flex()
 8309                                                                            .flex_1()
 8310                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8311                                                                            .child(self.center.render(
 8312                                                                                self.zoomed.as_ref(),
 8313                                                                                &PaneRenderContext {
 8314                                                                                    follower_states:
 8315                                                                                        &self.follower_states,
 8316                                                                                    active_call: self.active_call(),
 8317                                                                                    active_pane: &self.active_pane,
 8318                                                                                    app_state: &self.app_state,
 8319                                                                                    project: &self.project,
 8320                                                                                    workspace: &self.weak_self,
 8321                                                                                },
 8322                                                                                window,
 8323                                                                                cx,
 8324                                                                            ))
 8325                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8326                                                                    )
 8327                                                            )
 8328
 8329                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 8330                                                    )
 8331                                                    .child(
 8332                                                        div()
 8333                                                            .w_full()
 8334                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8335                                                    ),
 8336                                            ),
 8337                                        BottomDockLayout::Contained => div()
 8338                                            .flex()
 8339                                            .flex_row()
 8340                                            .h_full()
 8341                                            .children(self.render_dock(
 8342                                                DockPosition::Left,
 8343                                                &self.left_dock,
 8344                                                window,
 8345                                                cx,
 8346                                            ))
 8347
 8348                                            .child(
 8349                                                div()
 8350                                                    .flex()
 8351                                                    .flex_col()
 8352                                                    .flex_1()
 8353                                                    .overflow_hidden()
 8354                                                    .child(
 8355                                                        h_flex()
 8356                                                            .flex_1()
 8357                                                            .when_some(paddings.0, |this, p| {
 8358                                                                this.child(p.border_r_1())
 8359                                                            })
 8360                                                            .child(self.center.render(
 8361                                                                self.zoomed.as_ref(),
 8362                                                                &PaneRenderContext {
 8363                                                                    follower_states:
 8364                                                                        &self.follower_states,
 8365                                                                    active_call: self.active_call(),
 8366                                                                    active_pane: &self.active_pane,
 8367                                                                    app_state: &self.app_state,
 8368                                                                    project: &self.project,
 8369                                                                    workspace: &self.weak_self,
 8370                                                                },
 8371                                                                window,
 8372                                                                cx,
 8373                                                            ))
 8374                                                            .when_some(paddings.1, |this, p| {
 8375                                                                this.child(p.border_l_1())
 8376                                                            }),
 8377                                                    )
 8378                                                    .children(self.render_dock(
 8379                                                        DockPosition::Bottom,
 8380                                                        &self.bottom_dock,
 8381                                                        window,
 8382                                                        cx,
 8383                                                    )),
 8384                                            )
 8385
 8386                                            .children(self.render_dock(
 8387                                                DockPosition::Right,
 8388                                                &self.right_dock,
 8389                                                window,
 8390                                                cx,
 8391                                            )),
 8392                                    }
 8393                                })
 8394                                .children(self.zoomed.as_ref().and_then(|view| {
 8395                                    let zoomed_view = view.upgrade()?;
 8396                                    let div = div()
 8397                                        .occlude()
 8398                                        .absolute()
 8399                                        .overflow_hidden()
 8400                                        .border_color(colors.border)
 8401                                        .bg(colors.background)
 8402                                        .child(zoomed_view)
 8403                                        .inset_0()
 8404                                        .shadow_lg();
 8405
 8406                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8407                                       return Some(div);
 8408                                    }
 8409
 8410                                    Some(match self.zoomed_position {
 8411                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8412                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8413                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8414                                        None => {
 8415                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8416                                        }
 8417                                    })
 8418                                }))
 8419                                .children(self.render_notifications(window, cx)),
 8420                        )
 8421                        .when(self.status_bar_visible(cx), |parent| {
 8422                            parent.child(self.status_bar.clone())
 8423                        })
 8424                        .child(self.toast_layer.clone()),
 8425                )
 8426    }
 8427}
 8428
 8429impl WorkspaceStore {
 8430    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8431        Self {
 8432            workspaces: Default::default(),
 8433            _subscriptions: vec![
 8434                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8435                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8436            ],
 8437            client,
 8438        }
 8439    }
 8440
 8441    pub fn update_followers(
 8442        &self,
 8443        project_id: Option<u64>,
 8444        update: proto::update_followers::Variant,
 8445        cx: &App,
 8446    ) -> Option<()> {
 8447        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8448        let room_id = active_call.0.room_id(cx)?;
 8449        self.client
 8450            .send(proto::UpdateFollowers {
 8451                room_id,
 8452                project_id,
 8453                variant: Some(update),
 8454            })
 8455            .log_err()
 8456    }
 8457
 8458    pub async fn handle_follow(
 8459        this: Entity<Self>,
 8460        envelope: TypedEnvelope<proto::Follow>,
 8461        mut cx: AsyncApp,
 8462    ) -> Result<proto::FollowResponse> {
 8463        this.update(&mut cx, |this, cx| {
 8464            let follower = Follower {
 8465                project_id: envelope.payload.project_id,
 8466                peer_id: envelope.original_sender_id()?,
 8467            };
 8468
 8469            let mut response = proto::FollowResponse::default();
 8470
 8471            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8472                let Some(workspace) = weak_workspace.upgrade() else {
 8473                    return false;
 8474                };
 8475                window_handle
 8476                    .update(cx, |_, window, cx| {
 8477                        workspace.update(cx, |workspace, cx| {
 8478                            let handler_response =
 8479                                workspace.handle_follow(follower.project_id, window, cx);
 8480                            if let Some(active_view) = handler_response.active_view
 8481                                && workspace.project.read(cx).remote_id() == follower.project_id
 8482                            {
 8483                                response.active_view = Some(active_view)
 8484                            }
 8485                        });
 8486                    })
 8487                    .is_ok()
 8488            });
 8489
 8490            Ok(response)
 8491        })
 8492    }
 8493
 8494    async fn handle_update_followers(
 8495        this: Entity<Self>,
 8496        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8497        mut cx: AsyncApp,
 8498    ) -> Result<()> {
 8499        let leader_id = envelope.original_sender_id()?;
 8500        let update = envelope.payload;
 8501
 8502        this.update(&mut cx, |this, cx| {
 8503            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8504                let Some(workspace) = weak_workspace.upgrade() else {
 8505                    return false;
 8506                };
 8507                window_handle
 8508                    .update(cx, |_, window, cx| {
 8509                        workspace.update(cx, |workspace, cx| {
 8510                            let project_id = workspace.project.read(cx).remote_id();
 8511                            if update.project_id != project_id && update.project_id.is_some() {
 8512                                return;
 8513                            }
 8514                            workspace.handle_update_followers(
 8515                                leader_id,
 8516                                update.clone(),
 8517                                window,
 8518                                cx,
 8519                            );
 8520                        });
 8521                    })
 8522                    .is_ok()
 8523            });
 8524            Ok(())
 8525        })
 8526    }
 8527
 8528    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8529        self.workspaces.iter().map(|(_, weak)| weak)
 8530    }
 8531
 8532    pub fn workspaces_with_windows(
 8533        &self,
 8534    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8535        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8536    }
 8537}
 8538
 8539impl ViewId {
 8540    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8541        Ok(Self {
 8542            creator: message
 8543                .creator
 8544                .map(CollaboratorId::PeerId)
 8545                .context("creator is missing")?,
 8546            id: message.id,
 8547        })
 8548    }
 8549
 8550    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8551        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8552            Some(proto::ViewId {
 8553                creator: Some(peer_id),
 8554                id: self.id,
 8555            })
 8556        } else {
 8557            None
 8558        }
 8559    }
 8560}
 8561
 8562impl FollowerState {
 8563    fn pane(&self) -> &Entity<Pane> {
 8564        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8565    }
 8566}
 8567
 8568pub trait WorkspaceHandle {
 8569    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8570}
 8571
 8572impl WorkspaceHandle for Entity<Workspace> {
 8573    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8574        self.read(cx)
 8575            .worktrees(cx)
 8576            .flat_map(|worktree| {
 8577                let worktree_id = worktree.read(cx).id();
 8578                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8579                    worktree_id,
 8580                    path: f.path.clone(),
 8581                })
 8582            })
 8583            .collect::<Vec<_>>()
 8584    }
 8585}
 8586
 8587pub async fn last_opened_workspace_location(
 8588    db: &WorkspaceDb,
 8589    fs: &dyn fs::Fs,
 8590) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8591    db.last_workspace(fs)
 8592        .await
 8593        .log_err()
 8594        .flatten()
 8595        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8596}
 8597
 8598pub async fn last_session_workspace_locations(
 8599    db: &WorkspaceDb,
 8600    last_session_id: &str,
 8601    last_session_window_stack: Option<Vec<WindowId>>,
 8602    fs: &dyn fs::Fs,
 8603) -> Option<Vec<SessionWorkspace>> {
 8604    db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8605        .await
 8606        .log_err()
 8607}
 8608
 8609pub struct MultiWorkspaceRestoreResult {
 8610    pub window_handle: WindowHandle<MultiWorkspace>,
 8611    pub errors: Vec<anyhow::Error>,
 8612}
 8613
 8614pub async fn restore_multiworkspace(
 8615    multi_workspace: SerializedMultiWorkspace,
 8616    app_state: Arc<AppState>,
 8617    cx: &mut AsyncApp,
 8618) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8619    let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
 8620    let mut group_iter = workspaces.into_iter();
 8621    let first = group_iter
 8622        .next()
 8623        .context("window group must not be empty")?;
 8624
 8625    let window_handle = if first.paths.is_empty() {
 8626        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8627            .await?
 8628    } else {
 8629        let OpenResult { window, .. } = cx
 8630            .update(|cx| {
 8631                Workspace::new_local(
 8632                    first.paths.paths().to_vec(),
 8633                    app_state.clone(),
 8634                    None,
 8635                    None,
 8636                    None,
 8637                    OpenMode::Activate,
 8638                    cx,
 8639                )
 8640            })
 8641            .await?;
 8642        window
 8643    };
 8644
 8645    let mut errors = Vec::new();
 8646
 8647    for session_workspace in group_iter {
 8648        let error = if session_workspace.paths.is_empty() {
 8649            cx.update(|cx| {
 8650                open_workspace_by_id(
 8651                    session_workspace.workspace_id,
 8652                    app_state.clone(),
 8653                    Some(window_handle),
 8654                    cx,
 8655                )
 8656            })
 8657            .await
 8658            .err()
 8659        } else {
 8660            cx.update(|cx| {
 8661                Workspace::new_local(
 8662                    session_workspace.paths.paths().to_vec(),
 8663                    app_state.clone(),
 8664                    Some(window_handle),
 8665                    None,
 8666                    None,
 8667                    OpenMode::Add,
 8668                    cx,
 8669                )
 8670            })
 8671            .await
 8672            .err()
 8673        };
 8674
 8675        if let Some(error) = error {
 8676            errors.push(error);
 8677        }
 8678    }
 8679
 8680    if let Some(target_id) = state.active_workspace_id {
 8681        window_handle
 8682            .update(cx, |multi_workspace, window, cx| {
 8683                let target_index = multi_workspace
 8684                    .workspaces()
 8685                    .iter()
 8686                    .position(|ws| ws.read(cx).database_id() == Some(target_id));
 8687                let index = target_index.unwrap_or(0);
 8688                if let Some(workspace) = multi_workspace.workspaces().get(index).cloned() {
 8689                    multi_workspace.activate(workspace, window, cx);
 8690                }
 8691            })
 8692            .ok();
 8693    } else {
 8694        window_handle
 8695            .update(cx, |multi_workspace, window, cx| {
 8696                if let Some(workspace) = multi_workspace.workspaces().first().cloned() {
 8697                    multi_workspace.activate(workspace, window, cx);
 8698                }
 8699            })
 8700            .ok();
 8701    }
 8702
 8703    if state.sidebar_open {
 8704        window_handle
 8705            .update(cx, |multi_workspace, _, cx| {
 8706                multi_workspace.open_sidebar(cx);
 8707            })
 8708            .ok();
 8709    }
 8710
 8711    if let Some(sidebar_state) = &state.sidebar_state {
 8712        let sidebar_state = sidebar_state.clone();
 8713        window_handle
 8714            .update(cx, |multi_workspace, window, cx| {
 8715                if let Some(sidebar) = multi_workspace.sidebar() {
 8716                    sidebar.restore_serialized_state(&sidebar_state, window, cx);
 8717                }
 8718                multi_workspace.serialize(cx);
 8719            })
 8720            .ok();
 8721    }
 8722
 8723    window_handle
 8724        .update(cx, |_, window, _cx| {
 8725            window.activate_window();
 8726        })
 8727        .ok();
 8728
 8729    Ok(MultiWorkspaceRestoreResult {
 8730        window_handle,
 8731        errors,
 8732    })
 8733}
 8734
 8735actions!(
 8736    collab,
 8737    [
 8738        /// Opens the channel notes for the current call.
 8739        ///
 8740        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8741        /// channel in the collab panel.
 8742        ///
 8743        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8744        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8745        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8746        OpenChannelNotes,
 8747        /// Mutes your microphone.
 8748        Mute,
 8749        /// Deafens yourself (mute both microphone and speakers).
 8750        Deafen,
 8751        /// Leaves the current call.
 8752        LeaveCall,
 8753        /// Shares the current project with collaborators.
 8754        ShareProject,
 8755        /// Shares your screen with collaborators.
 8756        ScreenShare,
 8757        /// Copies the current room name and session id for debugging purposes.
 8758        CopyRoomId,
 8759    ]
 8760);
 8761
 8762/// Opens the channel notes for a specific channel by its ID.
 8763#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8764#[action(namespace = collab)]
 8765#[serde(deny_unknown_fields)]
 8766pub struct OpenChannelNotesById {
 8767    pub channel_id: u64,
 8768}
 8769
 8770actions!(
 8771    zed,
 8772    [
 8773        /// Opens the Zed log file.
 8774        OpenLog,
 8775        /// Reveals the Zed log file in the system file manager.
 8776        RevealLogInFileManager
 8777    ]
 8778);
 8779
 8780async fn join_channel_internal(
 8781    channel_id: ChannelId,
 8782    app_state: &Arc<AppState>,
 8783    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8784    requesting_workspace: Option<WeakEntity<Workspace>>,
 8785    active_call: &dyn AnyActiveCall,
 8786    cx: &mut AsyncApp,
 8787) -> Result<bool> {
 8788    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8789        if !active_call.is_in_room(cx) {
 8790            return (false, false);
 8791        }
 8792
 8793        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8794        let should_prompt = active_call.is_sharing_project(cx)
 8795            && active_call.has_remote_participants(cx)
 8796            && !already_in_channel;
 8797        (should_prompt, already_in_channel)
 8798    });
 8799
 8800    if already_in_channel {
 8801        let task = cx.update(|cx| {
 8802            if let Some((project, host)) = active_call.most_active_project(cx) {
 8803                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8804            } else {
 8805                None
 8806            }
 8807        });
 8808        if let Some(task) = task {
 8809            task.await?;
 8810        }
 8811        return anyhow::Ok(true);
 8812    }
 8813
 8814    if should_prompt {
 8815        if let Some(multi_workspace) = requesting_window {
 8816            let answer = multi_workspace
 8817                .update(cx, |_, window, cx| {
 8818                    window.prompt(
 8819                        PromptLevel::Warning,
 8820                        "Do you want to switch channels?",
 8821                        Some("Leaving this call will unshare your current project."),
 8822                        &["Yes, Join Channel", "Cancel"],
 8823                        cx,
 8824                    )
 8825                })?
 8826                .await;
 8827
 8828            if answer == Ok(1) {
 8829                return Ok(false);
 8830            }
 8831        } else {
 8832            return Ok(false);
 8833        }
 8834    }
 8835
 8836    let client = cx.update(|cx| active_call.client(cx));
 8837
 8838    let mut client_status = client.status();
 8839
 8840    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8841    'outer: loop {
 8842        let Some(status) = client_status.recv().await else {
 8843            anyhow::bail!("error connecting");
 8844        };
 8845
 8846        match status {
 8847            Status::Connecting
 8848            | Status::Authenticating
 8849            | Status::Authenticated
 8850            | Status::Reconnecting
 8851            | Status::Reauthenticating
 8852            | Status::Reauthenticated => continue,
 8853            Status::Connected { .. } => break 'outer,
 8854            Status::SignedOut | Status::AuthenticationError => {
 8855                return Err(ErrorCode::SignedOut.into());
 8856            }
 8857            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8858            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8859                return Err(ErrorCode::Disconnected.into());
 8860            }
 8861        }
 8862    }
 8863
 8864    let joined = cx
 8865        .update(|cx| active_call.join_channel(channel_id, cx))
 8866        .await?;
 8867
 8868    if !joined {
 8869        return anyhow::Ok(true);
 8870    }
 8871
 8872    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8873
 8874    let task = cx.update(|cx| {
 8875        if let Some((project, host)) = active_call.most_active_project(cx) {
 8876            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8877        }
 8878
 8879        // If you are the first to join a channel, see if you should share your project.
 8880        if !active_call.has_remote_participants(cx)
 8881            && !active_call.local_participant_is_guest(cx)
 8882            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8883        {
 8884            let project = workspace.update(cx, |workspace, cx| {
 8885                let project = workspace.project.read(cx);
 8886
 8887                if !active_call.share_on_join(cx) {
 8888                    return None;
 8889                }
 8890
 8891                if (project.is_local() || project.is_via_remote_server())
 8892                    && project.visible_worktrees(cx).any(|tree| {
 8893                        tree.read(cx)
 8894                            .root_entry()
 8895                            .is_some_and(|entry| entry.is_dir())
 8896                    })
 8897                {
 8898                    Some(workspace.project.clone())
 8899                } else {
 8900                    None
 8901                }
 8902            });
 8903            if let Some(project) = project {
 8904                let share_task = active_call.share_project(project, cx);
 8905                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8906                    share_task.await?;
 8907                    Ok(())
 8908                }));
 8909            }
 8910        }
 8911
 8912        None
 8913    });
 8914    if let Some(task) = task {
 8915        task.await?;
 8916        return anyhow::Ok(true);
 8917    }
 8918    anyhow::Ok(false)
 8919}
 8920
 8921pub fn join_channel(
 8922    channel_id: ChannelId,
 8923    app_state: Arc<AppState>,
 8924    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8925    requesting_workspace: Option<WeakEntity<Workspace>>,
 8926    cx: &mut App,
 8927) -> Task<Result<()>> {
 8928    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8929    cx.spawn(async move |cx| {
 8930        let result = join_channel_internal(
 8931            channel_id,
 8932            &app_state,
 8933            requesting_window,
 8934            requesting_workspace,
 8935            &*active_call.0,
 8936            cx,
 8937        )
 8938        .await;
 8939
 8940        // join channel succeeded, and opened a window
 8941        if matches!(result, Ok(true)) {
 8942            return anyhow::Ok(());
 8943        }
 8944
 8945        // find an existing workspace to focus and show call controls
 8946        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8947        if active_window.is_none() {
 8948            // no open workspaces, make one to show the error in (blergh)
 8949            let OpenResult {
 8950                window: window_handle,
 8951                ..
 8952            } = cx
 8953                .update(|cx| {
 8954                    Workspace::new_local(
 8955                        vec![],
 8956                        app_state.clone(),
 8957                        requesting_window,
 8958                        None,
 8959                        None,
 8960                        OpenMode::Activate,
 8961                        cx,
 8962                    )
 8963                })
 8964                .await?;
 8965
 8966            window_handle
 8967                .update(cx, |_, window, _cx| {
 8968                    window.activate_window();
 8969                })
 8970                .ok();
 8971
 8972            if result.is_ok() {
 8973                cx.update(|cx| {
 8974                    cx.dispatch_action(&OpenChannelNotes);
 8975                });
 8976            }
 8977
 8978            active_window = Some(window_handle);
 8979        }
 8980
 8981        if let Err(err) = result {
 8982            log::error!("failed to join channel: {}", err);
 8983            if let Some(active_window) = active_window {
 8984                active_window
 8985                    .update(cx, |_, window, cx| {
 8986                        let detail: SharedString = match err.error_code() {
 8987                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 8988                            ErrorCode::UpgradeRequired => concat!(
 8989                                "Your are running an unsupported version of Zed. ",
 8990                                "Please update to continue."
 8991                            )
 8992                            .into(),
 8993                            ErrorCode::NoSuchChannel => concat!(
 8994                                "No matching channel was found. ",
 8995                                "Please check the link and try again."
 8996                            )
 8997                            .into(),
 8998                            ErrorCode::Forbidden => concat!(
 8999                                "This channel is private, and you do not have access. ",
 9000                                "Please ask someone to add you and try again."
 9001                            )
 9002                            .into(),
 9003                            ErrorCode::Disconnected => {
 9004                                "Please check your internet connection and try again.".into()
 9005                            }
 9006                            _ => format!("{}\n\nPlease try again.", err).into(),
 9007                        };
 9008                        window.prompt(
 9009                            PromptLevel::Critical,
 9010                            "Failed to join channel",
 9011                            Some(&detail),
 9012                            &["Ok"],
 9013                            cx,
 9014                        )
 9015                    })?
 9016                    .await
 9017                    .ok();
 9018            }
 9019        }
 9020
 9021        // return ok, we showed the error to the user.
 9022        anyhow::Ok(())
 9023    })
 9024}
 9025
 9026pub async fn get_any_active_multi_workspace(
 9027    app_state: Arc<AppState>,
 9028    mut cx: AsyncApp,
 9029) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 9030    // find an existing workspace to focus and show call controls
 9031    let active_window = activate_any_workspace_window(&mut cx);
 9032    if active_window.is_none() {
 9033        cx.update(|cx| {
 9034            Workspace::new_local(
 9035                vec![],
 9036                app_state.clone(),
 9037                None,
 9038                None,
 9039                None,
 9040                OpenMode::Activate,
 9041                cx,
 9042            )
 9043        })
 9044        .await?;
 9045    }
 9046    activate_any_workspace_window(&mut cx).context("could not open zed")
 9047}
 9048
 9049fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 9050    cx.update(|cx| {
 9051        if let Some(workspace_window) = cx
 9052            .active_window()
 9053            .and_then(|window| window.downcast::<MultiWorkspace>())
 9054        {
 9055            return Some(workspace_window);
 9056        }
 9057
 9058        for window in cx.windows() {
 9059            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 9060                workspace_window
 9061                    .update(cx, |_, window, _| window.activate_window())
 9062                    .ok();
 9063                return Some(workspace_window);
 9064            }
 9065        }
 9066        None
 9067    })
 9068}
 9069
 9070pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 9071    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 9072}
 9073
 9074pub fn workspace_windows_for_location(
 9075    serialized_location: &SerializedWorkspaceLocation,
 9076    cx: &App,
 9077) -> Vec<WindowHandle<MultiWorkspace>> {
 9078    cx.windows()
 9079        .into_iter()
 9080        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9081        .filter(|multi_workspace| {
 9082            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 9083                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 9084                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 9085                }
 9086                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 9087                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 9088                    a.distro_name == b.distro_name
 9089                }
 9090                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 9091                    a.container_id == b.container_id
 9092                }
 9093                #[cfg(any(test, feature = "test-support"))]
 9094                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 9095                    a.id == b.id
 9096                }
 9097                _ => false,
 9098            };
 9099
 9100            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 9101                multi_workspace.workspaces().iter().any(|workspace| {
 9102                    match workspace.read(cx).workspace_location(cx) {
 9103                        WorkspaceLocation::Location(location, _) => {
 9104                            match (&location, serialized_location) {
 9105                                (
 9106                                    SerializedWorkspaceLocation::Local,
 9107                                    SerializedWorkspaceLocation::Local,
 9108                                ) => true,
 9109                                (
 9110                                    SerializedWorkspaceLocation::Remote(a),
 9111                                    SerializedWorkspaceLocation::Remote(b),
 9112                                ) => same_host(a, b),
 9113                                _ => false,
 9114                            }
 9115                        }
 9116                        _ => false,
 9117                    }
 9118                })
 9119            })
 9120        })
 9121        .collect()
 9122}
 9123
 9124pub async fn find_existing_workspace(
 9125    abs_paths: &[PathBuf],
 9126    open_options: &OpenOptions,
 9127    location: &SerializedWorkspaceLocation,
 9128    cx: &mut AsyncApp,
 9129) -> (
 9130    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 9131    OpenVisible,
 9132) {
 9133    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 9134    let mut open_visible = OpenVisible::All;
 9135    let mut best_match = None;
 9136
 9137    if open_options.open_new_workspace != Some(true) {
 9138        cx.update(|cx| {
 9139            for window in workspace_windows_for_location(location, cx) {
 9140                if let Ok(multi_workspace) = window.read(cx) {
 9141                    for workspace in multi_workspace.workspaces() {
 9142                        let project = workspace.read(cx).project.read(cx);
 9143                        let m = project.visibility_for_paths(
 9144                            abs_paths,
 9145                            open_options.open_new_workspace == None,
 9146                            cx,
 9147                        );
 9148                        if m > best_match {
 9149                            existing = Some((window, workspace.clone()));
 9150                            best_match = m;
 9151                        } else if best_match.is_none()
 9152                            && open_options.open_new_workspace == Some(false)
 9153                        {
 9154                            existing = Some((window, workspace.clone()))
 9155                        }
 9156                    }
 9157                }
 9158            }
 9159        });
 9160
 9161        let all_paths_are_files = existing
 9162            .as_ref()
 9163            .and_then(|(_, target_workspace)| {
 9164                cx.update(|cx| {
 9165                    let workspace = target_workspace.read(cx);
 9166                    let project = workspace.project.read(cx);
 9167                    let path_style = workspace.path_style(cx);
 9168                    Some(!abs_paths.iter().any(|path| {
 9169                        let path = util::paths::SanitizedPath::new(path);
 9170                        project.worktrees(cx).any(|worktree| {
 9171                            let worktree = worktree.read(cx);
 9172                            let abs_path = worktree.abs_path();
 9173                            path_style
 9174                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 9175                                .and_then(|rel| worktree.entry_for_path(&rel))
 9176                                .is_some_and(|e| e.is_dir())
 9177                        })
 9178                    }))
 9179                })
 9180            })
 9181            .unwrap_or(false);
 9182
 9183        if open_options.open_new_workspace.is_none()
 9184            && existing.is_some()
 9185            && open_options.wait
 9186            && all_paths_are_files
 9187        {
 9188            cx.update(|cx| {
 9189                let windows = workspace_windows_for_location(location, cx);
 9190                let window = cx
 9191                    .active_window()
 9192                    .and_then(|window| window.downcast::<MultiWorkspace>())
 9193                    .filter(|window| windows.contains(window))
 9194                    .or_else(|| windows.into_iter().next());
 9195                if let Some(window) = window {
 9196                    if let Ok(multi_workspace) = window.read(cx) {
 9197                        let active_workspace = multi_workspace.workspace().clone();
 9198                        existing = Some((window, active_workspace));
 9199                        open_visible = OpenVisible::None;
 9200                    }
 9201                }
 9202            });
 9203        }
 9204    }
 9205    (existing, open_visible)
 9206}
 9207
 9208#[derive(Default, Clone)]
 9209pub struct OpenOptions {
 9210    pub visible: Option<OpenVisible>,
 9211    pub focus: Option<bool>,
 9212    pub open_new_workspace: Option<bool>,
 9213    pub wait: bool,
 9214    pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9215    pub open_mode: OpenMode,
 9216    pub env: Option<HashMap<String, String>>,
 9217}
 9218
 9219/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 9220/// or [`Workspace::open_workspace_for_paths`].
 9221pub struct OpenResult {
 9222    pub window: WindowHandle<MultiWorkspace>,
 9223    pub workspace: Entity<Workspace>,
 9224    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 9225}
 9226
 9227/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 9228pub fn open_workspace_by_id(
 9229    workspace_id: WorkspaceId,
 9230    app_state: Arc<AppState>,
 9231    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9232    cx: &mut App,
 9233) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 9234    let project_handle = Project::local(
 9235        app_state.client.clone(),
 9236        app_state.node_runtime.clone(),
 9237        app_state.user_store.clone(),
 9238        app_state.languages.clone(),
 9239        app_state.fs.clone(),
 9240        None,
 9241        project::LocalProjectFlags {
 9242            init_worktree_trust: true,
 9243            ..project::LocalProjectFlags::default()
 9244        },
 9245        cx,
 9246    );
 9247
 9248    let db = WorkspaceDb::global(cx);
 9249    let kvp = db::kvp::KeyValueStore::global(cx);
 9250    cx.spawn(async move |cx| {
 9251        let serialized_workspace = db
 9252            .workspace_for_id(workspace_id)
 9253            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 9254
 9255        let centered_layout = serialized_workspace.centered_layout;
 9256
 9257        let (window, workspace) = if let Some(window) = requesting_window {
 9258            let workspace = window.update(cx, |multi_workspace, window, cx| {
 9259                let workspace = cx.new(|cx| {
 9260                    let mut workspace = Workspace::new(
 9261                        Some(workspace_id),
 9262                        project_handle.clone(),
 9263                        app_state.clone(),
 9264                        window,
 9265                        cx,
 9266                    );
 9267                    workspace.centered_layout = centered_layout;
 9268                    workspace
 9269                });
 9270                multi_workspace.add(workspace.clone(), &*window, cx);
 9271                workspace
 9272            })?;
 9273            (window, workspace)
 9274        } else {
 9275            let window_bounds_override = window_bounds_env_override();
 9276
 9277            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 9278                (Some(WindowBounds::Windowed(bounds)), None)
 9279            } else if let Some(display) = serialized_workspace.display
 9280                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 9281            {
 9282                (Some(bounds.0), Some(display))
 9283            } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
 9284                (Some(bounds), Some(display))
 9285            } else {
 9286                (None, None)
 9287            };
 9288
 9289            let options = cx.update(|cx| {
 9290                let mut options = (app_state.build_window_options)(display, cx);
 9291                options.window_bounds = window_bounds;
 9292                options
 9293            });
 9294
 9295            let window = cx.open_window(options, {
 9296                let app_state = app_state.clone();
 9297                let project_handle = project_handle.clone();
 9298                move |window, cx| {
 9299                    let workspace = cx.new(|cx| {
 9300                        let mut workspace = Workspace::new(
 9301                            Some(workspace_id),
 9302                            project_handle,
 9303                            app_state,
 9304                            window,
 9305                            cx,
 9306                        );
 9307                        workspace.centered_layout = centered_layout;
 9308                        workspace
 9309                    });
 9310                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9311                }
 9312            })?;
 9313
 9314            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 9315                multi_workspace.workspace().clone()
 9316            })?;
 9317
 9318            (window, workspace)
 9319        };
 9320
 9321        notify_if_database_failed(window, cx);
 9322
 9323        // Restore items from the serialized workspace
 9324        window
 9325            .update(cx, |_, window, cx| {
 9326                workspace.update(cx, |_workspace, cx| {
 9327                    open_items(Some(serialized_workspace), vec![], window, cx)
 9328                })
 9329            })?
 9330            .await?;
 9331
 9332        window.update(cx, |_, window, cx| {
 9333            workspace.update(cx, |workspace, cx| {
 9334                workspace.serialize_workspace(window, cx);
 9335            });
 9336        })?;
 9337
 9338        Ok(window)
 9339    })
 9340}
 9341
 9342#[allow(clippy::type_complexity)]
 9343pub fn open_paths(
 9344    abs_paths: &[PathBuf],
 9345    app_state: Arc<AppState>,
 9346    open_options: OpenOptions,
 9347    cx: &mut App,
 9348) -> Task<anyhow::Result<OpenResult>> {
 9349    let abs_paths = abs_paths.to_vec();
 9350    #[cfg(target_os = "windows")]
 9351    let wsl_path = abs_paths
 9352        .iter()
 9353        .find_map(|p| util::paths::WslPath::from_path(p));
 9354
 9355    cx.spawn(async move |cx| {
 9356        let (mut existing, mut open_visible) = find_existing_workspace(
 9357            &abs_paths,
 9358            &open_options,
 9359            &SerializedWorkspaceLocation::Local,
 9360            cx,
 9361        )
 9362        .await;
 9363
 9364        // Fallback: if no workspace contains the paths and all paths are files,
 9365        // prefer an existing local workspace window (active window first).
 9366        if open_options.open_new_workspace.is_none() && existing.is_none() {
 9367            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 9368            let all_metadatas = futures::future::join_all(all_paths)
 9369                .await
 9370                .into_iter()
 9371                .filter_map(|result| result.ok().flatten())
 9372                .collect::<Vec<_>>();
 9373
 9374            if all_metadatas.iter().all(|file| !file.is_dir) {
 9375                cx.update(|cx| {
 9376                    let windows = workspace_windows_for_location(
 9377                        &SerializedWorkspaceLocation::Local,
 9378                        cx,
 9379                    );
 9380                    let window = cx
 9381                        .active_window()
 9382                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9383                        .filter(|window| windows.contains(window))
 9384                        .or_else(|| windows.into_iter().next());
 9385                    if let Some(window) = window {
 9386                        if let Ok(multi_workspace) = window.read(cx) {
 9387                            let active_workspace = multi_workspace.workspace().clone();
 9388                            existing = Some((window, active_workspace));
 9389                            open_visible = OpenVisible::None;
 9390                        }
 9391                    }
 9392                });
 9393            }
 9394        }
 9395
 9396        let result = if let Some((existing, target_workspace)) = existing {
 9397            let open_task = existing
 9398                .update(cx, |multi_workspace, window, cx| {
 9399                    window.activate_window();
 9400                    multi_workspace.activate(target_workspace.clone(), window, cx);
 9401                    target_workspace.update(cx, |workspace, cx| {
 9402                        workspace.open_paths(
 9403                            abs_paths,
 9404                            OpenOptions {
 9405                                visible: Some(open_visible),
 9406                                ..Default::default()
 9407                            },
 9408                            None,
 9409                            window,
 9410                            cx,
 9411                        )
 9412                    })
 9413                })?
 9414                .await;
 9415
 9416            _ = existing.update(cx, |multi_workspace, _, cx| {
 9417                let workspace = multi_workspace.workspace().clone();
 9418                workspace.update(cx, |workspace, cx| {
 9419                    for item in open_task.iter().flatten() {
 9420                        if let Err(e) = item {
 9421                            workspace.show_error(&e, cx);
 9422                        }
 9423                    }
 9424                });
 9425            });
 9426
 9427            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9428        } else {
 9429            let result = cx
 9430                .update(move |cx| {
 9431                    Workspace::new_local(
 9432                        abs_paths,
 9433                        app_state.clone(),
 9434                        open_options.requesting_window,
 9435                        open_options.env,
 9436                        None,
 9437                        open_options.open_mode,
 9438                        cx,
 9439                    )
 9440                })
 9441                .await;
 9442
 9443            if let Ok(ref result) = result {
 9444                result.window
 9445                    .update(cx, |_, window, _cx| {
 9446                        window.activate_window();
 9447                    })
 9448                    .log_err();
 9449            }
 9450
 9451            result
 9452        };
 9453
 9454        #[cfg(target_os = "windows")]
 9455        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9456            && let Ok(ref result) = result
 9457        {
 9458            result.window
 9459                .update(cx, move |multi_workspace, _window, cx| {
 9460                    struct OpenInWsl;
 9461                    let workspace = multi_workspace.workspace().clone();
 9462                    workspace.update(cx, |workspace, cx| {
 9463                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9464                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9465                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9466                            cx.new(move |cx| {
 9467                                MessageNotification::new(msg, cx)
 9468                                    .primary_message("Open in WSL")
 9469                                    .primary_icon(IconName::FolderOpen)
 9470                                    .primary_on_click(move |window, cx| {
 9471                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9472                                                distro: remote::WslConnectionOptions {
 9473                                                        distro_name: distro.clone(),
 9474                                                    user: None,
 9475                                                },
 9476                                                paths: vec![path.clone().into()],
 9477                                            }), cx)
 9478                                    })
 9479                            })
 9480                        });
 9481                    });
 9482                })
 9483                .unwrap();
 9484        };
 9485        result
 9486    })
 9487}
 9488
 9489pub fn open_new(
 9490    open_options: OpenOptions,
 9491    app_state: Arc<AppState>,
 9492    cx: &mut App,
 9493    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9494) -> Task<anyhow::Result<()>> {
 9495    let addition = open_options.open_mode;
 9496    let task = Workspace::new_local(
 9497        Vec::new(),
 9498        app_state,
 9499        open_options.requesting_window,
 9500        open_options.env,
 9501        Some(Box::new(init)),
 9502        addition,
 9503        cx,
 9504    );
 9505    cx.spawn(async move |cx| {
 9506        let OpenResult { window, .. } = task.await?;
 9507        window
 9508            .update(cx, |_, window, _cx| {
 9509                window.activate_window();
 9510            })
 9511            .ok();
 9512        Ok(())
 9513    })
 9514}
 9515
 9516pub fn create_and_open_local_file(
 9517    path: &'static Path,
 9518    window: &mut Window,
 9519    cx: &mut Context<Workspace>,
 9520    default_content: impl 'static + Send + FnOnce() -> Rope,
 9521) -> Task<Result<Box<dyn ItemHandle>>> {
 9522    cx.spawn_in(window, async move |workspace, cx| {
 9523        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9524        if !fs.is_file(path).await {
 9525            fs.create_file(path, Default::default()).await?;
 9526            fs.save(path, &default_content(), Default::default())
 9527                .await?;
 9528        }
 9529
 9530        workspace
 9531            .update_in(cx, |workspace, window, cx| {
 9532                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9533                    let path = workspace
 9534                        .project
 9535                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9536                    cx.spawn_in(window, async move |workspace, cx| {
 9537                        let path = path.await?;
 9538
 9539                        let path = fs.canonicalize(&path).await.unwrap_or(path);
 9540
 9541                        let mut items = workspace
 9542                            .update_in(cx, |workspace, window, cx| {
 9543                                workspace.open_paths(
 9544                                    vec![path.to_path_buf()],
 9545                                    OpenOptions {
 9546                                        visible: Some(OpenVisible::None),
 9547                                        ..Default::default()
 9548                                    },
 9549                                    None,
 9550                                    window,
 9551                                    cx,
 9552                                )
 9553                            })?
 9554                            .await;
 9555                        let item = items.pop().flatten();
 9556                        item.with_context(|| format!("path {path:?} is not a file"))?
 9557                    })
 9558                })
 9559            })?
 9560            .await?
 9561            .await
 9562    })
 9563}
 9564
 9565pub fn open_remote_project_with_new_connection(
 9566    window: WindowHandle<MultiWorkspace>,
 9567    remote_connection: Arc<dyn RemoteConnection>,
 9568    cancel_rx: oneshot::Receiver<()>,
 9569    delegate: Arc<dyn RemoteClientDelegate>,
 9570    app_state: Arc<AppState>,
 9571    paths: Vec<PathBuf>,
 9572    cx: &mut App,
 9573) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9574    cx.spawn(async move |cx| {
 9575        let (workspace_id, serialized_workspace) =
 9576            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9577                .await?;
 9578
 9579        let session = match cx
 9580            .update(|cx| {
 9581                remote::RemoteClient::new(
 9582                    ConnectionIdentifier::Workspace(workspace_id.0),
 9583                    remote_connection,
 9584                    cancel_rx,
 9585                    delegate,
 9586                    cx,
 9587                )
 9588            })
 9589            .await?
 9590        {
 9591            Some(result) => result,
 9592            None => return Ok(Vec::new()),
 9593        };
 9594
 9595        let project = cx.update(|cx| {
 9596            project::Project::remote(
 9597                session,
 9598                app_state.client.clone(),
 9599                app_state.node_runtime.clone(),
 9600                app_state.user_store.clone(),
 9601                app_state.languages.clone(),
 9602                app_state.fs.clone(),
 9603                true,
 9604                cx,
 9605            )
 9606        });
 9607
 9608        open_remote_project_inner(
 9609            project,
 9610            paths,
 9611            workspace_id,
 9612            serialized_workspace,
 9613            app_state,
 9614            window,
 9615            cx,
 9616        )
 9617        .await
 9618    })
 9619}
 9620
 9621pub fn open_remote_project_with_existing_connection(
 9622    connection_options: RemoteConnectionOptions,
 9623    project: Entity<Project>,
 9624    paths: Vec<PathBuf>,
 9625    app_state: Arc<AppState>,
 9626    window: WindowHandle<MultiWorkspace>,
 9627    cx: &mut AsyncApp,
 9628) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9629    cx.spawn(async move |cx| {
 9630        let (workspace_id, serialized_workspace) =
 9631            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9632
 9633        open_remote_project_inner(
 9634            project,
 9635            paths,
 9636            workspace_id,
 9637            serialized_workspace,
 9638            app_state,
 9639            window,
 9640            cx,
 9641        )
 9642        .await
 9643    })
 9644}
 9645
 9646async fn open_remote_project_inner(
 9647    project: Entity<Project>,
 9648    paths: Vec<PathBuf>,
 9649    workspace_id: WorkspaceId,
 9650    serialized_workspace: Option<SerializedWorkspace>,
 9651    app_state: Arc<AppState>,
 9652    window: WindowHandle<MultiWorkspace>,
 9653    cx: &mut AsyncApp,
 9654) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9655    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9656    let toolchains = db.toolchains(workspace_id).await?;
 9657    for (toolchain, worktree_path, path) in toolchains {
 9658        project
 9659            .update(cx, |this, cx| {
 9660                let Some(worktree_id) =
 9661                    this.find_worktree(&worktree_path, cx)
 9662                        .and_then(|(worktree, rel_path)| {
 9663                            if rel_path.is_empty() {
 9664                                Some(worktree.read(cx).id())
 9665                            } else {
 9666                                None
 9667                            }
 9668                        })
 9669                else {
 9670                    return Task::ready(None);
 9671                };
 9672
 9673                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9674            })
 9675            .await;
 9676    }
 9677    let mut project_paths_to_open = vec![];
 9678    let mut project_path_errors = vec![];
 9679
 9680    for path in paths {
 9681        let result = cx
 9682            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9683            .await;
 9684        match result {
 9685            Ok((_, project_path)) => {
 9686                project_paths_to_open.push((path.clone(), Some(project_path)));
 9687            }
 9688            Err(error) => {
 9689                project_path_errors.push(error);
 9690            }
 9691        };
 9692    }
 9693
 9694    if project_paths_to_open.is_empty() {
 9695        return Err(project_path_errors.pop().context("no paths given")?);
 9696    }
 9697
 9698    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9699        telemetry::event!("SSH Project Opened");
 9700
 9701        let new_workspace = cx.new(|cx| {
 9702            let mut workspace =
 9703                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9704            workspace.update_history(cx);
 9705
 9706            if let Some(ref serialized) = serialized_workspace {
 9707                workspace.centered_layout = serialized.centered_layout;
 9708            }
 9709
 9710            workspace
 9711        });
 9712
 9713        multi_workspace.activate(new_workspace.clone(), window, cx);
 9714        new_workspace
 9715    })?;
 9716
 9717    let items = window
 9718        .update(cx, |_, window, cx| {
 9719            window.activate_window();
 9720            workspace.update(cx, |_workspace, cx| {
 9721                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9722            })
 9723        })?
 9724        .await?;
 9725
 9726    workspace.update(cx, |workspace, cx| {
 9727        for error in project_path_errors {
 9728            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9729                if let Some(path) = error.error_tag("path") {
 9730                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9731                }
 9732            } else {
 9733                workspace.show_error(&error, cx)
 9734            }
 9735        }
 9736    });
 9737
 9738    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9739}
 9740
 9741fn deserialize_remote_project(
 9742    connection_options: RemoteConnectionOptions,
 9743    paths: Vec<PathBuf>,
 9744    cx: &AsyncApp,
 9745) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9746    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9747    cx.background_spawn(async move {
 9748        let remote_connection_id = db
 9749            .get_or_create_remote_connection(connection_options)
 9750            .await?;
 9751
 9752        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
 9753
 9754        let workspace_id = if let Some(workspace_id) =
 9755            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9756        {
 9757            workspace_id
 9758        } else {
 9759            db.next_id().await?
 9760        };
 9761
 9762        Ok((workspace_id, serialized_workspace))
 9763    })
 9764}
 9765
 9766pub fn join_in_room_project(
 9767    project_id: u64,
 9768    follow_user_id: u64,
 9769    app_state: Arc<AppState>,
 9770    cx: &mut App,
 9771) -> Task<Result<()>> {
 9772    let windows = cx.windows();
 9773    cx.spawn(async move |cx| {
 9774        let existing_window_and_workspace: Option<(
 9775            WindowHandle<MultiWorkspace>,
 9776            Entity<Workspace>,
 9777        )> = windows.into_iter().find_map(|window_handle| {
 9778            window_handle
 9779                .downcast::<MultiWorkspace>()
 9780                .and_then(|window_handle| {
 9781                    window_handle
 9782                        .update(cx, |multi_workspace, _window, cx| {
 9783                            for workspace in multi_workspace.workspaces() {
 9784                                if workspace.read(cx).project().read(cx).remote_id()
 9785                                    == Some(project_id)
 9786                                {
 9787                                    return Some((window_handle, workspace.clone()));
 9788                                }
 9789                            }
 9790                            None
 9791                        })
 9792                        .unwrap_or(None)
 9793                })
 9794        });
 9795
 9796        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9797            existing_window_and_workspace
 9798        {
 9799            existing_window
 9800                .update(cx, |multi_workspace, window, cx| {
 9801                    multi_workspace.activate(target_workspace, window, cx);
 9802                })
 9803                .ok();
 9804            existing_window
 9805        } else {
 9806            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9807            let project = cx
 9808                .update(|cx| {
 9809                    active_call.0.join_project(
 9810                        project_id,
 9811                        app_state.languages.clone(),
 9812                        app_state.fs.clone(),
 9813                        cx,
 9814                    )
 9815                })
 9816                .await?;
 9817
 9818            let window_bounds_override = window_bounds_env_override();
 9819            cx.update(|cx| {
 9820                let mut options = (app_state.build_window_options)(None, cx);
 9821                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9822                cx.open_window(options, |window, cx| {
 9823                    let workspace = cx.new(|cx| {
 9824                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9825                    });
 9826                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9827                })
 9828            })?
 9829        };
 9830
 9831        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9832            cx.activate(true);
 9833            window.activate_window();
 9834
 9835            // We set the active workspace above, so this is the correct workspace.
 9836            let workspace = multi_workspace.workspace().clone();
 9837            workspace.update(cx, |workspace, cx| {
 9838                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9839                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9840                    .or_else(|| {
 9841                        // If we couldn't follow the given user, follow the host instead.
 9842                        let collaborator = workspace
 9843                            .project()
 9844                            .read(cx)
 9845                            .collaborators()
 9846                            .values()
 9847                            .find(|collaborator| collaborator.is_host)?;
 9848                        Some(collaborator.peer_id)
 9849                    });
 9850
 9851                if let Some(follow_peer_id) = follow_peer_id {
 9852                    workspace.follow(follow_peer_id, window, cx);
 9853                }
 9854            });
 9855        })?;
 9856
 9857        anyhow::Ok(())
 9858    })
 9859}
 9860
 9861pub fn reload(cx: &mut App) {
 9862    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9863    let mut workspace_windows = cx
 9864        .windows()
 9865        .into_iter()
 9866        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9867        .collect::<Vec<_>>();
 9868
 9869    // If multiple windows have unsaved changes, and need a save prompt,
 9870    // prompt in the active window before switching to a different window.
 9871    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9872
 9873    let mut prompt = None;
 9874    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9875        prompt = window
 9876            .update(cx, |_, window, cx| {
 9877                window.prompt(
 9878                    PromptLevel::Info,
 9879                    "Are you sure you want to restart?",
 9880                    None,
 9881                    &["Restart", "Cancel"],
 9882                    cx,
 9883                )
 9884            })
 9885            .ok();
 9886    }
 9887
 9888    cx.spawn(async move |cx| {
 9889        if let Some(prompt) = prompt {
 9890            let answer = prompt.await?;
 9891            if answer != 0 {
 9892                return anyhow::Ok(());
 9893            }
 9894        }
 9895
 9896        // If the user cancels any save prompt, then keep the app open.
 9897        for window in workspace_windows {
 9898            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9899                let workspace = multi_workspace.workspace().clone();
 9900                workspace.update(cx, |workspace, cx| {
 9901                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9902                })
 9903            }) && !should_close.await?
 9904            {
 9905                return anyhow::Ok(());
 9906            }
 9907        }
 9908        cx.update(|cx| cx.restart());
 9909        anyhow::Ok(())
 9910    })
 9911    .detach_and_log_err(cx);
 9912}
 9913
 9914fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9915    let mut parts = value.split(',');
 9916    let x: usize = parts.next()?.parse().ok()?;
 9917    let y: usize = parts.next()?.parse().ok()?;
 9918    Some(point(px(x as f32), px(y as f32)))
 9919}
 9920
 9921fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9922    let mut parts = value.split(',');
 9923    let width: usize = parts.next()?.parse().ok()?;
 9924    let height: usize = parts.next()?.parse().ok()?;
 9925    Some(size(px(width as f32), px(height as f32)))
 9926}
 9927
 9928/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9929/// appropriate.
 9930///
 9931/// The `border_radius_tiling` parameter allows overriding which corners get
 9932/// rounded, independently of the actual window tiling state. This is used
 9933/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9934/// we want square corners on the left (so the sidebar appears flush with the
 9935/// window edge) but we still need the shadow padding for proper visual
 9936/// appearance. Unlike actual window tiling, this only affects border radius -
 9937/// not padding or shadows.
 9938pub fn client_side_decorations(
 9939    element: impl IntoElement,
 9940    window: &mut Window,
 9941    cx: &mut App,
 9942    border_radius_tiling: Tiling,
 9943) -> Stateful<Div> {
 9944    const BORDER_SIZE: Pixels = px(1.0);
 9945    let decorations = window.window_decorations();
 9946    let tiling = match decorations {
 9947        Decorations::Server => Tiling::default(),
 9948        Decorations::Client { tiling } => tiling,
 9949    };
 9950
 9951    match decorations {
 9952        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9953        Decorations::Server => window.set_client_inset(px(0.0)),
 9954    }
 9955
 9956    struct GlobalResizeEdge(ResizeEdge);
 9957    impl Global for GlobalResizeEdge {}
 9958
 9959    div()
 9960        .id("window-backdrop")
 9961        .bg(transparent_black())
 9962        .map(|div| match decorations {
 9963            Decorations::Server => div,
 9964            Decorations::Client { .. } => div
 9965                .when(
 9966                    !(tiling.top
 9967                        || tiling.right
 9968                        || border_radius_tiling.top
 9969                        || border_radius_tiling.right),
 9970                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9971                )
 9972                .when(
 9973                    !(tiling.top
 9974                        || tiling.left
 9975                        || border_radius_tiling.top
 9976                        || border_radius_tiling.left),
 9977                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9978                )
 9979                .when(
 9980                    !(tiling.bottom
 9981                        || tiling.right
 9982                        || border_radius_tiling.bottom
 9983                        || border_radius_tiling.right),
 9984                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9985                )
 9986                .when(
 9987                    !(tiling.bottom
 9988                        || tiling.left
 9989                        || border_radius_tiling.bottom
 9990                        || border_radius_tiling.left),
 9991                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9992                )
 9993                .when(!tiling.top, |div| {
 9994                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9995                })
 9996                .when(!tiling.bottom, |div| {
 9997                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9998                })
 9999                .when(!tiling.left, |div| {
10000                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10001                })
10002                .when(!tiling.right, |div| {
10003                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10004                })
10005                .on_mouse_move(move |e, window, cx| {
10006                    let size = window.window_bounds().get_bounds().size;
10007                    let pos = e.position;
10008
10009                    let new_edge =
10010                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10011
10012                    let edge = cx.try_global::<GlobalResizeEdge>();
10013                    if new_edge != edge.map(|edge| edge.0) {
10014                        window
10015                            .window_handle()
10016                            .update(cx, |workspace, _, cx| {
10017                                cx.notify(workspace.entity_id());
10018                            })
10019                            .ok();
10020                    }
10021                })
10022                .on_mouse_down(MouseButton::Left, move |e, window, _| {
10023                    let size = window.window_bounds().get_bounds().size;
10024                    let pos = e.position;
10025
10026                    let edge = match resize_edge(
10027                        pos,
10028                        theme::CLIENT_SIDE_DECORATION_SHADOW,
10029                        size,
10030                        tiling,
10031                    ) {
10032                        Some(value) => value,
10033                        None => return,
10034                    };
10035
10036                    window.start_window_resize(edge);
10037                }),
10038        })
10039        .size_full()
10040        .child(
10041            div()
10042                .cursor(CursorStyle::Arrow)
10043                .map(|div| match decorations {
10044                    Decorations::Server => div,
10045                    Decorations::Client { .. } => div
10046                        .border_color(cx.theme().colors().border)
10047                        .when(
10048                            !(tiling.top
10049                                || tiling.right
10050                                || border_radius_tiling.top
10051                                || border_radius_tiling.right),
10052                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10053                        )
10054                        .when(
10055                            !(tiling.top
10056                                || tiling.left
10057                                || border_radius_tiling.top
10058                                || border_radius_tiling.left),
10059                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10060                        )
10061                        .when(
10062                            !(tiling.bottom
10063                                || tiling.right
10064                                || border_radius_tiling.bottom
10065                                || border_radius_tiling.right),
10066                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10067                        )
10068                        .when(
10069                            !(tiling.bottom
10070                                || tiling.left
10071                                || border_radius_tiling.bottom
10072                                || border_radius_tiling.left),
10073                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10074                        )
10075                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10076                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10077                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10078                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10079                        .when(!tiling.is_tiled(), |div| {
10080                            div.shadow(vec![gpui::BoxShadow {
10081                                color: Hsla {
10082                                    h: 0.,
10083                                    s: 0.,
10084                                    l: 0.,
10085                                    a: 0.4,
10086                                },
10087                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10088                                spread_radius: px(0.),
10089                                offset: point(px(0.0), px(0.0)),
10090                            }])
10091                        }),
10092                })
10093                .on_mouse_move(|_e, _, cx| {
10094                    cx.stop_propagation();
10095                })
10096                .size_full()
10097                .child(element),
10098        )
10099        .map(|div| match decorations {
10100            Decorations::Server => div,
10101            Decorations::Client { tiling, .. } => div.child(
10102                canvas(
10103                    |_bounds, window, _| {
10104                        window.insert_hitbox(
10105                            Bounds::new(
10106                                point(px(0.0), px(0.0)),
10107                                window.window_bounds().get_bounds().size,
10108                            ),
10109                            HitboxBehavior::Normal,
10110                        )
10111                    },
10112                    move |_bounds, hitbox, window, cx| {
10113                        let mouse = window.mouse_position();
10114                        let size = window.window_bounds().get_bounds().size;
10115                        let Some(edge) =
10116                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10117                        else {
10118                            return;
10119                        };
10120                        cx.set_global(GlobalResizeEdge(edge));
10121                        window.set_cursor_style(
10122                            match edge {
10123                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10124                                ResizeEdge::Left | ResizeEdge::Right => {
10125                                    CursorStyle::ResizeLeftRight
10126                                }
10127                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10128                                    CursorStyle::ResizeUpLeftDownRight
10129                                }
10130                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10131                                    CursorStyle::ResizeUpRightDownLeft
10132                                }
10133                            },
10134                            &hitbox,
10135                        );
10136                    },
10137                )
10138                .size_full()
10139                .absolute(),
10140            ),
10141        })
10142}
10143
10144fn resize_edge(
10145    pos: Point<Pixels>,
10146    shadow_size: Pixels,
10147    window_size: Size<Pixels>,
10148    tiling: Tiling,
10149) -> Option<ResizeEdge> {
10150    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10151    if bounds.contains(&pos) {
10152        return None;
10153    }
10154
10155    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10156    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10157    if !tiling.top && top_left_bounds.contains(&pos) {
10158        return Some(ResizeEdge::TopLeft);
10159    }
10160
10161    let top_right_bounds = Bounds::new(
10162        Point::new(window_size.width - corner_size.width, px(0.)),
10163        corner_size,
10164    );
10165    if !tiling.top && top_right_bounds.contains(&pos) {
10166        return Some(ResizeEdge::TopRight);
10167    }
10168
10169    let bottom_left_bounds = Bounds::new(
10170        Point::new(px(0.), window_size.height - corner_size.height),
10171        corner_size,
10172    );
10173    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10174        return Some(ResizeEdge::BottomLeft);
10175    }
10176
10177    let bottom_right_bounds = Bounds::new(
10178        Point::new(
10179            window_size.width - corner_size.width,
10180            window_size.height - corner_size.height,
10181        ),
10182        corner_size,
10183    );
10184    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10185        return Some(ResizeEdge::BottomRight);
10186    }
10187
10188    if !tiling.top && pos.y < shadow_size {
10189        Some(ResizeEdge::Top)
10190    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10191        Some(ResizeEdge::Bottom)
10192    } else if !tiling.left && pos.x < shadow_size {
10193        Some(ResizeEdge::Left)
10194    } else if !tiling.right && pos.x > window_size.width - shadow_size {
10195        Some(ResizeEdge::Right)
10196    } else {
10197        None
10198    }
10199}
10200
10201fn join_pane_into_active(
10202    active_pane: &Entity<Pane>,
10203    pane: &Entity<Pane>,
10204    window: &mut Window,
10205    cx: &mut App,
10206) {
10207    if pane == active_pane {
10208    } else if pane.read(cx).items_len() == 0 {
10209        pane.update(cx, |_, cx| {
10210            cx.emit(pane::Event::Remove {
10211                focus_on_pane: None,
10212            });
10213        })
10214    } else {
10215        move_all_items(pane, active_pane, window, cx);
10216    }
10217}
10218
10219fn move_all_items(
10220    from_pane: &Entity<Pane>,
10221    to_pane: &Entity<Pane>,
10222    window: &mut Window,
10223    cx: &mut App,
10224) {
10225    let destination_is_different = from_pane != to_pane;
10226    let mut moved_items = 0;
10227    for (item_ix, item_handle) in from_pane
10228        .read(cx)
10229        .items()
10230        .enumerate()
10231        .map(|(ix, item)| (ix, item.clone()))
10232        .collect::<Vec<_>>()
10233    {
10234        let ix = item_ix - moved_items;
10235        if destination_is_different {
10236            // Close item from previous pane
10237            from_pane.update(cx, |source, cx| {
10238                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10239            });
10240            moved_items += 1;
10241        }
10242
10243        // This automatically removes duplicate items in the pane
10244        to_pane.update(cx, |destination, cx| {
10245            destination.add_item(item_handle, true, true, None, window, cx);
10246            window.focus(&destination.focus_handle(cx), cx)
10247        });
10248    }
10249}
10250
10251pub fn move_item(
10252    source: &Entity<Pane>,
10253    destination: &Entity<Pane>,
10254    item_id_to_move: EntityId,
10255    destination_index: usize,
10256    activate: bool,
10257    window: &mut Window,
10258    cx: &mut App,
10259) {
10260    let Some((item_ix, item_handle)) = source
10261        .read(cx)
10262        .items()
10263        .enumerate()
10264        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10265        .map(|(ix, item)| (ix, item.clone()))
10266    else {
10267        // Tab was closed during drag
10268        return;
10269    };
10270
10271    if source != destination {
10272        // Close item from previous pane
10273        source.update(cx, |source, cx| {
10274            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10275        });
10276    }
10277
10278    // This automatically removes duplicate items in the pane
10279    destination.update(cx, |destination, cx| {
10280        destination.add_item_inner(
10281            item_handle,
10282            activate,
10283            activate,
10284            activate,
10285            Some(destination_index),
10286            window,
10287            cx,
10288        );
10289        if activate {
10290            window.focus(&destination.focus_handle(cx), cx)
10291        }
10292    });
10293}
10294
10295pub fn move_active_item(
10296    source: &Entity<Pane>,
10297    destination: &Entity<Pane>,
10298    focus_destination: bool,
10299    close_if_empty: bool,
10300    window: &mut Window,
10301    cx: &mut App,
10302) {
10303    if source == destination {
10304        return;
10305    }
10306    let Some(active_item) = source.read(cx).active_item() else {
10307        return;
10308    };
10309    source.update(cx, |source_pane, cx| {
10310        let item_id = active_item.item_id();
10311        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10312        destination.update(cx, |target_pane, cx| {
10313            target_pane.add_item(
10314                active_item,
10315                focus_destination,
10316                focus_destination,
10317                Some(target_pane.items_len()),
10318                window,
10319                cx,
10320            );
10321        });
10322    });
10323}
10324
10325pub fn clone_active_item(
10326    workspace_id: Option<WorkspaceId>,
10327    source: &Entity<Pane>,
10328    destination: &Entity<Pane>,
10329    focus_destination: bool,
10330    window: &mut Window,
10331    cx: &mut App,
10332) {
10333    if source == destination {
10334        return;
10335    }
10336    let Some(active_item) = source.read(cx).active_item() else {
10337        return;
10338    };
10339    if !active_item.can_split(cx) {
10340        return;
10341    }
10342    let destination = destination.downgrade();
10343    let task = active_item.clone_on_split(workspace_id, window, cx);
10344    window
10345        .spawn(cx, async move |cx| {
10346            let Some(clone) = task.await else {
10347                return;
10348            };
10349            destination
10350                .update_in(cx, |target_pane, window, cx| {
10351                    target_pane.add_item(
10352                        clone,
10353                        focus_destination,
10354                        focus_destination,
10355                        Some(target_pane.items_len()),
10356                        window,
10357                        cx,
10358                    );
10359                })
10360                .log_err();
10361        })
10362        .detach();
10363}
10364
10365#[derive(Debug)]
10366pub struct WorkspacePosition {
10367    pub window_bounds: Option<WindowBounds>,
10368    pub display: Option<Uuid>,
10369    pub centered_layout: bool,
10370}
10371
10372pub fn remote_workspace_position_from_db(
10373    connection_options: RemoteConnectionOptions,
10374    paths_to_open: &[PathBuf],
10375    cx: &App,
10376) -> Task<Result<WorkspacePosition>> {
10377    let paths = paths_to_open.to_vec();
10378    let db = WorkspaceDb::global(cx);
10379    let kvp = db::kvp::KeyValueStore::global(cx);
10380
10381    cx.background_spawn(async move {
10382        let remote_connection_id = db
10383            .get_or_create_remote_connection(connection_options)
10384            .await
10385            .context("fetching serialized ssh project")?;
10386        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10387
10388        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10389            (Some(WindowBounds::Windowed(bounds)), None)
10390        } else {
10391            let restorable_bounds = serialized_workspace
10392                .as_ref()
10393                .and_then(|workspace| {
10394                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10395                })
10396                .or_else(|| persistence::read_default_window_bounds(&kvp));
10397
10398            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10399                (Some(serialized_bounds), Some(serialized_display))
10400            } else {
10401                (None, None)
10402            }
10403        };
10404
10405        let centered_layout = serialized_workspace
10406            .as_ref()
10407            .map(|w| w.centered_layout)
10408            .unwrap_or(false);
10409
10410        Ok(WorkspacePosition {
10411            window_bounds,
10412            display,
10413            centered_layout,
10414        })
10415    })
10416}
10417
10418pub fn with_active_or_new_workspace(
10419    cx: &mut App,
10420    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10421) {
10422    match cx
10423        .active_window()
10424        .and_then(|w| w.downcast::<MultiWorkspace>())
10425    {
10426        Some(multi_workspace) => {
10427            cx.defer(move |cx| {
10428                multi_workspace
10429                    .update(cx, |multi_workspace, window, cx| {
10430                        let workspace = multi_workspace.workspace().clone();
10431                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10432                    })
10433                    .log_err();
10434            });
10435        }
10436        None => {
10437            let app_state = AppState::global(cx);
10438            open_new(
10439                OpenOptions::default(),
10440                app_state,
10441                cx,
10442                move |workspace, window, cx| f(workspace, window, cx),
10443            )
10444            .detach_and_log_err(cx);
10445        }
10446    }
10447}
10448
10449/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10450/// key. This migration path only runs once per panel per workspace.
10451fn load_legacy_panel_size(
10452    panel_key: &str,
10453    dock_position: DockPosition,
10454    workspace: &Workspace,
10455    cx: &mut App,
10456) -> Option<Pixels> {
10457    #[derive(Deserialize)]
10458    struct LegacyPanelState {
10459        #[serde(default)]
10460        width: Option<Pixels>,
10461        #[serde(default)]
10462        height: Option<Pixels>,
10463    }
10464
10465    let workspace_id = workspace
10466        .database_id()
10467        .map(|id| i64::from(id).to_string())
10468        .or_else(|| workspace.session_id())?;
10469
10470    let legacy_key = match panel_key {
10471        "ProjectPanel" => {
10472            format!("{}-{:?}", "ProjectPanel", workspace_id)
10473        }
10474        "OutlinePanel" => {
10475            format!("{}-{:?}", "OutlinePanel", workspace_id)
10476        }
10477        "GitPanel" => {
10478            format!("{}-{:?}", "GitPanel", workspace_id)
10479        }
10480        "TerminalPanel" => {
10481            format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10482        }
10483        _ => return None,
10484    };
10485
10486    let kvp = db::kvp::KeyValueStore::global(cx);
10487    let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10488    let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10489    let size = match dock_position {
10490        DockPosition::Bottom => state.height,
10491        DockPosition::Left | DockPosition::Right => state.width,
10492    }?;
10493
10494    cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10495        .detach_and_log_err(cx);
10496
10497    Some(size)
10498}
10499
10500#[cfg(test)]
10501mod tests {
10502    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10503
10504    use super::*;
10505    use crate::{
10506        dock::{PanelEvent, test::TestPanel},
10507        item::{
10508            ItemBufferKind, ItemEvent,
10509            test::{TestItem, TestProjectItem},
10510        },
10511    };
10512    use fs::FakeFs;
10513    use gpui::{
10514        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10515        UpdateGlobal, VisualTestContext, px,
10516    };
10517    use project::{Project, ProjectEntryId};
10518    use serde_json::json;
10519    use settings::SettingsStore;
10520    use util::path;
10521    use util::rel_path::rel_path;
10522
10523    #[gpui::test]
10524    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10525        init_test(cx);
10526
10527        let fs = FakeFs::new(cx.executor());
10528        let project = Project::test(fs, [], cx).await;
10529        let (workspace, cx) =
10530            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10531
10532        // Adding an item with no ambiguity renders the tab without detail.
10533        let item1 = cx.new(|cx| {
10534            let mut item = TestItem::new(cx);
10535            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10536            item
10537        });
10538        workspace.update_in(cx, |workspace, window, cx| {
10539            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10540        });
10541        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10542
10543        // Adding an item that creates ambiguity increases the level of detail on
10544        // both tabs.
10545        let item2 = cx.new_window_entity(|_window, cx| {
10546            let mut item = TestItem::new(cx);
10547            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10548            item
10549        });
10550        workspace.update_in(cx, |workspace, window, cx| {
10551            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10552        });
10553        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10554        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10555
10556        // Adding an item that creates ambiguity increases the level of detail only
10557        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10558        // we stop at the highest detail available.
10559        let item3 = cx.new(|cx| {
10560            let mut item = TestItem::new(cx);
10561            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10562            item
10563        });
10564        workspace.update_in(cx, |workspace, window, cx| {
10565            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10566        });
10567        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10568        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10569        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10570    }
10571
10572    #[gpui::test]
10573    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10574        init_test(cx);
10575
10576        let fs = FakeFs::new(cx.executor());
10577        fs.insert_tree(
10578            "/root1",
10579            json!({
10580                "one.txt": "",
10581                "two.txt": "",
10582            }),
10583        )
10584        .await;
10585        fs.insert_tree(
10586            "/root2",
10587            json!({
10588                "three.txt": "",
10589            }),
10590        )
10591        .await;
10592
10593        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10594        let (workspace, cx) =
10595            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10596        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10597        let worktree_id = project.update(cx, |project, cx| {
10598            project.worktrees(cx).next().unwrap().read(cx).id()
10599        });
10600
10601        let item1 = cx.new(|cx| {
10602            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10603        });
10604        let item2 = cx.new(|cx| {
10605            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10606        });
10607
10608        // Add an item to an empty pane
10609        workspace.update_in(cx, |workspace, window, cx| {
10610            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10611        });
10612        project.update(cx, |project, cx| {
10613            assert_eq!(
10614                project.active_entry(),
10615                project
10616                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10617                    .map(|e| e.id)
10618            );
10619        });
10620        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10621
10622        // Add a second item to a non-empty pane
10623        workspace.update_in(cx, |workspace, window, cx| {
10624            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10625        });
10626        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10627        project.update(cx, |project, cx| {
10628            assert_eq!(
10629                project.active_entry(),
10630                project
10631                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10632                    .map(|e| e.id)
10633            );
10634        });
10635
10636        // Close the active item
10637        pane.update_in(cx, |pane, window, cx| {
10638            pane.close_active_item(&Default::default(), window, cx)
10639        })
10640        .await
10641        .unwrap();
10642        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10643        project.update(cx, |project, cx| {
10644            assert_eq!(
10645                project.active_entry(),
10646                project
10647                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10648                    .map(|e| e.id)
10649            );
10650        });
10651
10652        // Add a project folder
10653        project
10654            .update(cx, |project, cx| {
10655                project.find_or_create_worktree("root2", true, cx)
10656            })
10657            .await
10658            .unwrap();
10659        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10660
10661        // Remove a project folder
10662        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10663        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10664    }
10665
10666    #[gpui::test]
10667    async fn test_close_window(cx: &mut TestAppContext) {
10668        init_test(cx);
10669
10670        let fs = FakeFs::new(cx.executor());
10671        fs.insert_tree("/root", json!({ "one": "" })).await;
10672
10673        let project = Project::test(fs, ["root".as_ref()], cx).await;
10674        let (workspace, cx) =
10675            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10676
10677        // When there are no dirty items, there's nothing to do.
10678        let item1 = cx.new(TestItem::new);
10679        workspace.update_in(cx, |w, window, cx| {
10680            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10681        });
10682        let task = workspace.update_in(cx, |w, window, cx| {
10683            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10684        });
10685        assert!(task.await.unwrap());
10686
10687        // When there are dirty untitled items, prompt to save each one. If the user
10688        // cancels any prompt, then abort.
10689        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10690        let item3 = cx.new(|cx| {
10691            TestItem::new(cx)
10692                .with_dirty(true)
10693                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10694        });
10695        workspace.update_in(cx, |w, window, cx| {
10696            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10697            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10698        });
10699        let task = workspace.update_in(cx, |w, window, cx| {
10700            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10701        });
10702        cx.executor().run_until_parked();
10703        cx.simulate_prompt_answer("Cancel"); // cancel save all
10704        cx.executor().run_until_parked();
10705        assert!(!cx.has_pending_prompt());
10706        assert!(!task.await.unwrap());
10707    }
10708
10709    #[gpui::test]
10710    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10711        init_test(cx);
10712
10713        let fs = FakeFs::new(cx.executor());
10714        fs.insert_tree("/root", json!({ "one": "" })).await;
10715
10716        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10717        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10718        let multi_workspace_handle =
10719            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10720        cx.run_until_parked();
10721
10722        let workspace_a = multi_workspace_handle
10723            .read_with(cx, |mw, _| mw.workspace().clone())
10724            .unwrap();
10725
10726        let workspace_b = multi_workspace_handle
10727            .update(cx, |mw, window, cx| {
10728                mw.test_add_workspace(project_b, window, cx)
10729            })
10730            .unwrap();
10731
10732        // Activate workspace A
10733        multi_workspace_handle
10734            .update(cx, |mw, window, cx| {
10735                let workspace = mw.workspaces()[0].clone();
10736                mw.activate(workspace, window, cx);
10737            })
10738            .unwrap();
10739
10740        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10741
10742        // Workspace A has a clean item
10743        let item_a = cx.new(TestItem::new);
10744        workspace_a.update_in(cx, |w, window, cx| {
10745            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10746        });
10747
10748        // Workspace B has a dirty item
10749        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10750        workspace_b.update_in(cx, |w, window, cx| {
10751            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10752        });
10753
10754        // Verify workspace A is active
10755        multi_workspace_handle
10756            .read_with(cx, |mw, _| {
10757                assert_eq!(mw.active_workspace_index(), 0);
10758            })
10759            .unwrap();
10760
10761        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10762        multi_workspace_handle
10763            .update(cx, |mw, window, cx| {
10764                mw.close_window(&CloseWindow, window, cx);
10765            })
10766            .unwrap();
10767        cx.run_until_parked();
10768
10769        // Workspace B should now be active since it has dirty items that need attention
10770        multi_workspace_handle
10771            .read_with(cx, |mw, _| {
10772                assert_eq!(
10773                    mw.active_workspace_index(),
10774                    1,
10775                    "workspace B should be activated when it prompts"
10776                );
10777            })
10778            .unwrap();
10779
10780        // User cancels the save prompt from workspace B
10781        cx.simulate_prompt_answer("Cancel");
10782        cx.run_until_parked();
10783
10784        // Window should still exist because workspace B's close was cancelled
10785        assert!(
10786            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10787            "window should still exist after cancelling one workspace's close"
10788        );
10789    }
10790
10791    #[gpui::test]
10792    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10793        init_test(cx);
10794
10795        // Register TestItem as a serializable item
10796        cx.update(|cx| {
10797            register_serializable_item::<TestItem>(cx);
10798        });
10799
10800        let fs = FakeFs::new(cx.executor());
10801        fs.insert_tree("/root", json!({ "one": "" })).await;
10802
10803        let project = Project::test(fs, ["root".as_ref()], cx).await;
10804        let (workspace, cx) =
10805            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10806
10807        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10808        let item1 = cx.new(|cx| {
10809            TestItem::new(cx)
10810                .with_dirty(true)
10811                .with_serialize(|| Some(Task::ready(Ok(()))))
10812        });
10813        let item2 = cx.new(|cx| {
10814            TestItem::new(cx)
10815                .with_dirty(true)
10816                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10817                .with_serialize(|| Some(Task::ready(Ok(()))))
10818        });
10819        workspace.update_in(cx, |w, window, cx| {
10820            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10821            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10822        });
10823        let task = workspace.update_in(cx, |w, window, cx| {
10824            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10825        });
10826        assert!(task.await.unwrap());
10827    }
10828
10829    #[gpui::test]
10830    async fn test_close_pane_items(cx: &mut TestAppContext) {
10831        init_test(cx);
10832
10833        let fs = FakeFs::new(cx.executor());
10834
10835        let project = Project::test(fs, None, cx).await;
10836        let (workspace, cx) =
10837            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10838
10839        let item1 = cx.new(|cx| {
10840            TestItem::new(cx)
10841                .with_dirty(true)
10842                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10843        });
10844        let item2 = cx.new(|cx| {
10845            TestItem::new(cx)
10846                .with_dirty(true)
10847                .with_conflict(true)
10848                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10849        });
10850        let item3 = cx.new(|cx| {
10851            TestItem::new(cx)
10852                .with_dirty(true)
10853                .with_conflict(true)
10854                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10855        });
10856        let item4 = cx.new(|cx| {
10857            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10858                let project_item = TestProjectItem::new_untitled(cx);
10859                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10860                project_item
10861            }])
10862        });
10863        let pane = workspace.update_in(cx, |workspace, window, cx| {
10864            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10865            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10866            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10867            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10868            workspace.active_pane().clone()
10869        });
10870
10871        let close_items = pane.update_in(cx, |pane, window, cx| {
10872            pane.activate_item(1, true, true, window, cx);
10873            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10874            let item1_id = item1.item_id();
10875            let item3_id = item3.item_id();
10876            let item4_id = item4.item_id();
10877            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10878                [item1_id, item3_id, item4_id].contains(&id)
10879            })
10880        });
10881        cx.executor().run_until_parked();
10882
10883        assert!(cx.has_pending_prompt());
10884        cx.simulate_prompt_answer("Save all");
10885
10886        cx.executor().run_until_parked();
10887
10888        // Item 1 is saved. There's a prompt to save item 3.
10889        pane.update(cx, |pane, cx| {
10890            assert_eq!(item1.read(cx).save_count, 1);
10891            assert_eq!(item1.read(cx).save_as_count, 0);
10892            assert_eq!(item1.read(cx).reload_count, 0);
10893            assert_eq!(pane.items_len(), 3);
10894            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10895        });
10896        assert!(cx.has_pending_prompt());
10897
10898        // Cancel saving item 3.
10899        cx.simulate_prompt_answer("Discard");
10900        cx.executor().run_until_parked();
10901
10902        // Item 3 is reloaded. There's a prompt to save item 4.
10903        pane.update(cx, |pane, cx| {
10904            assert_eq!(item3.read(cx).save_count, 0);
10905            assert_eq!(item3.read(cx).save_as_count, 0);
10906            assert_eq!(item3.read(cx).reload_count, 1);
10907            assert_eq!(pane.items_len(), 2);
10908            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10909        });
10910
10911        // There's a prompt for a path for item 4.
10912        cx.simulate_new_path_selection(|_| Some(Default::default()));
10913        close_items.await.unwrap();
10914
10915        // The requested items are closed.
10916        pane.update(cx, |pane, cx| {
10917            assert_eq!(item4.read(cx).save_count, 0);
10918            assert_eq!(item4.read(cx).save_as_count, 1);
10919            assert_eq!(item4.read(cx).reload_count, 0);
10920            assert_eq!(pane.items_len(), 1);
10921            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10922        });
10923    }
10924
10925    #[gpui::test]
10926    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10927        init_test(cx);
10928
10929        let fs = FakeFs::new(cx.executor());
10930        let project = Project::test(fs, [], cx).await;
10931        let (workspace, cx) =
10932            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10933
10934        // Create several workspace items with single project entries, and two
10935        // workspace items with multiple project entries.
10936        let single_entry_items = (0..=4)
10937            .map(|project_entry_id| {
10938                cx.new(|cx| {
10939                    TestItem::new(cx)
10940                        .with_dirty(true)
10941                        .with_project_items(&[dirty_project_item(
10942                            project_entry_id,
10943                            &format!("{project_entry_id}.txt"),
10944                            cx,
10945                        )])
10946                })
10947            })
10948            .collect::<Vec<_>>();
10949        let item_2_3 = cx.new(|cx| {
10950            TestItem::new(cx)
10951                .with_dirty(true)
10952                .with_buffer_kind(ItemBufferKind::Multibuffer)
10953                .with_project_items(&[
10954                    single_entry_items[2].read(cx).project_items[0].clone(),
10955                    single_entry_items[3].read(cx).project_items[0].clone(),
10956                ])
10957        });
10958        let item_3_4 = cx.new(|cx| {
10959            TestItem::new(cx)
10960                .with_dirty(true)
10961                .with_buffer_kind(ItemBufferKind::Multibuffer)
10962                .with_project_items(&[
10963                    single_entry_items[3].read(cx).project_items[0].clone(),
10964                    single_entry_items[4].read(cx).project_items[0].clone(),
10965                ])
10966        });
10967
10968        // Create two panes that contain the following project entries:
10969        //   left pane:
10970        //     multi-entry items:   (2, 3)
10971        //     single-entry items:  0, 2, 3, 4
10972        //   right pane:
10973        //     single-entry items:  4, 1
10974        //     multi-entry items:   (3, 4)
10975        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10976            let left_pane = workspace.active_pane().clone();
10977            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10978            workspace.add_item_to_active_pane(
10979                single_entry_items[0].boxed_clone(),
10980                None,
10981                true,
10982                window,
10983                cx,
10984            );
10985            workspace.add_item_to_active_pane(
10986                single_entry_items[2].boxed_clone(),
10987                None,
10988                true,
10989                window,
10990                cx,
10991            );
10992            workspace.add_item_to_active_pane(
10993                single_entry_items[3].boxed_clone(),
10994                None,
10995                true,
10996                window,
10997                cx,
10998            );
10999            workspace.add_item_to_active_pane(
11000                single_entry_items[4].boxed_clone(),
11001                None,
11002                true,
11003                window,
11004                cx,
11005            );
11006
11007            let right_pane =
11008                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11009
11010            let boxed_clone = single_entry_items[1].boxed_clone();
11011            let right_pane = window.spawn(cx, async move |cx| {
11012                right_pane.await.inspect(|right_pane| {
11013                    right_pane
11014                        .update_in(cx, |pane, window, cx| {
11015                            pane.add_item(boxed_clone, true, true, None, window, cx);
11016                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11017                        })
11018                        .unwrap();
11019                })
11020            });
11021
11022            (left_pane, right_pane)
11023        });
11024        let right_pane = right_pane.await.unwrap();
11025        cx.focus(&right_pane);
11026
11027        let close = right_pane.update_in(cx, |pane, window, cx| {
11028            pane.close_all_items(&CloseAllItems::default(), window, cx)
11029                .unwrap()
11030        });
11031        cx.executor().run_until_parked();
11032
11033        let msg = cx.pending_prompt().unwrap().0;
11034        assert!(msg.contains("1.txt"));
11035        assert!(!msg.contains("2.txt"));
11036        assert!(!msg.contains("3.txt"));
11037        assert!(!msg.contains("4.txt"));
11038
11039        // With best-effort close, cancelling item 1 keeps it open but items 4
11040        // and (3,4) still close since their entries exist in left pane.
11041        cx.simulate_prompt_answer("Cancel");
11042        close.await;
11043
11044        right_pane.read_with(cx, |pane, _| {
11045            assert_eq!(pane.items_len(), 1);
11046        });
11047
11048        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11049        left_pane
11050            .update_in(cx, |left_pane, window, cx| {
11051                left_pane.close_item_by_id(
11052                    single_entry_items[3].entity_id(),
11053                    SaveIntent::Skip,
11054                    window,
11055                    cx,
11056                )
11057            })
11058            .await
11059            .unwrap();
11060
11061        let close = left_pane.update_in(cx, |pane, window, cx| {
11062            pane.close_all_items(&CloseAllItems::default(), window, cx)
11063                .unwrap()
11064        });
11065        cx.executor().run_until_parked();
11066
11067        let details = cx.pending_prompt().unwrap().1;
11068        assert!(details.contains("0.txt"));
11069        assert!(details.contains("3.txt"));
11070        assert!(details.contains("4.txt"));
11071        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11072        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11073        // assert!(!details.contains("2.txt"));
11074
11075        cx.simulate_prompt_answer("Save all");
11076        cx.executor().run_until_parked();
11077        close.await;
11078
11079        left_pane.read_with(cx, |pane, _| {
11080            assert_eq!(pane.items_len(), 0);
11081        });
11082    }
11083
11084    #[gpui::test]
11085    async fn test_autosave(cx: &mut gpui::TestAppContext) {
11086        init_test(cx);
11087
11088        let fs = FakeFs::new(cx.executor());
11089        let project = Project::test(fs, [], cx).await;
11090        let (workspace, cx) =
11091            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11092        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11093
11094        let item = cx.new(|cx| {
11095            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11096        });
11097        let item_id = item.entity_id();
11098        workspace.update_in(cx, |workspace, window, cx| {
11099            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11100        });
11101
11102        // Autosave on window change.
11103        item.update(cx, |item, cx| {
11104            SettingsStore::update_global(cx, |settings, cx| {
11105                settings.update_user_settings(cx, |settings| {
11106                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11107                })
11108            });
11109            item.is_dirty = true;
11110        });
11111
11112        // Deactivating the window saves the file.
11113        cx.deactivate_window();
11114        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11115
11116        // Re-activating the window doesn't save the file.
11117        cx.update(|window, _| window.activate_window());
11118        cx.executor().run_until_parked();
11119        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11120
11121        // Autosave on focus change.
11122        item.update_in(cx, |item, window, cx| {
11123            cx.focus_self(window);
11124            SettingsStore::update_global(cx, |settings, cx| {
11125                settings.update_user_settings(cx, |settings| {
11126                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11127                })
11128            });
11129            item.is_dirty = true;
11130        });
11131        // Blurring the item saves the file.
11132        item.update_in(cx, |_, window, _| window.blur());
11133        cx.executor().run_until_parked();
11134        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11135
11136        // Deactivating the window still saves the file.
11137        item.update_in(cx, |item, window, cx| {
11138            cx.focus_self(window);
11139            item.is_dirty = true;
11140        });
11141        cx.deactivate_window();
11142        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11143
11144        // Autosave after delay.
11145        item.update(cx, |item, cx| {
11146            SettingsStore::update_global(cx, |settings, cx| {
11147                settings.update_user_settings(cx, |settings| {
11148                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11149                        milliseconds: 500.into(),
11150                    });
11151                })
11152            });
11153            item.is_dirty = true;
11154            cx.emit(ItemEvent::Edit);
11155        });
11156
11157        // Delay hasn't fully expired, so the file is still dirty and unsaved.
11158        cx.executor().advance_clock(Duration::from_millis(250));
11159        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11160
11161        // After delay expires, the file is saved.
11162        cx.executor().advance_clock(Duration::from_millis(250));
11163        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11164
11165        // Autosave after delay, should save earlier than delay if tab is closed
11166        item.update(cx, |item, cx| {
11167            item.is_dirty = true;
11168            cx.emit(ItemEvent::Edit);
11169        });
11170        cx.executor().advance_clock(Duration::from_millis(250));
11171        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11172
11173        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11174        pane.update_in(cx, |pane, window, cx| {
11175            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11176        })
11177        .await
11178        .unwrap();
11179        assert!(!cx.has_pending_prompt());
11180        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11181
11182        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11183        workspace.update_in(cx, |workspace, window, cx| {
11184            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11185        });
11186        item.update_in(cx, |item, _window, cx| {
11187            item.is_dirty = true;
11188            for project_item in &mut item.project_items {
11189                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11190            }
11191        });
11192        cx.run_until_parked();
11193        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11194
11195        // Autosave on focus change, ensuring closing the tab counts as such.
11196        item.update(cx, |item, cx| {
11197            SettingsStore::update_global(cx, |settings, cx| {
11198                settings.update_user_settings(cx, |settings| {
11199                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11200                })
11201            });
11202            item.is_dirty = true;
11203            for project_item in &mut item.project_items {
11204                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11205            }
11206        });
11207
11208        pane.update_in(cx, |pane, window, cx| {
11209            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11210        })
11211        .await
11212        .unwrap();
11213        assert!(!cx.has_pending_prompt());
11214        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11215
11216        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11217        workspace.update_in(cx, |workspace, window, cx| {
11218            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11219        });
11220        item.update_in(cx, |item, window, cx| {
11221            item.project_items[0].update(cx, |item, _| {
11222                item.entry_id = None;
11223            });
11224            item.is_dirty = true;
11225            window.blur();
11226        });
11227        cx.run_until_parked();
11228        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11229
11230        // Ensure autosave is prevented for deleted files also when closing the buffer.
11231        let _close_items = pane.update_in(cx, |pane, window, cx| {
11232            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11233        });
11234        cx.run_until_parked();
11235        assert!(cx.has_pending_prompt());
11236        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11237    }
11238
11239    #[gpui::test]
11240    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11241        init_test(cx);
11242
11243        let fs = FakeFs::new(cx.executor());
11244        let project = Project::test(fs, [], cx).await;
11245        let (workspace, cx) =
11246            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11247
11248        // Create a multibuffer-like item with two child focus handles,
11249        // simulating individual buffer editors within a multibuffer.
11250        let item = cx.new(|cx| {
11251            TestItem::new(cx)
11252                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11253                .with_child_focus_handles(2, cx)
11254        });
11255        workspace.update_in(cx, |workspace, window, cx| {
11256            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11257        });
11258
11259        // Set autosave to OnFocusChange and focus the first child handle,
11260        // simulating the user's cursor being inside one of the multibuffer's excerpts.
11261        item.update_in(cx, |item, window, cx| {
11262            SettingsStore::update_global(cx, |settings, cx| {
11263                settings.update_user_settings(cx, |settings| {
11264                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11265                })
11266            });
11267            item.is_dirty = true;
11268            window.focus(&item.child_focus_handles[0], cx);
11269        });
11270        cx.executor().run_until_parked();
11271        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11272
11273        // Moving focus from one child to another within the same item should
11274        // NOT trigger autosave — focus is still within the item's focus hierarchy.
11275        item.update_in(cx, |item, window, cx| {
11276            window.focus(&item.child_focus_handles[1], cx);
11277        });
11278        cx.executor().run_until_parked();
11279        item.read_with(cx, |item, _| {
11280            assert_eq!(
11281                item.save_count, 0,
11282                "Switching focus between children within the same item should not autosave"
11283            );
11284        });
11285
11286        // Blurring the item saves the file. This is the core regression scenario:
11287        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11288        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11289        // the leaf is always a child focus handle, so `on_blur` never detected
11290        // focus leaving the item.
11291        item.update_in(cx, |_, window, _| window.blur());
11292        cx.executor().run_until_parked();
11293        item.read_with(cx, |item, _| {
11294            assert_eq!(
11295                item.save_count, 1,
11296                "Blurring should trigger autosave when focus was on a child of the item"
11297            );
11298        });
11299
11300        // Deactivating the window should also trigger autosave when a child of
11301        // the multibuffer item currently owns focus.
11302        item.update_in(cx, |item, window, cx| {
11303            item.is_dirty = true;
11304            window.focus(&item.child_focus_handles[0], cx);
11305        });
11306        cx.executor().run_until_parked();
11307        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11308
11309        cx.deactivate_window();
11310        item.read_with(cx, |item, _| {
11311            assert_eq!(
11312                item.save_count, 2,
11313                "Deactivating window should trigger autosave when focus was on a child"
11314            );
11315        });
11316    }
11317
11318    #[gpui::test]
11319    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11320        init_test(cx);
11321
11322        let fs = FakeFs::new(cx.executor());
11323
11324        let project = Project::test(fs, [], cx).await;
11325        let (workspace, cx) =
11326            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11327
11328        let item = cx.new(|cx| {
11329            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11330        });
11331        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11332        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11333        let toolbar_notify_count = Rc::new(RefCell::new(0));
11334
11335        workspace.update_in(cx, |workspace, window, cx| {
11336            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11337            let toolbar_notification_count = toolbar_notify_count.clone();
11338            cx.observe_in(&toolbar, window, move |_, _, _, _| {
11339                *toolbar_notification_count.borrow_mut() += 1
11340            })
11341            .detach();
11342        });
11343
11344        pane.read_with(cx, |pane, _| {
11345            assert!(!pane.can_navigate_backward());
11346            assert!(!pane.can_navigate_forward());
11347        });
11348
11349        item.update_in(cx, |item, _, cx| {
11350            item.set_state("one".to_string(), cx);
11351        });
11352
11353        // Toolbar must be notified to re-render the navigation buttons
11354        assert_eq!(*toolbar_notify_count.borrow(), 1);
11355
11356        pane.read_with(cx, |pane, _| {
11357            assert!(pane.can_navigate_backward());
11358            assert!(!pane.can_navigate_forward());
11359        });
11360
11361        workspace
11362            .update_in(cx, |workspace, window, cx| {
11363                workspace.go_back(pane.downgrade(), window, cx)
11364            })
11365            .await
11366            .unwrap();
11367
11368        assert_eq!(*toolbar_notify_count.borrow(), 2);
11369        pane.read_with(cx, |pane, _| {
11370            assert!(!pane.can_navigate_backward());
11371            assert!(pane.can_navigate_forward());
11372        });
11373    }
11374
11375    /// Tests that the navigation history deduplicates entries for the same item.
11376    ///
11377    /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11378    /// the navigation history deduplicates by keeping only the most recent visit to each item,
11379    /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11380    /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11381    /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11382    ///
11383    /// This behavior prevents the navigation history from growing unnecessarily large and provides
11384    /// a better user experience by eliminating redundant navigation steps when jumping between files.
11385    #[gpui::test]
11386    async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11387        init_test(cx);
11388
11389        let fs = FakeFs::new(cx.executor());
11390        let project = Project::test(fs, [], cx).await;
11391        let (workspace, cx) =
11392            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11393
11394        let item_a = cx.new(|cx| {
11395            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11396        });
11397        let item_b = cx.new(|cx| {
11398            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11399        });
11400        let item_c = cx.new(|cx| {
11401            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11402        });
11403
11404        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11405
11406        workspace.update_in(cx, |workspace, window, cx| {
11407            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11408            workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11409            workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11410        });
11411
11412        workspace.update_in(cx, |workspace, window, cx| {
11413            workspace.activate_item(&item_a, false, false, window, cx);
11414        });
11415        cx.run_until_parked();
11416
11417        workspace.update_in(cx, |workspace, window, cx| {
11418            workspace.activate_item(&item_b, false, false, window, cx);
11419        });
11420        cx.run_until_parked();
11421
11422        workspace.update_in(cx, |workspace, window, cx| {
11423            workspace.activate_item(&item_a, false, false, window, cx);
11424        });
11425        cx.run_until_parked();
11426
11427        workspace.update_in(cx, |workspace, window, cx| {
11428            workspace.activate_item(&item_b, false, false, window, cx);
11429        });
11430        cx.run_until_parked();
11431
11432        workspace.update_in(cx, |workspace, window, cx| {
11433            workspace.activate_item(&item_a, false, false, window, cx);
11434        });
11435        cx.run_until_parked();
11436
11437        workspace.update_in(cx, |workspace, window, cx| {
11438            workspace.activate_item(&item_b, false, false, window, cx);
11439        });
11440        cx.run_until_parked();
11441
11442        workspace.update_in(cx, |workspace, window, cx| {
11443            workspace.activate_item(&item_c, false, false, window, cx);
11444        });
11445        cx.run_until_parked();
11446
11447        let backward_count = pane.read_with(cx, |pane, cx| {
11448            let mut count = 0;
11449            pane.nav_history().for_each_entry(cx, &mut |_, _| {
11450                count += 1;
11451            });
11452            count
11453        });
11454        assert!(
11455            backward_count <= 4,
11456            "Should have at most 4 entries, got {}",
11457            backward_count
11458        );
11459
11460        workspace
11461            .update_in(cx, |workspace, window, cx| {
11462                workspace.go_back(pane.downgrade(), window, cx)
11463            })
11464            .await
11465            .unwrap();
11466
11467        let active_item = workspace.read_with(cx, |workspace, cx| {
11468            workspace.active_item(cx).unwrap().item_id()
11469        });
11470        assert_eq!(
11471            active_item,
11472            item_b.entity_id(),
11473            "After first go_back, should be at item B"
11474        );
11475
11476        workspace
11477            .update_in(cx, |workspace, window, cx| {
11478                workspace.go_back(pane.downgrade(), window, cx)
11479            })
11480            .await
11481            .unwrap();
11482
11483        let active_item = workspace.read_with(cx, |workspace, cx| {
11484            workspace.active_item(cx).unwrap().item_id()
11485        });
11486        assert_eq!(
11487            active_item,
11488            item_a.entity_id(),
11489            "After second go_back, should be at item A"
11490        );
11491
11492        pane.read_with(cx, |pane, _| {
11493            assert!(pane.can_navigate_forward(), "Should be able to go forward");
11494        });
11495    }
11496
11497    #[gpui::test]
11498    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11499        init_test(cx);
11500        let fs = FakeFs::new(cx.executor());
11501        let project = Project::test(fs, [], cx).await;
11502        let (multi_workspace, cx) =
11503            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11504        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11505
11506        workspace.update_in(cx, |workspace, window, cx| {
11507            let first_item = cx.new(|cx| {
11508                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11509            });
11510            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11511            workspace.split_pane(
11512                workspace.active_pane().clone(),
11513                SplitDirection::Right,
11514                window,
11515                cx,
11516            );
11517            workspace.split_pane(
11518                workspace.active_pane().clone(),
11519                SplitDirection::Right,
11520                window,
11521                cx,
11522            );
11523        });
11524
11525        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11526            let panes = workspace.center.panes();
11527            assert!(panes.len() >= 2);
11528            (
11529                panes.first().expect("at least one pane").entity_id(),
11530                panes.last().expect("at least one pane").entity_id(),
11531            )
11532        });
11533
11534        workspace.update_in(cx, |workspace, window, cx| {
11535            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11536        });
11537        workspace.update(cx, |workspace, _| {
11538            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11539            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11540        });
11541
11542        cx.dispatch_action(ActivateLastPane);
11543
11544        workspace.update(cx, |workspace, _| {
11545            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11546        });
11547    }
11548
11549    #[gpui::test]
11550    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11551        init_test(cx);
11552        let fs = FakeFs::new(cx.executor());
11553
11554        let project = Project::test(fs, [], cx).await;
11555        let (workspace, cx) =
11556            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11557
11558        let panel = workspace.update_in(cx, |workspace, window, cx| {
11559            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11560            workspace.add_panel(panel.clone(), window, cx);
11561
11562            workspace
11563                .right_dock()
11564                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11565
11566            panel
11567        });
11568
11569        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11570        pane.update_in(cx, |pane, window, cx| {
11571            let item = cx.new(TestItem::new);
11572            pane.add_item(Box::new(item), true, true, None, window, cx);
11573        });
11574
11575        // Transfer focus from center to panel
11576        workspace.update_in(cx, |workspace, window, cx| {
11577            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11578        });
11579
11580        workspace.update_in(cx, |workspace, window, cx| {
11581            assert!(workspace.right_dock().read(cx).is_open());
11582            assert!(!panel.is_zoomed(window, cx));
11583            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11584        });
11585
11586        // Transfer focus from panel to center
11587        workspace.update_in(cx, |workspace, window, cx| {
11588            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11589        });
11590
11591        workspace.update_in(cx, |workspace, window, cx| {
11592            assert!(workspace.right_dock().read(cx).is_open());
11593            assert!(!panel.is_zoomed(window, cx));
11594            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11595            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11596        });
11597
11598        // Close the dock
11599        workspace.update_in(cx, |workspace, window, cx| {
11600            workspace.toggle_dock(DockPosition::Right, window, cx);
11601        });
11602
11603        workspace.update_in(cx, |workspace, window, cx| {
11604            assert!(!workspace.right_dock().read(cx).is_open());
11605            assert!(!panel.is_zoomed(window, cx));
11606            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11607            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11608        });
11609
11610        // Open the dock
11611        workspace.update_in(cx, |workspace, window, cx| {
11612            workspace.toggle_dock(DockPosition::Right, window, cx);
11613        });
11614
11615        workspace.update_in(cx, |workspace, window, cx| {
11616            assert!(workspace.right_dock().read(cx).is_open());
11617            assert!(!panel.is_zoomed(window, cx));
11618            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11619        });
11620
11621        // Focus and zoom panel
11622        panel.update_in(cx, |panel, window, cx| {
11623            cx.focus_self(window);
11624            panel.set_zoomed(true, window, cx)
11625        });
11626
11627        workspace.update_in(cx, |workspace, window, cx| {
11628            assert!(workspace.right_dock().read(cx).is_open());
11629            assert!(panel.is_zoomed(window, cx));
11630            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11631        });
11632
11633        // Transfer focus to the center closes the dock
11634        workspace.update_in(cx, |workspace, window, cx| {
11635            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11636        });
11637
11638        workspace.update_in(cx, |workspace, window, cx| {
11639            assert!(!workspace.right_dock().read(cx).is_open());
11640            assert!(panel.is_zoomed(window, cx));
11641            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11642        });
11643
11644        // Transferring focus back to the panel keeps it zoomed
11645        workspace.update_in(cx, |workspace, window, cx| {
11646            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11647        });
11648
11649        workspace.update_in(cx, |workspace, window, cx| {
11650            assert!(workspace.right_dock().read(cx).is_open());
11651            assert!(panel.is_zoomed(window, cx));
11652            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11653        });
11654
11655        // Close the dock while it is zoomed
11656        workspace.update_in(cx, |workspace, window, cx| {
11657            workspace.toggle_dock(DockPosition::Right, window, cx)
11658        });
11659
11660        workspace.update_in(cx, |workspace, window, cx| {
11661            assert!(!workspace.right_dock().read(cx).is_open());
11662            assert!(panel.is_zoomed(window, cx));
11663            assert!(workspace.zoomed.is_none());
11664            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11665        });
11666
11667        // Opening the dock, when it's zoomed, retains focus
11668        workspace.update_in(cx, |workspace, window, cx| {
11669            workspace.toggle_dock(DockPosition::Right, window, cx)
11670        });
11671
11672        workspace.update_in(cx, |workspace, window, cx| {
11673            assert!(workspace.right_dock().read(cx).is_open());
11674            assert!(panel.is_zoomed(window, cx));
11675            assert!(workspace.zoomed.is_some());
11676            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11677        });
11678
11679        // Unzoom and close the panel, zoom the active pane.
11680        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11681        workspace.update_in(cx, |workspace, window, cx| {
11682            workspace.toggle_dock(DockPosition::Right, window, cx)
11683        });
11684        pane.update_in(cx, |pane, window, cx| {
11685            pane.toggle_zoom(&Default::default(), window, cx)
11686        });
11687
11688        // Opening a dock unzooms the pane.
11689        workspace.update_in(cx, |workspace, window, cx| {
11690            workspace.toggle_dock(DockPosition::Right, window, cx)
11691        });
11692        workspace.update_in(cx, |workspace, window, cx| {
11693            let pane = pane.read(cx);
11694            assert!(!pane.is_zoomed());
11695            assert!(!pane.focus_handle(cx).is_focused(window));
11696            assert!(workspace.right_dock().read(cx).is_open());
11697            assert!(workspace.zoomed.is_none());
11698        });
11699    }
11700
11701    #[gpui::test]
11702    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11703        init_test(cx);
11704        let fs = FakeFs::new(cx.executor());
11705
11706        let project = Project::test(fs, [], cx).await;
11707        let (workspace, cx) =
11708            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11709
11710        let panel = workspace.update_in(cx, |workspace, window, cx| {
11711            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11712            workspace.add_panel(panel.clone(), window, cx);
11713            panel
11714        });
11715
11716        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11717        pane.update_in(cx, |pane, window, cx| {
11718            let item = cx.new(TestItem::new);
11719            pane.add_item(Box::new(item), true, true, None, window, cx);
11720        });
11721
11722        // Enable close_panel_on_toggle
11723        cx.update_global(|store: &mut SettingsStore, cx| {
11724            store.update_user_settings(cx, |settings| {
11725                settings.workspace.close_panel_on_toggle = Some(true);
11726            });
11727        });
11728
11729        // Panel starts closed. Toggling should open and focus it.
11730        workspace.update_in(cx, |workspace, window, cx| {
11731            assert!(!workspace.right_dock().read(cx).is_open());
11732            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11733        });
11734
11735        workspace.update_in(cx, |workspace, window, cx| {
11736            assert!(
11737                workspace.right_dock().read(cx).is_open(),
11738                "Dock should be open after toggling from center"
11739            );
11740            assert!(
11741                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11742                "Panel should be focused after toggling from center"
11743            );
11744        });
11745
11746        // Panel is open and focused. Toggling should close the panel and
11747        // return focus to the center.
11748        workspace.update_in(cx, |workspace, window, cx| {
11749            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11750        });
11751
11752        workspace.update_in(cx, |workspace, window, cx| {
11753            assert!(
11754                !workspace.right_dock().read(cx).is_open(),
11755                "Dock should be closed after toggling from focused panel"
11756            );
11757            assert!(
11758                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11759                "Panel should not be focused after toggling from focused panel"
11760            );
11761        });
11762
11763        // Open the dock and focus something else so the panel is open but not
11764        // focused. Toggling should focus the panel (not close it).
11765        workspace.update_in(cx, |workspace, window, cx| {
11766            workspace
11767                .right_dock()
11768                .update(cx, |dock, cx| dock.set_open(true, window, cx));
11769            window.focus(&pane.read(cx).focus_handle(cx), cx);
11770        });
11771
11772        workspace.update_in(cx, |workspace, window, cx| {
11773            assert!(workspace.right_dock().read(cx).is_open());
11774            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11775            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11776        });
11777
11778        workspace.update_in(cx, |workspace, window, cx| {
11779            assert!(
11780                workspace.right_dock().read(cx).is_open(),
11781                "Dock should remain open when toggling focuses an open-but-unfocused panel"
11782            );
11783            assert!(
11784                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11785                "Panel should be focused after toggling an open-but-unfocused panel"
11786            );
11787        });
11788
11789        // Now disable the setting and verify the original behavior: toggling
11790        // from a focused panel moves focus to center but leaves the dock open.
11791        cx.update_global(|store: &mut SettingsStore, cx| {
11792            store.update_user_settings(cx, |settings| {
11793                settings.workspace.close_panel_on_toggle = Some(false);
11794            });
11795        });
11796
11797        workspace.update_in(cx, |workspace, window, cx| {
11798            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11799        });
11800
11801        workspace.update_in(cx, |workspace, window, cx| {
11802            assert!(
11803                workspace.right_dock().read(cx).is_open(),
11804                "Dock should remain open when setting is disabled"
11805            );
11806            assert!(
11807                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11808                "Panel should not be focused after toggling with setting disabled"
11809            );
11810        });
11811    }
11812
11813    #[gpui::test]
11814    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11815        init_test(cx);
11816        let fs = FakeFs::new(cx.executor());
11817
11818        let project = Project::test(fs, [], cx).await;
11819        let (workspace, cx) =
11820            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11821
11822        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11823            workspace.active_pane().clone()
11824        });
11825
11826        // Add an item to the pane so it can be zoomed
11827        workspace.update_in(cx, |workspace, window, cx| {
11828            let item = cx.new(TestItem::new);
11829            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11830        });
11831
11832        // Initially not zoomed
11833        workspace.update_in(cx, |workspace, _window, cx| {
11834            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11835            assert!(
11836                workspace.zoomed.is_none(),
11837                "Workspace should track no zoomed pane"
11838            );
11839            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11840        });
11841
11842        // Zoom In
11843        pane.update_in(cx, |pane, window, cx| {
11844            pane.zoom_in(&crate::ZoomIn, window, cx);
11845        });
11846
11847        workspace.update_in(cx, |workspace, window, cx| {
11848            assert!(
11849                pane.read(cx).is_zoomed(),
11850                "Pane should be zoomed after ZoomIn"
11851            );
11852            assert!(
11853                workspace.zoomed.is_some(),
11854                "Workspace should track the zoomed pane"
11855            );
11856            assert!(
11857                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11858                "ZoomIn should focus the pane"
11859            );
11860        });
11861
11862        // Zoom In again is a no-op
11863        pane.update_in(cx, |pane, window, cx| {
11864            pane.zoom_in(&crate::ZoomIn, window, cx);
11865        });
11866
11867        workspace.update_in(cx, |workspace, window, cx| {
11868            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11869            assert!(
11870                workspace.zoomed.is_some(),
11871                "Workspace still tracks zoomed pane"
11872            );
11873            assert!(
11874                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11875                "Pane remains focused after repeated ZoomIn"
11876            );
11877        });
11878
11879        // Zoom Out
11880        pane.update_in(cx, |pane, window, cx| {
11881            pane.zoom_out(&crate::ZoomOut, window, cx);
11882        });
11883
11884        workspace.update_in(cx, |workspace, _window, cx| {
11885            assert!(
11886                !pane.read(cx).is_zoomed(),
11887                "Pane should unzoom after ZoomOut"
11888            );
11889            assert!(
11890                workspace.zoomed.is_none(),
11891                "Workspace clears zoom tracking after ZoomOut"
11892            );
11893        });
11894
11895        // Zoom Out again is a no-op
11896        pane.update_in(cx, |pane, window, cx| {
11897            pane.zoom_out(&crate::ZoomOut, window, cx);
11898        });
11899
11900        workspace.update_in(cx, |workspace, _window, cx| {
11901            assert!(
11902                !pane.read(cx).is_zoomed(),
11903                "Second ZoomOut keeps pane unzoomed"
11904            );
11905            assert!(
11906                workspace.zoomed.is_none(),
11907                "Workspace remains without zoomed pane"
11908            );
11909        });
11910    }
11911
11912    #[gpui::test]
11913    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11914        init_test(cx);
11915        let fs = FakeFs::new(cx.executor());
11916
11917        let project = Project::test(fs, [], cx).await;
11918        let (workspace, cx) =
11919            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11920        workspace.update_in(cx, |workspace, window, cx| {
11921            // Open two docks
11922            let left_dock = workspace.dock_at_position(DockPosition::Left);
11923            let right_dock = workspace.dock_at_position(DockPosition::Right);
11924
11925            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11926            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11927
11928            assert!(left_dock.read(cx).is_open());
11929            assert!(right_dock.read(cx).is_open());
11930        });
11931
11932        workspace.update_in(cx, |workspace, window, cx| {
11933            // Toggle all docks - should close both
11934            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11935
11936            let left_dock = workspace.dock_at_position(DockPosition::Left);
11937            let right_dock = workspace.dock_at_position(DockPosition::Right);
11938            assert!(!left_dock.read(cx).is_open());
11939            assert!(!right_dock.read(cx).is_open());
11940        });
11941
11942        workspace.update_in(cx, |workspace, window, cx| {
11943            // Toggle again - should reopen both
11944            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11945
11946            let left_dock = workspace.dock_at_position(DockPosition::Left);
11947            let right_dock = workspace.dock_at_position(DockPosition::Right);
11948            assert!(left_dock.read(cx).is_open());
11949            assert!(right_dock.read(cx).is_open());
11950        });
11951    }
11952
11953    #[gpui::test]
11954    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11955        init_test(cx);
11956        let fs = FakeFs::new(cx.executor());
11957
11958        let project = Project::test(fs, [], cx).await;
11959        let (workspace, cx) =
11960            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11961        workspace.update_in(cx, |workspace, window, cx| {
11962            // Open two docks
11963            let left_dock = workspace.dock_at_position(DockPosition::Left);
11964            let right_dock = workspace.dock_at_position(DockPosition::Right);
11965
11966            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11967            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11968
11969            assert!(left_dock.read(cx).is_open());
11970            assert!(right_dock.read(cx).is_open());
11971        });
11972
11973        workspace.update_in(cx, |workspace, window, cx| {
11974            // Close them manually
11975            workspace.toggle_dock(DockPosition::Left, window, cx);
11976            workspace.toggle_dock(DockPosition::Right, window, cx);
11977
11978            let left_dock = workspace.dock_at_position(DockPosition::Left);
11979            let right_dock = workspace.dock_at_position(DockPosition::Right);
11980            assert!(!left_dock.read(cx).is_open());
11981            assert!(!right_dock.read(cx).is_open());
11982        });
11983
11984        workspace.update_in(cx, |workspace, window, cx| {
11985            // Toggle all docks - only last closed (right dock) should reopen
11986            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11987
11988            let left_dock = workspace.dock_at_position(DockPosition::Left);
11989            let right_dock = workspace.dock_at_position(DockPosition::Right);
11990            assert!(!left_dock.read(cx).is_open());
11991            assert!(right_dock.read(cx).is_open());
11992        });
11993    }
11994
11995    #[gpui::test]
11996    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11997        init_test(cx);
11998        let fs = FakeFs::new(cx.executor());
11999        let project = Project::test(fs, [], cx).await;
12000        let (multi_workspace, cx) =
12001            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12002        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12003
12004        // Open two docks (left and right) with one panel each
12005        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12006            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12007            workspace.add_panel(left_panel.clone(), window, cx);
12008
12009            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12010            workspace.add_panel(right_panel.clone(), window, cx);
12011
12012            workspace.toggle_dock(DockPosition::Left, window, cx);
12013            workspace.toggle_dock(DockPosition::Right, window, cx);
12014
12015            // Verify initial state
12016            assert!(
12017                workspace.left_dock().read(cx).is_open(),
12018                "Left dock should be open"
12019            );
12020            assert_eq!(
12021                workspace
12022                    .left_dock()
12023                    .read(cx)
12024                    .visible_panel()
12025                    .unwrap()
12026                    .panel_id(),
12027                left_panel.panel_id(),
12028                "Left panel should be visible in left dock"
12029            );
12030            assert!(
12031                workspace.right_dock().read(cx).is_open(),
12032                "Right dock should be open"
12033            );
12034            assert_eq!(
12035                workspace
12036                    .right_dock()
12037                    .read(cx)
12038                    .visible_panel()
12039                    .unwrap()
12040                    .panel_id(),
12041                right_panel.panel_id(),
12042                "Right panel should be visible in right dock"
12043            );
12044            assert!(
12045                !workspace.bottom_dock().read(cx).is_open(),
12046                "Bottom dock should be closed"
12047            );
12048
12049            (left_panel, right_panel)
12050        });
12051
12052        // Focus the left panel and move it to the next position (bottom dock)
12053        workspace.update_in(cx, |workspace, window, cx| {
12054            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12055            assert!(
12056                left_panel.read(cx).focus_handle(cx).is_focused(window),
12057                "Left panel should be focused"
12058            );
12059        });
12060
12061        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12062
12063        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12064        workspace.update(cx, |workspace, cx| {
12065            assert!(
12066                !workspace.left_dock().read(cx).is_open(),
12067                "Left dock should be closed"
12068            );
12069            assert!(
12070                workspace.bottom_dock().read(cx).is_open(),
12071                "Bottom dock should now be open"
12072            );
12073            assert_eq!(
12074                left_panel.read(cx).position,
12075                DockPosition::Bottom,
12076                "Left panel should now be in the bottom dock"
12077            );
12078            assert_eq!(
12079                workspace
12080                    .bottom_dock()
12081                    .read(cx)
12082                    .visible_panel()
12083                    .unwrap()
12084                    .panel_id(),
12085                left_panel.panel_id(),
12086                "Left panel should be the visible panel in the bottom dock"
12087            );
12088        });
12089
12090        // Toggle all docks off
12091        workspace.update_in(cx, |workspace, window, cx| {
12092            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12093            assert!(
12094                !workspace.left_dock().read(cx).is_open(),
12095                "Left dock should be closed"
12096            );
12097            assert!(
12098                !workspace.right_dock().read(cx).is_open(),
12099                "Right dock should be closed"
12100            );
12101            assert!(
12102                !workspace.bottom_dock().read(cx).is_open(),
12103                "Bottom dock should be closed"
12104            );
12105        });
12106
12107        // Toggle all docks back on and verify positions are restored
12108        workspace.update_in(cx, |workspace, window, cx| {
12109            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12110            assert!(
12111                !workspace.left_dock().read(cx).is_open(),
12112                "Left dock should remain closed"
12113            );
12114            assert!(
12115                workspace.right_dock().read(cx).is_open(),
12116                "Right dock should remain open"
12117            );
12118            assert!(
12119                workspace.bottom_dock().read(cx).is_open(),
12120                "Bottom dock should remain open"
12121            );
12122            assert_eq!(
12123                left_panel.read(cx).position,
12124                DockPosition::Bottom,
12125                "Left panel should remain in the bottom dock"
12126            );
12127            assert_eq!(
12128                right_panel.read(cx).position,
12129                DockPosition::Right,
12130                "Right panel should remain in the right dock"
12131            );
12132            assert_eq!(
12133                workspace
12134                    .bottom_dock()
12135                    .read(cx)
12136                    .visible_panel()
12137                    .unwrap()
12138                    .panel_id(),
12139                left_panel.panel_id(),
12140                "Left panel should be the visible panel in the right dock"
12141            );
12142        });
12143    }
12144
12145    #[gpui::test]
12146    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12147        init_test(cx);
12148
12149        let fs = FakeFs::new(cx.executor());
12150
12151        let project = Project::test(fs, None, cx).await;
12152        let (workspace, cx) =
12153            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12154
12155        // Let's arrange the panes like this:
12156        //
12157        // +-----------------------+
12158        // |         top           |
12159        // +------+--------+-------+
12160        // | left | center | right |
12161        // +------+--------+-------+
12162        // |        bottom         |
12163        // +-----------------------+
12164
12165        let top_item = cx.new(|cx| {
12166            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12167        });
12168        let bottom_item = cx.new(|cx| {
12169            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12170        });
12171        let left_item = cx.new(|cx| {
12172            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12173        });
12174        let right_item = cx.new(|cx| {
12175            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12176        });
12177        let center_item = cx.new(|cx| {
12178            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12179        });
12180
12181        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12182            let top_pane_id = workspace.active_pane().entity_id();
12183            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12184            workspace.split_pane(
12185                workspace.active_pane().clone(),
12186                SplitDirection::Down,
12187                window,
12188                cx,
12189            );
12190            top_pane_id
12191        });
12192        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12193            let bottom_pane_id = workspace.active_pane().entity_id();
12194            workspace.add_item_to_active_pane(
12195                Box::new(bottom_item.clone()),
12196                None,
12197                false,
12198                window,
12199                cx,
12200            );
12201            workspace.split_pane(
12202                workspace.active_pane().clone(),
12203                SplitDirection::Up,
12204                window,
12205                cx,
12206            );
12207            bottom_pane_id
12208        });
12209        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12210            let left_pane_id = workspace.active_pane().entity_id();
12211            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12212            workspace.split_pane(
12213                workspace.active_pane().clone(),
12214                SplitDirection::Right,
12215                window,
12216                cx,
12217            );
12218            left_pane_id
12219        });
12220        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12221            let right_pane_id = workspace.active_pane().entity_id();
12222            workspace.add_item_to_active_pane(
12223                Box::new(right_item.clone()),
12224                None,
12225                false,
12226                window,
12227                cx,
12228            );
12229            workspace.split_pane(
12230                workspace.active_pane().clone(),
12231                SplitDirection::Left,
12232                window,
12233                cx,
12234            );
12235            right_pane_id
12236        });
12237        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12238            let center_pane_id = workspace.active_pane().entity_id();
12239            workspace.add_item_to_active_pane(
12240                Box::new(center_item.clone()),
12241                None,
12242                false,
12243                window,
12244                cx,
12245            );
12246            center_pane_id
12247        });
12248        cx.executor().run_until_parked();
12249
12250        workspace.update_in(cx, |workspace, window, cx| {
12251            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12252
12253            // Join into next from center pane into right
12254            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12255        });
12256
12257        workspace.update_in(cx, |workspace, window, cx| {
12258            let active_pane = workspace.active_pane();
12259            assert_eq!(right_pane_id, active_pane.entity_id());
12260            assert_eq!(2, active_pane.read(cx).items_len());
12261            let item_ids_in_pane =
12262                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12263            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12264            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12265
12266            // Join into next from right pane into bottom
12267            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12268        });
12269
12270        workspace.update_in(cx, |workspace, window, cx| {
12271            let active_pane = workspace.active_pane();
12272            assert_eq!(bottom_pane_id, active_pane.entity_id());
12273            assert_eq!(3, active_pane.read(cx).items_len());
12274            let item_ids_in_pane =
12275                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12276            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12277            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12278            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12279
12280            // Join into next from bottom pane into left
12281            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12282        });
12283
12284        workspace.update_in(cx, |workspace, window, cx| {
12285            let active_pane = workspace.active_pane();
12286            assert_eq!(left_pane_id, active_pane.entity_id());
12287            assert_eq!(4, active_pane.read(cx).items_len());
12288            let item_ids_in_pane =
12289                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12290            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12291            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12292            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12293            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12294
12295            // Join into next from left pane into top
12296            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12297        });
12298
12299        workspace.update_in(cx, |workspace, window, cx| {
12300            let active_pane = workspace.active_pane();
12301            assert_eq!(top_pane_id, active_pane.entity_id());
12302            assert_eq!(5, active_pane.read(cx).items_len());
12303            let item_ids_in_pane =
12304                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12305            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12306            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12307            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12308            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12309            assert!(item_ids_in_pane.contains(&top_item.item_id()));
12310
12311            // Single pane left: no-op
12312            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12313        });
12314
12315        workspace.update(cx, |workspace, _cx| {
12316            let active_pane = workspace.active_pane();
12317            assert_eq!(top_pane_id, active_pane.entity_id());
12318        });
12319    }
12320
12321    fn add_an_item_to_active_pane(
12322        cx: &mut VisualTestContext,
12323        workspace: &Entity<Workspace>,
12324        item_id: u64,
12325    ) -> Entity<TestItem> {
12326        let item = cx.new(|cx| {
12327            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12328                item_id,
12329                "item{item_id}.txt",
12330                cx,
12331            )])
12332        });
12333        workspace.update_in(cx, |workspace, window, cx| {
12334            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12335        });
12336        item
12337    }
12338
12339    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12340        workspace.update_in(cx, |workspace, window, cx| {
12341            workspace.split_pane(
12342                workspace.active_pane().clone(),
12343                SplitDirection::Right,
12344                window,
12345                cx,
12346            )
12347        })
12348    }
12349
12350    #[gpui::test]
12351    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12352        init_test(cx);
12353        let fs = FakeFs::new(cx.executor());
12354        let project = Project::test(fs, None, cx).await;
12355        let (workspace, cx) =
12356            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12357
12358        add_an_item_to_active_pane(cx, &workspace, 1);
12359        split_pane(cx, &workspace);
12360        add_an_item_to_active_pane(cx, &workspace, 2);
12361        split_pane(cx, &workspace); // empty pane
12362        split_pane(cx, &workspace);
12363        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12364
12365        cx.executor().run_until_parked();
12366
12367        workspace.update(cx, |workspace, cx| {
12368            let num_panes = workspace.panes().len();
12369            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12370            let active_item = workspace
12371                .active_pane()
12372                .read(cx)
12373                .active_item()
12374                .expect("item is in focus");
12375
12376            assert_eq!(num_panes, 4);
12377            assert_eq!(num_items_in_current_pane, 1);
12378            assert_eq!(active_item.item_id(), last_item.item_id());
12379        });
12380
12381        workspace.update_in(cx, |workspace, window, cx| {
12382            workspace.join_all_panes(window, cx);
12383        });
12384
12385        workspace.update(cx, |workspace, cx| {
12386            let num_panes = workspace.panes().len();
12387            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12388            let active_item = workspace
12389                .active_pane()
12390                .read(cx)
12391                .active_item()
12392                .expect("item is in focus");
12393
12394            assert_eq!(num_panes, 1);
12395            assert_eq!(num_items_in_current_pane, 3);
12396            assert_eq!(active_item.item_id(), last_item.item_id());
12397        });
12398    }
12399
12400    #[gpui::test]
12401    async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12402        init_test(cx);
12403        let fs = FakeFs::new(cx.executor());
12404
12405        let project = Project::test(fs, [], cx).await;
12406        let (multi_workspace, cx) =
12407            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12408        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12409
12410        workspace.update(cx, |workspace, _cx| {
12411            workspace.bounds.size.width = px(800.);
12412        });
12413
12414        workspace.update_in(cx, |workspace, window, cx| {
12415            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12416            workspace.add_panel(panel, window, cx);
12417            workspace.toggle_dock(DockPosition::Right, window, cx);
12418        });
12419
12420        let (panel, resized_width, ratio_basis_width) =
12421            workspace.update_in(cx, |workspace, window, cx| {
12422                let item = cx.new(|cx| {
12423                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12424                });
12425                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12426
12427                let dock = workspace.right_dock().read(cx);
12428                let workspace_width = workspace.bounds.size.width;
12429                let initial_width = workspace
12430                    .dock_size(&dock, window, cx)
12431                    .expect("flexible dock should have an initial width");
12432
12433                assert_eq!(initial_width, workspace_width / 2.);
12434
12435                workspace.resize_right_dock(px(300.), window, cx);
12436
12437                let dock = workspace.right_dock().read(cx);
12438                let resized_width = workspace
12439                    .dock_size(&dock, window, cx)
12440                    .expect("flexible dock should keep its resized width");
12441
12442                assert_eq!(resized_width, px(300.));
12443
12444                let panel = workspace
12445                    .right_dock()
12446                    .read(cx)
12447                    .visible_panel()
12448                    .expect("flexible dock should have a visible panel")
12449                    .panel_id();
12450
12451                (panel, resized_width, workspace_width)
12452            });
12453
12454        workspace.update_in(cx, |workspace, window, cx| {
12455            workspace.toggle_dock(DockPosition::Right, window, cx);
12456            workspace.toggle_dock(DockPosition::Right, window, cx);
12457
12458            let dock = workspace.right_dock().read(cx);
12459            let reopened_width = workspace
12460                .dock_size(&dock, window, cx)
12461                .expect("flexible dock should restore when reopened");
12462
12463            assert_eq!(reopened_width, resized_width);
12464
12465            let right_dock = workspace.right_dock().read(cx);
12466            let flexible_panel = right_dock
12467                .visible_panel()
12468                .expect("flexible dock should still have a visible panel");
12469            assert_eq!(flexible_panel.panel_id(), panel);
12470            assert_eq!(
12471                right_dock
12472                    .stored_panel_size_state(flexible_panel.as_ref())
12473                    .and_then(|size_state| size_state.flex),
12474                Some(
12475                    resized_width.to_f64() as f32
12476                        / (workspace.bounds.size.width - resized_width).to_f64() as f32
12477                )
12478            );
12479        });
12480
12481        workspace.update_in(cx, |workspace, window, cx| {
12482            workspace.split_pane(
12483                workspace.active_pane().clone(),
12484                SplitDirection::Right,
12485                window,
12486                cx,
12487            );
12488
12489            let dock = workspace.right_dock().read(cx);
12490            let split_width = workspace
12491                .dock_size(&dock, window, cx)
12492                .expect("flexible dock should keep its user-resized proportion");
12493
12494            assert_eq!(split_width, px(300.));
12495
12496            workspace.bounds.size.width = px(1600.);
12497
12498            let dock = workspace.right_dock().read(cx);
12499            let resized_window_width = workspace
12500                .dock_size(&dock, window, cx)
12501                .expect("flexible dock should preserve proportional size on window resize");
12502
12503            assert_eq!(
12504                resized_window_width,
12505                workspace.bounds.size.width
12506                    * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12507            );
12508        });
12509    }
12510
12511    #[gpui::test]
12512    async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12513        init_test(cx);
12514        let fs = FakeFs::new(cx.executor());
12515
12516        // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12517        {
12518            let project = Project::test(fs.clone(), [], cx).await;
12519            let (multi_workspace, cx) =
12520                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12521            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12522
12523            workspace.update(cx, |workspace, _cx| {
12524                workspace.set_random_database_id();
12525                workspace.bounds.size.width = px(800.);
12526            });
12527
12528            let panel = workspace.update_in(cx, |workspace, window, cx| {
12529                let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12530                workspace.add_panel(panel.clone(), window, cx);
12531                workspace.toggle_dock(DockPosition::Left, window, cx);
12532                panel
12533            });
12534
12535            workspace.update_in(cx, |workspace, window, cx| {
12536                workspace.resize_left_dock(px(350.), window, cx);
12537            });
12538
12539            cx.run_until_parked();
12540
12541            let persisted = workspace.read_with(cx, |workspace, cx| {
12542                workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12543            });
12544            assert_eq!(
12545                persisted.and_then(|s| s.size),
12546                Some(px(350.)),
12547                "fixed-width panel size should be persisted to KVP"
12548            );
12549
12550            // Remove the panel and re-add a fresh instance with the same key.
12551            // The new instance should have its size state restored from KVP.
12552            workspace.update_in(cx, |workspace, window, cx| {
12553                workspace.remove_panel(&panel, window, cx);
12554            });
12555
12556            workspace.update_in(cx, |workspace, window, cx| {
12557                let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12558                workspace.add_panel(new_panel, window, cx);
12559
12560                let left_dock = workspace.left_dock().read(cx);
12561                let size_state = left_dock
12562                    .panel::<TestPanel>()
12563                    .and_then(|p| left_dock.stored_panel_size_state(&p));
12564                assert_eq!(
12565                    size_state.and_then(|s| s.size),
12566                    Some(px(350.)),
12567                    "re-added fixed-width panel should restore persisted size from KVP"
12568                );
12569            });
12570        }
12571
12572        // Flexible panel: both pixel size and ratio are persisted and restored.
12573        {
12574            let project = Project::test(fs.clone(), [], cx).await;
12575            let (multi_workspace, cx) =
12576                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12577            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12578
12579            workspace.update(cx, |workspace, _cx| {
12580                workspace.set_random_database_id();
12581                workspace.bounds.size.width = px(800.);
12582            });
12583
12584            let panel = workspace.update_in(cx, |workspace, window, cx| {
12585                let item = cx.new(|cx| {
12586                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12587                });
12588                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12589
12590                let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12591                workspace.add_panel(panel.clone(), window, cx);
12592                workspace.toggle_dock(DockPosition::Right, window, cx);
12593                panel
12594            });
12595
12596            workspace.update_in(cx, |workspace, window, cx| {
12597                workspace.resize_right_dock(px(300.), window, cx);
12598            });
12599
12600            cx.run_until_parked();
12601
12602            let persisted = workspace
12603                .read_with(cx, |workspace, cx| {
12604                    workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12605                })
12606                .expect("flexible panel state should be persisted to KVP");
12607            assert_eq!(
12608                persisted.size, None,
12609                "flexible panel should not persist a redundant pixel size"
12610            );
12611            let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12612
12613            // Remove the panel and re-add: both size and ratio should be restored.
12614            workspace.update_in(cx, |workspace, window, cx| {
12615                workspace.remove_panel(&panel, window, cx);
12616            });
12617
12618            workspace.update_in(cx, |workspace, window, cx| {
12619                let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12620                workspace.add_panel(new_panel, window, cx);
12621
12622                let right_dock = workspace.right_dock().read(cx);
12623                let size_state = right_dock
12624                    .panel::<TestPanel>()
12625                    .and_then(|p| right_dock.stored_panel_size_state(&p))
12626                    .expect("re-added flexible panel should have restored size state from KVP");
12627                assert_eq!(
12628                    size_state.size, None,
12629                    "re-added flexible panel should not have a persisted pixel size"
12630                );
12631                assert_eq!(
12632                    size_state.flex,
12633                    Some(original_ratio),
12634                    "re-added flexible panel should restore persisted flex"
12635                );
12636            });
12637        }
12638    }
12639
12640    #[gpui::test]
12641    async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12642        init_test(cx);
12643        let fs = FakeFs::new(cx.executor());
12644
12645        let project = Project::test(fs, [], cx).await;
12646        let (multi_workspace, cx) =
12647            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12648        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12649
12650        workspace.update(cx, |workspace, _cx| {
12651            workspace.bounds.size.width = px(900.);
12652        });
12653
12654        // Step 1: Add a tab to the center pane then open a flexible panel in the left
12655        // dock. With one full-width center pane the default ratio is 0.5, so the panel
12656        // and the center pane each take half the workspace width.
12657        workspace.update_in(cx, |workspace, window, cx| {
12658            let item = cx.new(|cx| {
12659                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12660            });
12661            workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12662
12663            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12664            workspace.add_panel(panel, window, cx);
12665            workspace.toggle_dock(DockPosition::Left, window, cx);
12666
12667            let left_dock = workspace.left_dock().read(cx);
12668            let left_width = workspace
12669                .dock_size(&left_dock, window, cx)
12670                .expect("left dock should have an active panel");
12671
12672            assert_eq!(
12673                left_width,
12674                workspace.bounds.size.width / 2.,
12675                "flexible left panel should split evenly with the center pane"
12676            );
12677        });
12678
12679        // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12680        // change horizontal width fractions, so the flexible panel stays at the same
12681        // width as each half of the split.
12682        workspace.update_in(cx, |workspace, window, cx| {
12683            workspace.split_pane(
12684                workspace.active_pane().clone(),
12685                SplitDirection::Down,
12686                window,
12687                cx,
12688            );
12689
12690            let left_dock = workspace.left_dock().read(cx);
12691            let left_width = workspace
12692                .dock_size(&left_dock, window, cx)
12693                .expect("left dock should still have an active panel after vertical split");
12694
12695            assert_eq!(
12696                left_width,
12697                workspace.bounds.size.width / 2.,
12698                "flexible left panel width should match each vertically-split pane"
12699            );
12700        });
12701
12702        // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12703        // size reduces the available width, so the flexible left panel and the center
12704        // panes all shrink proportionally to accommodate it.
12705        workspace.update_in(cx, |workspace, window, cx| {
12706            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12707            workspace.add_panel(panel, window, cx);
12708            workspace.toggle_dock(DockPosition::Right, window, cx);
12709
12710            let right_dock = workspace.right_dock().read(cx);
12711            let right_width = workspace
12712                .dock_size(&right_dock, window, cx)
12713                .expect("right dock should have an active panel");
12714
12715            let left_dock = workspace.left_dock().read(cx);
12716            let left_width = workspace
12717                .dock_size(&left_dock, window, cx)
12718                .expect("left dock should still have an active panel");
12719
12720            let available_width = workspace.bounds.size.width - right_width;
12721            assert_eq!(
12722                left_width,
12723                available_width / 2.,
12724                "flexible left panel should shrink proportionally as the right dock takes space"
12725            );
12726        });
12727
12728        // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12729        // flex sizing and the workspace width is divided among left-flex, center
12730        // (implicit flex 1.0), and right-flex.
12731        workspace.update_in(cx, |workspace, window, cx| {
12732            let right_dock = workspace.right_dock().clone();
12733            let right_panel = right_dock
12734                .read(cx)
12735                .visible_panel()
12736                .expect("right dock should have a visible panel")
12737                .clone();
12738            workspace.toggle_dock_panel_flexible_size(
12739                &right_dock,
12740                right_panel.as_ref(),
12741                window,
12742                cx,
12743            );
12744
12745            let right_dock = right_dock.read(cx);
12746            let right_panel = right_dock
12747                .visible_panel()
12748                .expect("right dock should still have a visible panel");
12749            assert!(
12750                right_panel.has_flexible_size(window, cx),
12751                "right panel should now be flexible"
12752            );
12753
12754            let right_size_state = right_dock
12755                .stored_panel_size_state(right_panel.as_ref())
12756                .expect("right panel should have a stored size state after toggling");
12757            let right_flex = right_size_state
12758                .flex
12759                .expect("right panel should have a flex value after toggling");
12760
12761            let left_dock = workspace.left_dock().read(cx);
12762            let left_width = workspace
12763                .dock_size(&left_dock, window, cx)
12764                .expect("left dock should still have an active panel");
12765            let right_width = workspace
12766                .dock_size(&right_dock, window, cx)
12767                .expect("right dock should still have an active panel");
12768
12769            let left_flex = workspace
12770                .default_dock_flex(DockPosition::Left)
12771                .expect("left dock should have a default flex");
12772
12773            let total_flex = left_flex + 1.0 + right_flex;
12774            let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12775            let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12776            assert_eq!(
12777                left_width, expected_left,
12778                "flexible left panel should share workspace width via flex ratios"
12779            );
12780            assert_eq!(
12781                right_width, expected_right,
12782                "flexible right panel should share workspace width via flex ratios"
12783            );
12784        });
12785    }
12786
12787    struct TestModal(FocusHandle);
12788
12789    impl TestModal {
12790        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12791            Self(cx.focus_handle())
12792        }
12793    }
12794
12795    impl EventEmitter<DismissEvent> for TestModal {}
12796
12797    impl Focusable for TestModal {
12798        fn focus_handle(&self, _cx: &App) -> FocusHandle {
12799            self.0.clone()
12800        }
12801    }
12802
12803    impl ModalView for TestModal {}
12804
12805    impl Render for TestModal {
12806        fn render(
12807            &mut self,
12808            _window: &mut Window,
12809            _cx: &mut Context<TestModal>,
12810        ) -> impl IntoElement {
12811            div().track_focus(&self.0)
12812        }
12813    }
12814
12815    #[gpui::test]
12816    async fn test_panels(cx: &mut gpui::TestAppContext) {
12817        init_test(cx);
12818        let fs = FakeFs::new(cx.executor());
12819
12820        let project = Project::test(fs, [], cx).await;
12821        let (multi_workspace, cx) =
12822            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12823        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12824
12825        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12826            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12827            workspace.add_panel(panel_1.clone(), window, cx);
12828            workspace.toggle_dock(DockPosition::Left, window, cx);
12829            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12830            workspace.add_panel(panel_2.clone(), window, cx);
12831            workspace.toggle_dock(DockPosition::Right, window, cx);
12832
12833            let left_dock = workspace.left_dock();
12834            assert_eq!(
12835                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12836                panel_1.panel_id()
12837            );
12838            assert_eq!(
12839                workspace.dock_size(&left_dock.read(cx), window, cx),
12840                Some(px(300.))
12841            );
12842
12843            workspace.resize_left_dock(px(1337.), window, cx);
12844            assert_eq!(
12845                workspace
12846                    .right_dock()
12847                    .read(cx)
12848                    .visible_panel()
12849                    .unwrap()
12850                    .panel_id(),
12851                panel_2.panel_id(),
12852            );
12853
12854            (panel_1, panel_2)
12855        });
12856
12857        // Move panel_1 to the right
12858        panel_1.update_in(cx, |panel_1, window, cx| {
12859            panel_1.set_position(DockPosition::Right, window, cx)
12860        });
12861
12862        workspace.update_in(cx, |workspace, window, cx| {
12863            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12864            // Since it was the only panel on the left, the left dock should now be closed.
12865            assert!(!workspace.left_dock().read(cx).is_open());
12866            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12867            let right_dock = workspace.right_dock();
12868            assert_eq!(
12869                right_dock.read(cx).visible_panel().unwrap().panel_id(),
12870                panel_1.panel_id()
12871            );
12872            assert_eq!(
12873                right_dock
12874                    .read(cx)
12875                    .active_panel_size()
12876                    .unwrap()
12877                    .size
12878                    .unwrap(),
12879                px(1337.)
12880            );
12881
12882            // Now we move panel_2 to the left
12883            panel_2.set_position(DockPosition::Left, window, cx);
12884        });
12885
12886        workspace.update(cx, |workspace, cx| {
12887            // Since panel_2 was not visible on the right, we don't open the left dock.
12888            assert!(!workspace.left_dock().read(cx).is_open());
12889            // And the right dock is unaffected in its displaying of panel_1
12890            assert!(workspace.right_dock().read(cx).is_open());
12891            assert_eq!(
12892                workspace
12893                    .right_dock()
12894                    .read(cx)
12895                    .visible_panel()
12896                    .unwrap()
12897                    .panel_id(),
12898                panel_1.panel_id(),
12899            );
12900        });
12901
12902        // Move panel_1 back to the left
12903        panel_1.update_in(cx, |panel_1, window, cx| {
12904            panel_1.set_position(DockPosition::Left, window, cx)
12905        });
12906
12907        workspace.update_in(cx, |workspace, window, cx| {
12908            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12909            let left_dock = workspace.left_dock();
12910            assert!(left_dock.read(cx).is_open());
12911            assert_eq!(
12912                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12913                panel_1.panel_id()
12914            );
12915            assert_eq!(
12916                workspace.dock_size(&left_dock.read(cx), window, cx),
12917                Some(px(1337.))
12918            );
12919            // And the right dock should be closed as it no longer has any panels.
12920            assert!(!workspace.right_dock().read(cx).is_open());
12921
12922            // Now we move panel_1 to the bottom
12923            panel_1.set_position(DockPosition::Bottom, window, cx);
12924        });
12925
12926        workspace.update_in(cx, |workspace, window, cx| {
12927            // Since panel_1 was visible on the left, we close the left dock.
12928            assert!(!workspace.left_dock().read(cx).is_open());
12929            // The bottom dock is sized based on the panel's default size,
12930            // since the panel orientation changed from vertical to horizontal.
12931            let bottom_dock = workspace.bottom_dock();
12932            assert_eq!(
12933                workspace.dock_size(&bottom_dock.read(cx), window, cx),
12934                Some(px(300.))
12935            );
12936            // Close bottom dock and move panel_1 back to the left.
12937            bottom_dock.update(cx, |bottom_dock, cx| {
12938                bottom_dock.set_open(false, window, cx)
12939            });
12940            panel_1.set_position(DockPosition::Left, window, cx);
12941        });
12942
12943        // Emit activated event on panel 1
12944        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12945
12946        // Now the left dock is open and panel_1 is active and focused.
12947        workspace.update_in(cx, |workspace, window, cx| {
12948            let left_dock = workspace.left_dock();
12949            assert!(left_dock.read(cx).is_open());
12950            assert_eq!(
12951                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12952                panel_1.panel_id(),
12953            );
12954            assert!(panel_1.focus_handle(cx).is_focused(window));
12955        });
12956
12957        // Emit closed event on panel 2, which is not active
12958        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12959
12960        // Wo don't close the left dock, because panel_2 wasn't the active panel
12961        workspace.update(cx, |workspace, cx| {
12962            let left_dock = workspace.left_dock();
12963            assert!(left_dock.read(cx).is_open());
12964            assert_eq!(
12965                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12966                panel_1.panel_id(),
12967            );
12968        });
12969
12970        // Emitting a ZoomIn event shows the panel as zoomed.
12971        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12972        workspace.read_with(cx, |workspace, _| {
12973            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12974            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12975        });
12976
12977        // Move panel to another dock while it is zoomed
12978        panel_1.update_in(cx, |panel, window, cx| {
12979            panel.set_position(DockPosition::Right, window, cx)
12980        });
12981        workspace.read_with(cx, |workspace, _| {
12982            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12983
12984            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12985        });
12986
12987        // This is a helper for getting a:
12988        // - valid focus on an element,
12989        // - that isn't a part of the panes and panels system of the Workspace,
12990        // - and doesn't trigger the 'on_focus_lost' API.
12991        let focus_other_view = {
12992            let workspace = workspace.clone();
12993            move |cx: &mut VisualTestContext| {
12994                workspace.update_in(cx, |workspace, window, cx| {
12995                    if workspace.active_modal::<TestModal>(cx).is_some() {
12996                        workspace.toggle_modal(window, cx, TestModal::new);
12997                        workspace.toggle_modal(window, cx, TestModal::new);
12998                    } else {
12999                        workspace.toggle_modal(window, cx, TestModal::new);
13000                    }
13001                })
13002            }
13003        };
13004
13005        // If focus is transferred to another view that's not a panel or another pane, we still show
13006        // the panel as zoomed.
13007        focus_other_view(cx);
13008        workspace.read_with(cx, |workspace, _| {
13009            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13010            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13011        });
13012
13013        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13014        workspace.update_in(cx, |_workspace, window, cx| {
13015            cx.focus_self(window);
13016        });
13017        workspace.read_with(cx, |workspace, _| {
13018            assert_eq!(workspace.zoomed, None);
13019            assert_eq!(workspace.zoomed_position, None);
13020        });
13021
13022        // If focus is transferred again to another view that's not a panel or a pane, we won't
13023        // show the panel as zoomed because it wasn't zoomed before.
13024        focus_other_view(cx);
13025        workspace.read_with(cx, |workspace, _| {
13026            assert_eq!(workspace.zoomed, None);
13027            assert_eq!(workspace.zoomed_position, None);
13028        });
13029
13030        // When the panel is activated, it is zoomed again.
13031        cx.dispatch_action(ToggleRightDock);
13032        workspace.read_with(cx, |workspace, _| {
13033            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13034            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13035        });
13036
13037        // Emitting a ZoomOut event unzooms the panel.
13038        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13039        workspace.read_with(cx, |workspace, _| {
13040            assert_eq!(workspace.zoomed, None);
13041            assert_eq!(workspace.zoomed_position, None);
13042        });
13043
13044        // Emit closed event on panel 1, which is active
13045        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13046
13047        // Now the left dock is closed, because panel_1 was the active panel
13048        workspace.update(cx, |workspace, cx| {
13049            let right_dock = workspace.right_dock();
13050            assert!(!right_dock.read(cx).is_open());
13051        });
13052    }
13053
13054    #[gpui::test]
13055    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13056        init_test(cx);
13057
13058        let fs = FakeFs::new(cx.background_executor.clone());
13059        let project = Project::test(fs, [], cx).await;
13060        let (workspace, cx) =
13061            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13062        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13063
13064        let dirty_regular_buffer = cx.new(|cx| {
13065            TestItem::new(cx)
13066                .with_dirty(true)
13067                .with_label("1.txt")
13068                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13069        });
13070        let dirty_regular_buffer_2 = cx.new(|cx| {
13071            TestItem::new(cx)
13072                .with_dirty(true)
13073                .with_label("2.txt")
13074                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13075        });
13076        let dirty_multi_buffer_with_both = cx.new(|cx| {
13077            TestItem::new(cx)
13078                .with_dirty(true)
13079                .with_buffer_kind(ItemBufferKind::Multibuffer)
13080                .with_label("Fake Project Search")
13081                .with_project_items(&[
13082                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13083                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13084                ])
13085        });
13086        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13087        workspace.update_in(cx, |workspace, window, cx| {
13088            workspace.add_item(
13089                pane.clone(),
13090                Box::new(dirty_regular_buffer.clone()),
13091                None,
13092                false,
13093                false,
13094                window,
13095                cx,
13096            );
13097            workspace.add_item(
13098                pane.clone(),
13099                Box::new(dirty_regular_buffer_2.clone()),
13100                None,
13101                false,
13102                false,
13103                window,
13104                cx,
13105            );
13106            workspace.add_item(
13107                pane.clone(),
13108                Box::new(dirty_multi_buffer_with_both.clone()),
13109                None,
13110                false,
13111                false,
13112                window,
13113                cx,
13114            );
13115        });
13116
13117        pane.update_in(cx, |pane, window, cx| {
13118            pane.activate_item(2, true, true, window, cx);
13119            assert_eq!(
13120                pane.active_item().unwrap().item_id(),
13121                multi_buffer_with_both_files_id,
13122                "Should select the multi buffer in the pane"
13123            );
13124        });
13125        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13126            pane.close_other_items(
13127                &CloseOtherItems {
13128                    save_intent: Some(SaveIntent::Save),
13129                    close_pinned: true,
13130                },
13131                None,
13132                window,
13133                cx,
13134            )
13135        });
13136        cx.background_executor.run_until_parked();
13137        assert!(!cx.has_pending_prompt());
13138        close_all_but_multi_buffer_task
13139            .await
13140            .expect("Closing all buffers but the multi buffer failed");
13141        pane.update(cx, |pane, cx| {
13142            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13143            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13144            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13145            assert_eq!(pane.items_len(), 1);
13146            assert_eq!(
13147                pane.active_item().unwrap().item_id(),
13148                multi_buffer_with_both_files_id,
13149                "Should have only the multi buffer left in the pane"
13150            );
13151            assert!(
13152                dirty_multi_buffer_with_both.read(cx).is_dirty,
13153                "The multi buffer containing the unsaved buffer should still be dirty"
13154            );
13155        });
13156
13157        dirty_regular_buffer.update(cx, |buffer, cx| {
13158            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13159        });
13160
13161        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13162            pane.close_active_item(
13163                &CloseActiveItem {
13164                    save_intent: Some(SaveIntent::Close),
13165                    close_pinned: false,
13166                },
13167                window,
13168                cx,
13169            )
13170        });
13171        cx.background_executor.run_until_parked();
13172        assert!(
13173            cx.has_pending_prompt(),
13174            "Dirty multi buffer should prompt a save dialog"
13175        );
13176        cx.simulate_prompt_answer("Save");
13177        cx.background_executor.run_until_parked();
13178        close_multi_buffer_task
13179            .await
13180            .expect("Closing the multi buffer failed");
13181        pane.update(cx, |pane, cx| {
13182            assert_eq!(
13183                dirty_multi_buffer_with_both.read(cx).save_count,
13184                1,
13185                "Multi buffer item should get be saved"
13186            );
13187            // Test impl does not save inner items, so we do not assert them
13188            assert_eq!(
13189                pane.items_len(),
13190                0,
13191                "No more items should be left in the pane"
13192            );
13193            assert!(pane.active_item().is_none());
13194        });
13195    }
13196
13197    #[gpui::test]
13198    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13199        cx: &mut TestAppContext,
13200    ) {
13201        init_test(cx);
13202
13203        let fs = FakeFs::new(cx.background_executor.clone());
13204        let project = Project::test(fs, [], cx).await;
13205        let (workspace, cx) =
13206            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13207        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13208
13209        let dirty_regular_buffer = cx.new(|cx| {
13210            TestItem::new(cx)
13211                .with_dirty(true)
13212                .with_label("1.txt")
13213                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13214        });
13215        let dirty_regular_buffer_2 = cx.new(|cx| {
13216            TestItem::new(cx)
13217                .with_dirty(true)
13218                .with_label("2.txt")
13219                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13220        });
13221        let clear_regular_buffer = cx.new(|cx| {
13222            TestItem::new(cx)
13223                .with_label("3.txt")
13224                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13225        });
13226
13227        let dirty_multi_buffer_with_both = cx.new(|cx| {
13228            TestItem::new(cx)
13229                .with_dirty(true)
13230                .with_buffer_kind(ItemBufferKind::Multibuffer)
13231                .with_label("Fake Project Search")
13232                .with_project_items(&[
13233                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13234                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13235                    clear_regular_buffer.read(cx).project_items[0].clone(),
13236                ])
13237        });
13238        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13239        workspace.update_in(cx, |workspace, window, cx| {
13240            workspace.add_item(
13241                pane.clone(),
13242                Box::new(dirty_regular_buffer.clone()),
13243                None,
13244                false,
13245                false,
13246                window,
13247                cx,
13248            );
13249            workspace.add_item(
13250                pane.clone(),
13251                Box::new(dirty_multi_buffer_with_both.clone()),
13252                None,
13253                false,
13254                false,
13255                window,
13256                cx,
13257            );
13258        });
13259
13260        pane.update_in(cx, |pane, window, cx| {
13261            pane.activate_item(1, true, true, window, cx);
13262            assert_eq!(
13263                pane.active_item().unwrap().item_id(),
13264                multi_buffer_with_both_files_id,
13265                "Should select the multi buffer in the pane"
13266            );
13267        });
13268        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13269            pane.close_active_item(
13270                &CloseActiveItem {
13271                    save_intent: None,
13272                    close_pinned: false,
13273                },
13274                window,
13275                cx,
13276            )
13277        });
13278        cx.background_executor.run_until_parked();
13279        assert!(
13280            cx.has_pending_prompt(),
13281            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13282        );
13283    }
13284
13285    /// Tests that when `close_on_file_delete` is enabled, files are automatically
13286    /// closed when they are deleted from disk.
13287    #[gpui::test]
13288    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13289        init_test(cx);
13290
13291        // Enable the close_on_disk_deletion setting
13292        cx.update_global(|store: &mut SettingsStore, cx| {
13293            store.update_user_settings(cx, |settings| {
13294                settings.workspace.close_on_file_delete = Some(true);
13295            });
13296        });
13297
13298        let fs = FakeFs::new(cx.background_executor.clone());
13299        let project = Project::test(fs, [], cx).await;
13300        let (workspace, cx) =
13301            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13302        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13303
13304        // Create a test item that simulates a file
13305        let item = cx.new(|cx| {
13306            TestItem::new(cx)
13307                .with_label("test.txt")
13308                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13309        });
13310
13311        // Add item to workspace
13312        workspace.update_in(cx, |workspace, window, cx| {
13313            workspace.add_item(
13314                pane.clone(),
13315                Box::new(item.clone()),
13316                None,
13317                false,
13318                false,
13319                window,
13320                cx,
13321            );
13322        });
13323
13324        // Verify the item is in the pane
13325        pane.read_with(cx, |pane, _| {
13326            assert_eq!(pane.items().count(), 1);
13327        });
13328
13329        // Simulate file deletion by setting the item's deleted state
13330        item.update(cx, |item, _| {
13331            item.set_has_deleted_file(true);
13332        });
13333
13334        // Emit UpdateTab event to trigger the close behavior
13335        cx.run_until_parked();
13336        item.update(cx, |_, cx| {
13337            cx.emit(ItemEvent::UpdateTab);
13338        });
13339
13340        // Allow the close operation to complete
13341        cx.run_until_parked();
13342
13343        // Verify the item was automatically closed
13344        pane.read_with(cx, |pane, _| {
13345            assert_eq!(
13346                pane.items().count(),
13347                0,
13348                "Item should be automatically closed when file is deleted"
13349            );
13350        });
13351    }
13352
13353    /// Tests that when `close_on_file_delete` is disabled (default), files remain
13354    /// open with a strikethrough when they are deleted from disk.
13355    #[gpui::test]
13356    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13357        init_test(cx);
13358
13359        // Ensure close_on_disk_deletion is disabled (default)
13360        cx.update_global(|store: &mut SettingsStore, cx| {
13361            store.update_user_settings(cx, |settings| {
13362                settings.workspace.close_on_file_delete = Some(false);
13363            });
13364        });
13365
13366        let fs = FakeFs::new(cx.background_executor.clone());
13367        let project = Project::test(fs, [], cx).await;
13368        let (workspace, cx) =
13369            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13370        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13371
13372        // Create a test item that simulates a file
13373        let item = cx.new(|cx| {
13374            TestItem::new(cx)
13375                .with_label("test.txt")
13376                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13377        });
13378
13379        // Add item to workspace
13380        workspace.update_in(cx, |workspace, window, cx| {
13381            workspace.add_item(
13382                pane.clone(),
13383                Box::new(item.clone()),
13384                None,
13385                false,
13386                false,
13387                window,
13388                cx,
13389            );
13390        });
13391
13392        // Verify the item is in the pane
13393        pane.read_with(cx, |pane, _| {
13394            assert_eq!(pane.items().count(), 1);
13395        });
13396
13397        // Simulate file deletion
13398        item.update(cx, |item, _| {
13399            item.set_has_deleted_file(true);
13400        });
13401
13402        // Emit UpdateTab event
13403        cx.run_until_parked();
13404        item.update(cx, |_, cx| {
13405            cx.emit(ItemEvent::UpdateTab);
13406        });
13407
13408        // Allow any potential close operation to complete
13409        cx.run_until_parked();
13410
13411        // Verify the item remains open (with strikethrough)
13412        pane.read_with(cx, |pane, _| {
13413            assert_eq!(
13414                pane.items().count(),
13415                1,
13416                "Item should remain open when close_on_disk_deletion is disabled"
13417            );
13418        });
13419
13420        // Verify the item shows as deleted
13421        item.read_with(cx, |item, _| {
13422            assert!(
13423                item.has_deleted_file,
13424                "Item should be marked as having deleted file"
13425            );
13426        });
13427    }
13428
13429    /// Tests that dirty files are not automatically closed when deleted from disk,
13430    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13431    /// unsaved changes without being prompted.
13432    #[gpui::test]
13433    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13434        init_test(cx);
13435
13436        // Enable the close_on_file_delete setting
13437        cx.update_global(|store: &mut SettingsStore, cx| {
13438            store.update_user_settings(cx, |settings| {
13439                settings.workspace.close_on_file_delete = Some(true);
13440            });
13441        });
13442
13443        let fs = FakeFs::new(cx.background_executor.clone());
13444        let project = Project::test(fs, [], cx).await;
13445        let (workspace, cx) =
13446            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13447        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13448
13449        // Create a dirty test item
13450        let item = cx.new(|cx| {
13451            TestItem::new(cx)
13452                .with_dirty(true)
13453                .with_label("test.txt")
13454                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13455        });
13456
13457        // Add item to workspace
13458        workspace.update_in(cx, |workspace, window, cx| {
13459            workspace.add_item(
13460                pane.clone(),
13461                Box::new(item.clone()),
13462                None,
13463                false,
13464                false,
13465                window,
13466                cx,
13467            );
13468        });
13469
13470        // Simulate file deletion
13471        item.update(cx, |item, _| {
13472            item.set_has_deleted_file(true);
13473        });
13474
13475        // Emit UpdateTab event to trigger the close behavior
13476        cx.run_until_parked();
13477        item.update(cx, |_, cx| {
13478            cx.emit(ItemEvent::UpdateTab);
13479        });
13480
13481        // Allow any potential close operation to complete
13482        cx.run_until_parked();
13483
13484        // Verify the item remains open (dirty files are not auto-closed)
13485        pane.read_with(cx, |pane, _| {
13486            assert_eq!(
13487                pane.items().count(),
13488                1,
13489                "Dirty items should not be automatically closed even when file is deleted"
13490            );
13491        });
13492
13493        // Verify the item is marked as deleted and still dirty
13494        item.read_with(cx, |item, _| {
13495            assert!(
13496                item.has_deleted_file,
13497                "Item should be marked as having deleted file"
13498            );
13499            assert!(item.is_dirty, "Item should still be dirty");
13500        });
13501    }
13502
13503    /// Tests that navigation history is cleaned up when files are auto-closed
13504    /// due to deletion from disk.
13505    #[gpui::test]
13506    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13507        init_test(cx);
13508
13509        // Enable the close_on_file_delete setting
13510        cx.update_global(|store: &mut SettingsStore, cx| {
13511            store.update_user_settings(cx, |settings| {
13512                settings.workspace.close_on_file_delete = Some(true);
13513            });
13514        });
13515
13516        let fs = FakeFs::new(cx.background_executor.clone());
13517        let project = Project::test(fs, [], cx).await;
13518        let (workspace, cx) =
13519            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13520        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13521
13522        // Create test items
13523        let item1 = cx.new(|cx| {
13524            TestItem::new(cx)
13525                .with_label("test1.txt")
13526                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13527        });
13528        let item1_id = item1.item_id();
13529
13530        let item2 = cx.new(|cx| {
13531            TestItem::new(cx)
13532                .with_label("test2.txt")
13533                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13534        });
13535
13536        // Add items to workspace
13537        workspace.update_in(cx, |workspace, window, cx| {
13538            workspace.add_item(
13539                pane.clone(),
13540                Box::new(item1.clone()),
13541                None,
13542                false,
13543                false,
13544                window,
13545                cx,
13546            );
13547            workspace.add_item(
13548                pane.clone(),
13549                Box::new(item2.clone()),
13550                None,
13551                false,
13552                false,
13553                window,
13554                cx,
13555            );
13556        });
13557
13558        // Activate item1 to ensure it gets navigation entries
13559        pane.update_in(cx, |pane, window, cx| {
13560            pane.activate_item(0, true, true, window, cx);
13561        });
13562
13563        // Switch to item2 and back to create navigation history
13564        pane.update_in(cx, |pane, window, cx| {
13565            pane.activate_item(1, true, true, window, cx);
13566        });
13567        cx.run_until_parked();
13568
13569        pane.update_in(cx, |pane, window, cx| {
13570            pane.activate_item(0, true, true, window, cx);
13571        });
13572        cx.run_until_parked();
13573
13574        // Simulate file deletion for item1
13575        item1.update(cx, |item, _| {
13576            item.set_has_deleted_file(true);
13577        });
13578
13579        // Emit UpdateTab event to trigger the close behavior
13580        item1.update(cx, |_, cx| {
13581            cx.emit(ItemEvent::UpdateTab);
13582        });
13583        cx.run_until_parked();
13584
13585        // Verify item1 was closed
13586        pane.read_with(cx, |pane, _| {
13587            assert_eq!(
13588                pane.items().count(),
13589                1,
13590                "Should have 1 item remaining after auto-close"
13591            );
13592        });
13593
13594        // Check navigation history after close
13595        let has_item = pane.read_with(cx, |pane, cx| {
13596            let mut has_item = false;
13597            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13598                if entry.item.id() == item1_id {
13599                    has_item = true;
13600                }
13601            });
13602            has_item
13603        });
13604
13605        assert!(
13606            !has_item,
13607            "Navigation history should not contain closed item entries"
13608        );
13609    }
13610
13611    #[gpui::test]
13612    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13613        cx: &mut TestAppContext,
13614    ) {
13615        init_test(cx);
13616
13617        let fs = FakeFs::new(cx.background_executor.clone());
13618        let project = Project::test(fs, [], cx).await;
13619        let (workspace, cx) =
13620            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13621        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13622
13623        let dirty_regular_buffer = cx.new(|cx| {
13624            TestItem::new(cx)
13625                .with_dirty(true)
13626                .with_label("1.txt")
13627                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13628        });
13629        let dirty_regular_buffer_2 = cx.new(|cx| {
13630            TestItem::new(cx)
13631                .with_dirty(true)
13632                .with_label("2.txt")
13633                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13634        });
13635        let clear_regular_buffer = cx.new(|cx| {
13636            TestItem::new(cx)
13637                .with_label("3.txt")
13638                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13639        });
13640
13641        let dirty_multi_buffer = cx.new(|cx| {
13642            TestItem::new(cx)
13643                .with_dirty(true)
13644                .with_buffer_kind(ItemBufferKind::Multibuffer)
13645                .with_label("Fake Project Search")
13646                .with_project_items(&[
13647                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13648                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13649                    clear_regular_buffer.read(cx).project_items[0].clone(),
13650                ])
13651        });
13652        workspace.update_in(cx, |workspace, window, cx| {
13653            workspace.add_item(
13654                pane.clone(),
13655                Box::new(dirty_regular_buffer.clone()),
13656                None,
13657                false,
13658                false,
13659                window,
13660                cx,
13661            );
13662            workspace.add_item(
13663                pane.clone(),
13664                Box::new(dirty_regular_buffer_2.clone()),
13665                None,
13666                false,
13667                false,
13668                window,
13669                cx,
13670            );
13671            workspace.add_item(
13672                pane.clone(),
13673                Box::new(dirty_multi_buffer.clone()),
13674                None,
13675                false,
13676                false,
13677                window,
13678                cx,
13679            );
13680        });
13681
13682        pane.update_in(cx, |pane, window, cx| {
13683            pane.activate_item(2, true, true, window, cx);
13684            assert_eq!(
13685                pane.active_item().unwrap().item_id(),
13686                dirty_multi_buffer.item_id(),
13687                "Should select the multi buffer in the pane"
13688            );
13689        });
13690        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13691            pane.close_active_item(
13692                &CloseActiveItem {
13693                    save_intent: None,
13694                    close_pinned: false,
13695                },
13696                window,
13697                cx,
13698            )
13699        });
13700        cx.background_executor.run_until_parked();
13701        assert!(
13702            !cx.has_pending_prompt(),
13703            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13704        );
13705        close_multi_buffer_task
13706            .await
13707            .expect("Closing multi buffer failed");
13708        pane.update(cx, |pane, cx| {
13709            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13710            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13711            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13712            assert_eq!(
13713                pane.items()
13714                    .map(|item| item.item_id())
13715                    .sorted()
13716                    .collect::<Vec<_>>(),
13717                vec![
13718                    dirty_regular_buffer.item_id(),
13719                    dirty_regular_buffer_2.item_id(),
13720                ],
13721                "Should have no multi buffer left in the pane"
13722            );
13723            assert!(dirty_regular_buffer.read(cx).is_dirty);
13724            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13725        });
13726    }
13727
13728    #[gpui::test]
13729    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13730        init_test(cx);
13731        let fs = FakeFs::new(cx.executor());
13732        let project = Project::test(fs, [], cx).await;
13733        let (multi_workspace, cx) =
13734            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13735        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13736
13737        // Add a new panel to the right dock, opening the dock and setting the
13738        // focus to the new panel.
13739        let panel = workspace.update_in(cx, |workspace, window, cx| {
13740            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13741            workspace.add_panel(panel.clone(), window, cx);
13742
13743            workspace
13744                .right_dock()
13745                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13746
13747            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13748
13749            panel
13750        });
13751
13752        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13753        // panel to the next valid position which, in this case, is the left
13754        // dock.
13755        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13756        workspace.update(cx, |workspace, cx| {
13757            assert!(workspace.left_dock().read(cx).is_open());
13758            assert_eq!(panel.read(cx).position, DockPosition::Left);
13759        });
13760
13761        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13762        // panel to the next valid position which, in this case, is the bottom
13763        // dock.
13764        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13765        workspace.update(cx, |workspace, cx| {
13766            assert!(workspace.bottom_dock().read(cx).is_open());
13767            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13768        });
13769
13770        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13771        // around moving the panel to its initial position, the right dock.
13772        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13773        workspace.update(cx, |workspace, cx| {
13774            assert!(workspace.right_dock().read(cx).is_open());
13775            assert_eq!(panel.read(cx).position, DockPosition::Right);
13776        });
13777
13778        // Remove focus from the panel, ensuring that, if the panel is not
13779        // focused, the `MoveFocusedPanelToNextPosition` action does not update
13780        // the panel's position, so the panel is still in the right dock.
13781        workspace.update_in(cx, |workspace, window, cx| {
13782            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13783        });
13784
13785        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13786        workspace.update(cx, |workspace, cx| {
13787            assert!(workspace.right_dock().read(cx).is_open());
13788            assert_eq!(panel.read(cx).position, DockPosition::Right);
13789        });
13790    }
13791
13792    #[gpui::test]
13793    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13794        init_test(cx);
13795
13796        let fs = FakeFs::new(cx.executor());
13797        let project = Project::test(fs, [], cx).await;
13798        let (workspace, cx) =
13799            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13800
13801        let item_1 = cx.new(|cx| {
13802            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13803        });
13804        workspace.update_in(cx, |workspace, window, cx| {
13805            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13806            workspace.move_item_to_pane_in_direction(
13807                &MoveItemToPaneInDirection {
13808                    direction: SplitDirection::Right,
13809                    focus: true,
13810                    clone: false,
13811                },
13812                window,
13813                cx,
13814            );
13815            workspace.move_item_to_pane_at_index(
13816                &MoveItemToPane {
13817                    destination: 3,
13818                    focus: true,
13819                    clone: false,
13820                },
13821                window,
13822                cx,
13823            );
13824
13825            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13826            assert_eq!(
13827                pane_items_paths(&workspace.active_pane, cx),
13828                vec!["first.txt".to_string()],
13829                "Single item was not moved anywhere"
13830            );
13831        });
13832
13833        let item_2 = cx.new(|cx| {
13834            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13835        });
13836        workspace.update_in(cx, |workspace, window, cx| {
13837            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13838            assert_eq!(
13839                pane_items_paths(&workspace.panes[0], cx),
13840                vec!["first.txt".to_string(), "second.txt".to_string()],
13841            );
13842            workspace.move_item_to_pane_in_direction(
13843                &MoveItemToPaneInDirection {
13844                    direction: SplitDirection::Right,
13845                    focus: true,
13846                    clone: false,
13847                },
13848                window,
13849                cx,
13850            );
13851
13852            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13853            assert_eq!(
13854                pane_items_paths(&workspace.panes[0], cx),
13855                vec!["first.txt".to_string()],
13856                "After moving, one item should be left in the original pane"
13857            );
13858            assert_eq!(
13859                pane_items_paths(&workspace.panes[1], cx),
13860                vec!["second.txt".to_string()],
13861                "New item should have been moved to the new pane"
13862            );
13863        });
13864
13865        let item_3 = cx.new(|cx| {
13866            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13867        });
13868        workspace.update_in(cx, |workspace, window, cx| {
13869            let original_pane = workspace.panes[0].clone();
13870            workspace.set_active_pane(&original_pane, window, cx);
13871            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13872            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13873            assert_eq!(
13874                pane_items_paths(&workspace.active_pane, cx),
13875                vec!["first.txt".to_string(), "third.txt".to_string()],
13876                "New pane should be ready to move one item out"
13877            );
13878
13879            workspace.move_item_to_pane_at_index(
13880                &MoveItemToPane {
13881                    destination: 3,
13882                    focus: true,
13883                    clone: false,
13884                },
13885                window,
13886                cx,
13887            );
13888            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13889            assert_eq!(
13890                pane_items_paths(&workspace.active_pane, cx),
13891                vec!["first.txt".to_string()],
13892                "After moving, one item should be left in the original pane"
13893            );
13894            assert_eq!(
13895                pane_items_paths(&workspace.panes[1], cx),
13896                vec!["second.txt".to_string()],
13897                "Previously created pane should be unchanged"
13898            );
13899            assert_eq!(
13900                pane_items_paths(&workspace.panes[2], cx),
13901                vec!["third.txt".to_string()],
13902                "New item should have been moved to the new pane"
13903            );
13904        });
13905    }
13906
13907    #[gpui::test]
13908    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13909        init_test(cx);
13910
13911        let fs = FakeFs::new(cx.executor());
13912        let project = Project::test(fs, [], cx).await;
13913        let (workspace, cx) =
13914            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13915
13916        let item_1 = cx.new(|cx| {
13917            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13918        });
13919        workspace.update_in(cx, |workspace, window, cx| {
13920            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13921            workspace.move_item_to_pane_in_direction(
13922                &MoveItemToPaneInDirection {
13923                    direction: SplitDirection::Right,
13924                    focus: true,
13925                    clone: true,
13926                },
13927                window,
13928                cx,
13929            );
13930        });
13931        cx.run_until_parked();
13932        workspace.update_in(cx, |workspace, window, cx| {
13933            workspace.move_item_to_pane_at_index(
13934                &MoveItemToPane {
13935                    destination: 3,
13936                    focus: true,
13937                    clone: true,
13938                },
13939                window,
13940                cx,
13941            );
13942        });
13943        cx.run_until_parked();
13944
13945        workspace.update(cx, |workspace, cx| {
13946            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13947            for pane in workspace.panes() {
13948                assert_eq!(
13949                    pane_items_paths(pane, cx),
13950                    vec!["first.txt".to_string()],
13951                    "Single item exists in all panes"
13952                );
13953            }
13954        });
13955
13956        // verify that the active pane has been updated after waiting for the
13957        // pane focus event to fire and resolve
13958        workspace.read_with(cx, |workspace, _app| {
13959            assert_eq!(
13960                workspace.active_pane(),
13961                &workspace.panes[2],
13962                "The third pane should be the active one: {:?}",
13963                workspace.panes
13964            );
13965        })
13966    }
13967
13968    #[gpui::test]
13969    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13970        init_test(cx);
13971
13972        let fs = FakeFs::new(cx.executor());
13973        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13974
13975        let project = Project::test(fs, ["root".as_ref()], cx).await;
13976        let (workspace, cx) =
13977            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13978
13979        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13980        // Add item to pane A with project path
13981        let item_a = cx.new(|cx| {
13982            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13983        });
13984        workspace.update_in(cx, |workspace, window, cx| {
13985            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13986        });
13987
13988        // Split to create pane B
13989        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13990            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13991        });
13992
13993        // Add item with SAME project path to pane B, and pin it
13994        let item_b = cx.new(|cx| {
13995            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13996        });
13997        pane_b.update_in(cx, |pane, window, cx| {
13998            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13999            pane.set_pinned_count(1);
14000        });
14001
14002        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14003        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14004
14005        // close_pinned: false should only close the unpinned copy
14006        workspace.update_in(cx, |workspace, window, cx| {
14007            workspace.close_item_in_all_panes(
14008                &CloseItemInAllPanes {
14009                    save_intent: Some(SaveIntent::Close),
14010                    close_pinned: false,
14011                },
14012                window,
14013                cx,
14014            )
14015        });
14016        cx.executor().run_until_parked();
14017
14018        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14019        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14020        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14021        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14022
14023        // Split again, seeing as closing the previous item also closed its
14024        // pane, so only pane remains, which does not allow us to properly test
14025        // that both items close when `close_pinned: true`.
14026        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14027            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14028        });
14029
14030        // Add an item with the same project path to pane C so that
14031        // close_item_in_all_panes can determine what to close across all panes
14032        // (it reads the active item from the active pane, and split_pane
14033        // creates an empty pane).
14034        let item_c = cx.new(|cx| {
14035            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14036        });
14037        pane_c.update_in(cx, |pane, window, cx| {
14038            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14039        });
14040
14041        // close_pinned: true should close the pinned copy too
14042        workspace.update_in(cx, |workspace, window, cx| {
14043            let panes_count = workspace.panes().len();
14044            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14045
14046            workspace.close_item_in_all_panes(
14047                &CloseItemInAllPanes {
14048                    save_intent: Some(SaveIntent::Close),
14049                    close_pinned: true,
14050                },
14051                window,
14052                cx,
14053            )
14054        });
14055        cx.executor().run_until_parked();
14056
14057        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14058        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14059        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14060        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14061    }
14062
14063    mod register_project_item_tests {
14064
14065        use super::*;
14066
14067        // View
14068        struct TestPngItemView {
14069            focus_handle: FocusHandle,
14070        }
14071        // Model
14072        struct TestPngItem {}
14073
14074        impl project::ProjectItem for TestPngItem {
14075            fn try_open(
14076                _project: &Entity<Project>,
14077                path: &ProjectPath,
14078                cx: &mut App,
14079            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14080                if path.path.extension().unwrap() == "png" {
14081                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14082                } else {
14083                    None
14084                }
14085            }
14086
14087            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14088                None
14089            }
14090
14091            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14092                None
14093            }
14094
14095            fn is_dirty(&self) -> bool {
14096                false
14097            }
14098        }
14099
14100        impl Item for TestPngItemView {
14101            type Event = ();
14102            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14103                "".into()
14104            }
14105        }
14106        impl EventEmitter<()> for TestPngItemView {}
14107        impl Focusable for TestPngItemView {
14108            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14109                self.focus_handle.clone()
14110            }
14111        }
14112
14113        impl Render for TestPngItemView {
14114            fn render(
14115                &mut self,
14116                _window: &mut Window,
14117                _cx: &mut Context<Self>,
14118            ) -> impl IntoElement {
14119                Empty
14120            }
14121        }
14122
14123        impl ProjectItem for TestPngItemView {
14124            type Item = TestPngItem;
14125
14126            fn for_project_item(
14127                _project: Entity<Project>,
14128                _pane: Option<&Pane>,
14129                _item: Entity<Self::Item>,
14130                _: &mut Window,
14131                cx: &mut Context<Self>,
14132            ) -> Self
14133            where
14134                Self: Sized,
14135            {
14136                Self {
14137                    focus_handle: cx.focus_handle(),
14138                }
14139            }
14140        }
14141
14142        // View
14143        struct TestIpynbItemView {
14144            focus_handle: FocusHandle,
14145        }
14146        // Model
14147        struct TestIpynbItem {}
14148
14149        impl project::ProjectItem for TestIpynbItem {
14150            fn try_open(
14151                _project: &Entity<Project>,
14152                path: &ProjectPath,
14153                cx: &mut App,
14154            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14155                if path.path.extension().unwrap() == "ipynb" {
14156                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14157                } else {
14158                    None
14159                }
14160            }
14161
14162            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14163                None
14164            }
14165
14166            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14167                None
14168            }
14169
14170            fn is_dirty(&self) -> bool {
14171                false
14172            }
14173        }
14174
14175        impl Item for TestIpynbItemView {
14176            type Event = ();
14177            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14178                "".into()
14179            }
14180        }
14181        impl EventEmitter<()> for TestIpynbItemView {}
14182        impl Focusable for TestIpynbItemView {
14183            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14184                self.focus_handle.clone()
14185            }
14186        }
14187
14188        impl Render for TestIpynbItemView {
14189            fn render(
14190                &mut self,
14191                _window: &mut Window,
14192                _cx: &mut Context<Self>,
14193            ) -> impl IntoElement {
14194                Empty
14195            }
14196        }
14197
14198        impl ProjectItem for TestIpynbItemView {
14199            type Item = TestIpynbItem;
14200
14201            fn for_project_item(
14202                _project: Entity<Project>,
14203                _pane: Option<&Pane>,
14204                _item: Entity<Self::Item>,
14205                _: &mut Window,
14206                cx: &mut Context<Self>,
14207            ) -> Self
14208            where
14209                Self: Sized,
14210            {
14211                Self {
14212                    focus_handle: cx.focus_handle(),
14213                }
14214            }
14215        }
14216
14217        struct TestAlternatePngItemView {
14218            focus_handle: FocusHandle,
14219        }
14220
14221        impl Item for TestAlternatePngItemView {
14222            type Event = ();
14223            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14224                "".into()
14225            }
14226        }
14227
14228        impl EventEmitter<()> for TestAlternatePngItemView {}
14229        impl Focusable for TestAlternatePngItemView {
14230            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14231                self.focus_handle.clone()
14232            }
14233        }
14234
14235        impl Render for TestAlternatePngItemView {
14236            fn render(
14237                &mut self,
14238                _window: &mut Window,
14239                _cx: &mut Context<Self>,
14240            ) -> impl IntoElement {
14241                Empty
14242            }
14243        }
14244
14245        impl ProjectItem for TestAlternatePngItemView {
14246            type Item = TestPngItem;
14247
14248            fn for_project_item(
14249                _project: Entity<Project>,
14250                _pane: Option<&Pane>,
14251                _item: Entity<Self::Item>,
14252                _: &mut Window,
14253                cx: &mut Context<Self>,
14254            ) -> Self
14255            where
14256                Self: Sized,
14257            {
14258                Self {
14259                    focus_handle: cx.focus_handle(),
14260                }
14261            }
14262        }
14263
14264        #[gpui::test]
14265        async fn test_register_project_item(cx: &mut TestAppContext) {
14266            init_test(cx);
14267
14268            cx.update(|cx| {
14269                register_project_item::<TestPngItemView>(cx);
14270                register_project_item::<TestIpynbItemView>(cx);
14271            });
14272
14273            let fs = FakeFs::new(cx.executor());
14274            fs.insert_tree(
14275                "/root1",
14276                json!({
14277                    "one.png": "BINARYDATAHERE",
14278                    "two.ipynb": "{ totally a notebook }",
14279                    "three.txt": "editing text, sure why not?"
14280                }),
14281            )
14282            .await;
14283
14284            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14285            let (workspace, cx) =
14286                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14287
14288            let worktree_id = project.update(cx, |project, cx| {
14289                project.worktrees(cx).next().unwrap().read(cx).id()
14290            });
14291
14292            let handle = workspace
14293                .update_in(cx, |workspace, window, cx| {
14294                    let project_path = (worktree_id, rel_path("one.png"));
14295                    workspace.open_path(project_path, None, true, window, cx)
14296                })
14297                .await
14298                .unwrap();
14299
14300            // Now we can check if the handle we got back errored or not
14301            assert_eq!(
14302                handle.to_any_view().entity_type(),
14303                TypeId::of::<TestPngItemView>()
14304            );
14305
14306            let handle = workspace
14307                .update_in(cx, |workspace, window, cx| {
14308                    let project_path = (worktree_id, rel_path("two.ipynb"));
14309                    workspace.open_path(project_path, None, true, window, cx)
14310                })
14311                .await
14312                .unwrap();
14313
14314            assert_eq!(
14315                handle.to_any_view().entity_type(),
14316                TypeId::of::<TestIpynbItemView>()
14317            );
14318
14319            let handle = workspace
14320                .update_in(cx, |workspace, window, cx| {
14321                    let project_path = (worktree_id, rel_path("three.txt"));
14322                    workspace.open_path(project_path, None, true, window, cx)
14323                })
14324                .await;
14325            assert!(handle.is_err());
14326        }
14327
14328        #[gpui::test]
14329        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14330            init_test(cx);
14331
14332            cx.update(|cx| {
14333                register_project_item::<TestPngItemView>(cx);
14334                register_project_item::<TestAlternatePngItemView>(cx);
14335            });
14336
14337            let fs = FakeFs::new(cx.executor());
14338            fs.insert_tree(
14339                "/root1",
14340                json!({
14341                    "one.png": "BINARYDATAHERE",
14342                    "two.ipynb": "{ totally a notebook }",
14343                    "three.txt": "editing text, sure why not?"
14344                }),
14345            )
14346            .await;
14347            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14348            let (workspace, cx) =
14349                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14350            let worktree_id = project.update(cx, |project, cx| {
14351                project.worktrees(cx).next().unwrap().read(cx).id()
14352            });
14353
14354            let handle = workspace
14355                .update_in(cx, |workspace, window, cx| {
14356                    let project_path = (worktree_id, rel_path("one.png"));
14357                    workspace.open_path(project_path, None, true, window, cx)
14358                })
14359                .await
14360                .unwrap();
14361
14362            // This _must_ be the second item registered
14363            assert_eq!(
14364                handle.to_any_view().entity_type(),
14365                TypeId::of::<TestAlternatePngItemView>()
14366            );
14367
14368            let handle = workspace
14369                .update_in(cx, |workspace, window, cx| {
14370                    let project_path = (worktree_id, rel_path("three.txt"));
14371                    workspace.open_path(project_path, None, true, window, cx)
14372                })
14373                .await;
14374            assert!(handle.is_err());
14375        }
14376    }
14377
14378    #[gpui::test]
14379    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14380        init_test(cx);
14381
14382        let fs = FakeFs::new(cx.executor());
14383        let project = Project::test(fs, [], cx).await;
14384        let (workspace, _cx) =
14385            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14386
14387        // Test with status bar shown (default)
14388        workspace.read_with(cx, |workspace, cx| {
14389            let visible = workspace.status_bar_visible(cx);
14390            assert!(visible, "Status bar should be visible by default");
14391        });
14392
14393        // Test with status bar hidden
14394        cx.update_global(|store: &mut SettingsStore, cx| {
14395            store.update_user_settings(cx, |settings| {
14396                settings.status_bar.get_or_insert_default().show = Some(false);
14397            });
14398        });
14399
14400        workspace.read_with(cx, |workspace, cx| {
14401            let visible = workspace.status_bar_visible(cx);
14402            assert!(!visible, "Status bar should be hidden when show is false");
14403        });
14404
14405        // Test with status bar shown explicitly
14406        cx.update_global(|store: &mut SettingsStore, cx| {
14407            store.update_user_settings(cx, |settings| {
14408                settings.status_bar.get_or_insert_default().show = Some(true);
14409            });
14410        });
14411
14412        workspace.read_with(cx, |workspace, cx| {
14413            let visible = workspace.status_bar_visible(cx);
14414            assert!(visible, "Status bar should be visible when show is true");
14415        });
14416    }
14417
14418    #[gpui::test]
14419    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14420        init_test(cx);
14421
14422        let fs = FakeFs::new(cx.executor());
14423        let project = Project::test(fs, [], cx).await;
14424        let (multi_workspace, cx) =
14425            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14426        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14427        let panel = workspace.update_in(cx, |workspace, window, cx| {
14428            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14429            workspace.add_panel(panel.clone(), window, cx);
14430
14431            workspace
14432                .right_dock()
14433                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14434
14435            panel
14436        });
14437
14438        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14439        let item_a = cx.new(TestItem::new);
14440        let item_b = cx.new(TestItem::new);
14441        let item_a_id = item_a.entity_id();
14442        let item_b_id = item_b.entity_id();
14443
14444        pane.update_in(cx, |pane, window, cx| {
14445            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14446            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14447        });
14448
14449        pane.read_with(cx, |pane, _| {
14450            assert_eq!(pane.items_len(), 2);
14451            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14452        });
14453
14454        workspace.update_in(cx, |workspace, window, cx| {
14455            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14456        });
14457
14458        workspace.update_in(cx, |_, window, cx| {
14459            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14460        });
14461
14462        // Assert that the `pane::CloseActiveItem` action is handled at the
14463        // workspace level when one of the dock panels is focused and, in that
14464        // case, the center pane's active item is closed but the focus is not
14465        // moved.
14466        cx.dispatch_action(pane::CloseActiveItem::default());
14467        cx.run_until_parked();
14468
14469        pane.read_with(cx, |pane, _| {
14470            assert_eq!(pane.items_len(), 1);
14471            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14472        });
14473
14474        workspace.update_in(cx, |workspace, window, cx| {
14475            assert!(workspace.right_dock().read(cx).is_open());
14476            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14477        });
14478    }
14479
14480    #[gpui::test]
14481    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14482        init_test(cx);
14483        let fs = FakeFs::new(cx.executor());
14484
14485        let project_a = Project::test(fs.clone(), [], cx).await;
14486        let project_b = Project::test(fs, [], cx).await;
14487
14488        let multi_workspace_handle =
14489            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14490        cx.run_until_parked();
14491
14492        let workspace_a = multi_workspace_handle
14493            .read_with(cx, |mw, _| mw.workspace().clone())
14494            .unwrap();
14495
14496        let _workspace_b = multi_workspace_handle
14497            .update(cx, |mw, window, cx| {
14498                mw.test_add_workspace(project_b, window, cx)
14499            })
14500            .unwrap();
14501
14502        // Switch to workspace A
14503        multi_workspace_handle
14504            .update(cx, |mw, window, cx| {
14505                let workspace = mw.workspaces()[0].clone();
14506                mw.activate(workspace, window, cx);
14507            })
14508            .unwrap();
14509
14510        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14511
14512        // Add a panel to workspace A's right dock and open the dock
14513        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14514            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14515            workspace.add_panel(panel.clone(), window, cx);
14516            workspace
14517                .right_dock()
14518                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14519            panel
14520        });
14521
14522        // Focus the panel through the workspace (matching existing test pattern)
14523        workspace_a.update_in(cx, |workspace, window, cx| {
14524            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14525        });
14526
14527        // Zoom the panel
14528        panel.update_in(cx, |panel, window, cx| {
14529            panel.set_zoomed(true, window, cx);
14530        });
14531
14532        // Verify the panel is zoomed and the dock is open
14533        workspace_a.update_in(cx, |workspace, window, cx| {
14534            assert!(
14535                workspace.right_dock().read(cx).is_open(),
14536                "dock should be open before switch"
14537            );
14538            assert!(
14539                panel.is_zoomed(window, cx),
14540                "panel should be zoomed before switch"
14541            );
14542            assert!(
14543                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14544                "panel should be focused before switch"
14545            );
14546        });
14547
14548        // Switch to workspace B
14549        multi_workspace_handle
14550            .update(cx, |mw, window, cx| {
14551                let workspace = mw.workspaces()[1].clone();
14552                mw.activate(workspace, window, cx);
14553            })
14554            .unwrap();
14555        cx.run_until_parked();
14556
14557        // Switch back to workspace A
14558        multi_workspace_handle
14559            .update(cx, |mw, window, cx| {
14560                let workspace = mw.workspaces()[0].clone();
14561                mw.activate(workspace, window, cx);
14562            })
14563            .unwrap();
14564        cx.run_until_parked();
14565
14566        // Verify the panel is still zoomed and the dock is still open
14567        workspace_a.update_in(cx, |workspace, window, cx| {
14568            assert!(
14569                workspace.right_dock().read(cx).is_open(),
14570                "dock should still be open after switching back"
14571            );
14572            assert!(
14573                panel.is_zoomed(window, cx),
14574                "panel should still be zoomed after switching back"
14575            );
14576        });
14577    }
14578
14579    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14580        pane.read(cx)
14581            .items()
14582            .flat_map(|item| {
14583                item.project_paths(cx)
14584                    .into_iter()
14585                    .map(|path| path.path.display(PathStyle::local()).into_owned())
14586            })
14587            .collect()
14588    }
14589
14590    pub fn init_test(cx: &mut TestAppContext) {
14591        cx.update(|cx| {
14592            let settings_store = SettingsStore::test(cx);
14593            cx.set_global(settings_store);
14594            cx.set_global(db::AppDatabase::test_new());
14595            theme_settings::init(theme::LoadThemes::JustBase, cx);
14596        });
14597    }
14598
14599    #[gpui::test]
14600    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14601        use settings::{ThemeName, ThemeSelection};
14602        use theme::SystemAppearance;
14603        use zed_actions::theme::ToggleMode;
14604
14605        init_test(cx);
14606
14607        let fs = FakeFs::new(cx.executor());
14608        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14609
14610        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14611            .await;
14612
14613        // Build a test project and workspace view so the test can invoke
14614        // the workspace action handler the same way the UI would.
14615        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14616        let (workspace, cx) =
14617            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14618
14619        // Seed the settings file with a plain static light theme so the
14620        // first toggle always starts from a known persisted state.
14621        workspace.update_in(cx, |_workspace, _window, cx| {
14622            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14623            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14624                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14625            });
14626        });
14627        cx.executor().advance_clock(Duration::from_millis(200));
14628        cx.run_until_parked();
14629
14630        // Confirm the initial persisted settings contain the static theme
14631        // we just wrote before any toggling happens.
14632        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14633        assert!(settings_text.contains(r#""theme": "One Light""#));
14634
14635        // Toggle once. This should migrate the persisted theme settings
14636        // into light/dark slots and enable system mode.
14637        workspace.update_in(cx, |workspace, window, cx| {
14638            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14639        });
14640        cx.executor().advance_clock(Duration::from_millis(200));
14641        cx.run_until_parked();
14642
14643        // 1. Static -> Dynamic
14644        // this assertion checks theme changed from static to dynamic.
14645        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14646        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14647        assert_eq!(
14648            parsed["theme"],
14649            serde_json::json!({
14650                "mode": "system",
14651                "light": "One Light",
14652                "dark": "One Dark"
14653            })
14654        );
14655
14656        // 2. Toggle again, suppose it will change the mode to light
14657        workspace.update_in(cx, |workspace, window, cx| {
14658            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14659        });
14660        cx.executor().advance_clock(Duration::from_millis(200));
14661        cx.run_until_parked();
14662
14663        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14664        assert!(settings_text.contains(r#""mode": "light""#));
14665    }
14666
14667    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14668        let item = TestProjectItem::new(id, path, cx);
14669        item.update(cx, |item, _| {
14670            item.is_dirty = true;
14671        });
14672        item
14673    }
14674
14675    #[gpui::test]
14676    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14677        cx: &mut gpui::TestAppContext,
14678    ) {
14679        init_test(cx);
14680        let fs = FakeFs::new(cx.executor());
14681
14682        let project = Project::test(fs, [], cx).await;
14683        let (workspace, cx) =
14684            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14685
14686        let panel = workspace.update_in(cx, |workspace, window, cx| {
14687            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14688            workspace.add_panel(panel.clone(), window, cx);
14689            workspace
14690                .right_dock()
14691                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14692            panel
14693        });
14694
14695        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14696        pane.update_in(cx, |pane, window, cx| {
14697            let item = cx.new(TestItem::new);
14698            pane.add_item(Box::new(item), true, true, None, window, cx);
14699        });
14700
14701        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14702        // mirrors the real-world flow and avoids side effects from directly
14703        // focusing the panel while the center pane is active.
14704        workspace.update_in(cx, |workspace, window, cx| {
14705            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14706        });
14707
14708        panel.update_in(cx, |panel, window, cx| {
14709            panel.set_zoomed(true, window, cx);
14710        });
14711
14712        workspace.update_in(cx, |workspace, window, cx| {
14713            assert!(workspace.right_dock().read(cx).is_open());
14714            assert!(panel.is_zoomed(window, cx));
14715            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14716        });
14717
14718        // Simulate a spurious pane::Event::Focus on the center pane while the
14719        // panel still has focus. This mirrors what happens during macOS window
14720        // activation: the center pane fires a focus event even though actual
14721        // focus remains on the dock panel.
14722        pane.update_in(cx, |_, _, cx| {
14723            cx.emit(pane::Event::Focus);
14724        });
14725
14726        // The dock must remain open because the panel had focus at the time the
14727        // event was processed. Before the fix, dock_to_preserve was None for
14728        // panels that don't implement pane(), causing the dock to close.
14729        workspace.update_in(cx, |workspace, window, cx| {
14730            assert!(
14731                workspace.right_dock().read(cx).is_open(),
14732                "Dock should stay open when its zoomed panel (without pane()) still has focus"
14733            );
14734            assert!(panel.is_zoomed(window, cx));
14735        });
14736    }
14737
14738    #[gpui::test]
14739    async fn test_panels_stay_open_after_position_change_and_settings_update(
14740        cx: &mut gpui::TestAppContext,
14741    ) {
14742        init_test(cx);
14743        let fs = FakeFs::new(cx.executor());
14744        let project = Project::test(fs, [], cx).await;
14745        let (workspace, cx) =
14746            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14747
14748        // Add two panels to the left dock and open it.
14749        let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14750            let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14751            let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14752            workspace.add_panel(panel_a.clone(), window, cx);
14753            workspace.add_panel(panel_b.clone(), window, cx);
14754            workspace.left_dock().update(cx, |dock, cx| {
14755                dock.set_open(true, window, cx);
14756                dock.activate_panel(0, window, cx);
14757            });
14758            (panel_a, panel_b)
14759        });
14760
14761        workspace.update_in(cx, |workspace, _, cx| {
14762            assert!(workspace.left_dock().read(cx).is_open());
14763        });
14764
14765        // Simulate a feature flag changing default dock positions: both panels
14766        // move from Left to Right.
14767        workspace.update_in(cx, |_workspace, _window, cx| {
14768            panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14769            panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14770            cx.update_global::<SettingsStore, _>(|_, _| {});
14771        });
14772
14773        // Both panels should now be in the right dock.
14774        workspace.update_in(cx, |workspace, _, cx| {
14775            let right_dock = workspace.right_dock().read(cx);
14776            assert_eq!(right_dock.panels_len(), 2);
14777        });
14778
14779        // Open the right dock and activate panel_b (simulating the user
14780        // opening the panel after it moved).
14781        workspace.update_in(cx, |workspace, window, cx| {
14782            workspace.right_dock().update(cx, |dock, cx| {
14783                dock.set_open(true, window, cx);
14784                dock.activate_panel(1, window, cx);
14785            });
14786        });
14787
14788        // Now trigger another SettingsStore change
14789        workspace.update_in(cx, |_workspace, _window, cx| {
14790            cx.update_global::<SettingsStore, _>(|_, _| {});
14791        });
14792
14793        workspace.update_in(cx, |workspace, _, cx| {
14794            assert!(
14795                workspace.right_dock().read(cx).is_open(),
14796                "Right dock should still be open after a settings change"
14797            );
14798            assert_eq!(
14799                workspace.right_dock().read(cx).panels_len(),
14800                2,
14801                "Both panels should still be in the right dock"
14802            );
14803        });
14804    }
14805}