workspace.rs

    1pub mod active_file_name;
    2pub mod dock;
    3pub mod history_manager;
    4pub mod invalid_item_view;
    5pub mod item;
    6mod modal_layer;
    7mod multi_workspace;
    8#[cfg(test)]
    9mod multi_workspace_tests;
   10pub mod notifications;
   11pub mod pane;
   12pub mod pane_group;
   13pub mod path_list {
   14    pub use util::path_list::{PathList, SerializedPathList};
   15}
   16mod persistence;
   17pub mod searchable;
   18mod security_modal;
   19pub mod shared_screen;
   20use db::smol::future::yield_now;
   21pub use shared_screen::SharedScreen;
   22pub mod focus_follows_mouse;
   23mod status_bar;
   24pub mod tasks;
   25mod theme_preview;
   26mod toast_layer;
   27mod toolbar;
   28pub mod welcome;
   29mod workspace_settings;
   30
   31pub use crate::notifications::NotificationFrame;
   32pub use dock::Panel;
   33pub use multi_workspace::{
   34    CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
   35    MultiWorkspaceEvent, NextWorkspace, PreviousWorkspace, Sidebar, SidebarEvent, SidebarHandle,
   36    SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar, sidebar_side_context_menu,
   37};
   38pub use path_list::{PathList, SerializedPathList};
   39pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   40
   41use anyhow::{Context as _, Result, anyhow};
   42use client::{
   43    ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
   44    proto::{self, ErrorCode, PanelId, PeerId},
   45};
   46use collections::{HashMap, HashSet, hash_map};
   47use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   48use fs::Fs;
   49use futures::{
   50    Future, FutureExt, StreamExt,
   51    channel::{
   52        mpsc::{self, UnboundedReceiver, UnboundedSender},
   53        oneshot,
   54    },
   55    future::{Shared, try_join_all},
   56};
   57use gpui::{
   58    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
   59    Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   60    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   61    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   62    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   63    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   64};
   65pub use history_manager::*;
   66pub use item::{
   67    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   68    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   69};
   70use itertools::Itertools;
   71use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   72pub use modal_layer::*;
   73use node_runtime::NodeRuntime;
   74use notifications::{
   75    DetachAndPromptErr, Notifications, dismiss_app_notification,
   76    simple_message_notification::MessageNotification,
   77};
   78pub use pane::*;
   79pub use pane_group::{
   80    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   81    SplitDirection,
   82};
   83use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
   84pub use persistence::{
   85    WorkspaceDb, delete_unloaded_items,
   86    model::{
   87        DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
   88        SessionWorkspace,
   89    },
   90    read_serialized_multi_workspaces, resolve_worktree_workspaces,
   91};
   92use postage::stream::Stream;
   93use project::{
   94    DirectoryLister, Project, ProjectEntryId, ProjectGroupKey, ProjectPath, ResolvedPath, Worktree,
   95    WorktreeId, WorktreeSettings,
   96    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   97    project_settings::ProjectSettings,
   98    toolchain_store::ToolchainStoreEvent,
   99    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
  100};
  101use remote::{
  102    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
  103    remote_client::ConnectionIdentifier,
  104};
  105use schemars::JsonSchema;
  106use serde::Deserialize;
  107use session::AppSession;
  108use settings::{
  109    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  110};
  111
  112use sqlez::{
  113    bindable::{Bind, Column, StaticColumnCount},
  114    statement::Statement,
  115};
  116use status_bar::StatusBar;
  117pub use status_bar::StatusItemView;
  118use std::{
  119    any::TypeId,
  120    borrow::Cow,
  121    cell::RefCell,
  122    cmp,
  123    collections::VecDeque,
  124    env,
  125    hash::Hash,
  126    path::{Path, PathBuf},
  127    process::ExitStatus,
  128    rc::Rc,
  129    sync::{
  130        Arc, LazyLock,
  131        atomic::{AtomicBool, AtomicUsize},
  132    },
  133    time::Duration,
  134};
  135use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  136use theme::{ActiveTheme, SystemAppearance};
  137use theme_settings::ThemeSettings;
  138pub use toolbar::{
  139    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  140};
  141pub use ui;
  142use ui::{Window, prelude::*};
  143use util::{
  144    ResultExt, TryFutureExt,
  145    paths::{PathStyle, SanitizedPath},
  146    rel_path::RelPath,
  147    serde::default_true,
  148};
  149use uuid::Uuid;
  150pub use workspace_settings::{
  151    AutosaveSetting, BottomDockLayout, FocusFollowsMouse, RestoreOnStartupBehavior,
  152    StatusBarSettings, TabBarSettings, WorkspaceSettings,
  153};
  154use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
  155
  156use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::NotificationId};
  157use crate::{
  158    persistence::{
  159        SerializedAxis,
  160        model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
  161    },
  162    security_modal::SecurityModal,
  163};
  164
  165pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  166
  167static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  168    env::var("ZED_WINDOW_SIZE")
  169        .ok()
  170        .as_deref()
  171        .and_then(parse_pixel_size_env_var)
  172});
  173
  174static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  175    env::var("ZED_WINDOW_POSITION")
  176        .ok()
  177        .as_deref()
  178        .and_then(parse_pixel_position_env_var)
  179});
  180
  181pub trait TerminalProvider {
  182    fn spawn(
  183        &self,
  184        task: SpawnInTerminal,
  185        window: &mut Window,
  186        cx: &mut App,
  187    ) -> Task<Option<Result<ExitStatus>>>;
  188}
  189
  190pub trait DebuggerProvider {
  191    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  192    fn start_session(
  193        &self,
  194        definition: DebugScenario,
  195        task_context: SharedTaskContext,
  196        active_buffer: Option<Entity<Buffer>>,
  197        worktree_id: Option<WorktreeId>,
  198        window: &mut Window,
  199        cx: &mut App,
  200    );
  201
  202    fn spawn_task_or_modal(
  203        &self,
  204        workspace: &mut Workspace,
  205        action: &Spawn,
  206        window: &mut Window,
  207        cx: &mut Context<Workspace>,
  208    );
  209
  210    fn task_scheduled(&self, cx: &mut App);
  211    fn debug_scenario_scheduled(&self, cx: &mut App);
  212    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  213
  214    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  215}
  216
  217/// Opens a file or directory.
  218#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  219#[action(namespace = workspace)]
  220pub struct Open {
  221    /// When true, opens in a new window. When false, adds to the current
  222    /// window as a new workspace (multi-workspace).
  223    #[serde(default = "Open::default_create_new_window")]
  224    pub create_new_window: bool,
  225}
  226
  227impl Open {
  228    pub const DEFAULT: Self = Self {
  229        create_new_window: true,
  230    };
  231
  232    /// Used by `#[serde(default)]` on the `create_new_window` field so that
  233    /// the serde default and `Open::DEFAULT` stay in sync.
  234    fn default_create_new_window() -> bool {
  235        Self::DEFAULT.create_new_window
  236    }
  237}
  238
  239impl Default for Open {
  240    fn default() -> Self {
  241        Self::DEFAULT
  242    }
  243}
  244
  245actions!(
  246    workspace,
  247    [
  248        /// Activates the next pane in the workspace.
  249        ActivateNextPane,
  250        /// Activates the previous pane in the workspace.
  251        ActivatePreviousPane,
  252        /// Activates the last pane in the workspace.
  253        ActivateLastPane,
  254        /// Switches to the next window.
  255        ActivateNextWindow,
  256        /// Switches to the previous window.
  257        ActivatePreviousWindow,
  258        /// Adds a folder to the current project.
  259        AddFolderToProject,
  260        /// Clears all notifications.
  261        ClearAllNotifications,
  262        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  263        ClearNavigationHistory,
  264        /// Closes the active dock.
  265        CloseActiveDock,
  266        /// Closes all docks.
  267        CloseAllDocks,
  268        /// Toggles all docks.
  269        ToggleAllDocks,
  270        /// Closes the current window.
  271        CloseWindow,
  272        /// Closes the current project.
  273        CloseProject,
  274        /// Opens the feedback dialog.
  275        Feedback,
  276        /// Follows the next collaborator in the session.
  277        FollowNextCollaborator,
  278        /// Moves the focused panel to the next position.
  279        MoveFocusedPanelToNextPosition,
  280        /// Creates a new file.
  281        NewFile,
  282        /// Creates a new file in a vertical split.
  283        NewFileSplitVertical,
  284        /// Creates a new file in a horizontal split.
  285        NewFileSplitHorizontal,
  286        /// Opens a new search.
  287        NewSearch,
  288        /// Opens a new window.
  289        NewWindow,
  290        /// Opens multiple files.
  291        OpenFiles,
  292        /// Opens the current location in terminal.
  293        OpenInTerminal,
  294        /// Opens the component preview.
  295        OpenComponentPreview,
  296        /// Reloads the active item.
  297        ReloadActiveItem,
  298        /// Resets the active dock to its default size.
  299        ResetActiveDockSize,
  300        /// Resets all open docks to their default sizes.
  301        ResetOpenDocksSize,
  302        /// Reloads the application
  303        Reload,
  304        /// Saves the current file with a new name.
  305        SaveAs,
  306        /// Saves without formatting.
  307        SaveWithoutFormat,
  308        /// Shuts down all debug adapters.
  309        ShutdownDebugAdapters,
  310        /// Suppresses the current notification.
  311        SuppressNotification,
  312        /// Toggles the bottom dock.
  313        ToggleBottomDock,
  314        /// Toggles centered layout mode.
  315        ToggleCenteredLayout,
  316        /// Toggles edit prediction feature globally for all files.
  317        ToggleEditPrediction,
  318        /// Toggles the left dock.
  319        ToggleLeftDock,
  320        /// Toggles the right dock.
  321        ToggleRightDock,
  322        /// Toggles zoom on the active pane.
  323        ToggleZoom,
  324        /// Toggles read-only mode for the active item (if supported by that item).
  325        ToggleReadOnlyFile,
  326        /// Zooms in on the active pane.
  327        ZoomIn,
  328        /// Zooms out of the active pane.
  329        ZoomOut,
  330        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  331        /// If the modal is shown already, closes it without trusting any worktree.
  332        ToggleWorktreeSecurity,
  333        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  334        /// Requires restart to take effect on already opened projects.
  335        ClearTrustedWorktrees,
  336        /// Stops following a collaborator.
  337        Unfollow,
  338        /// Restores the banner.
  339        RestoreBanner,
  340        /// Toggles expansion of the selected item.
  341        ToggleExpandItem,
  342    ]
  343);
  344
  345/// Activates a specific pane by its index.
  346#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  347#[action(namespace = workspace)]
  348pub struct ActivatePane(pub usize);
  349
  350/// Moves an item to a specific pane by index.
  351#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  352#[action(namespace = workspace)]
  353#[serde(deny_unknown_fields)]
  354pub struct MoveItemToPane {
  355    #[serde(default = "default_1")]
  356    pub destination: usize,
  357    #[serde(default = "default_true")]
  358    pub focus: bool,
  359    #[serde(default)]
  360    pub clone: bool,
  361}
  362
  363fn default_1() -> usize {
  364    1
  365}
  366
  367/// Moves an item to a pane in the specified direction.
  368#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  369#[action(namespace = workspace)]
  370#[serde(deny_unknown_fields)]
  371pub struct MoveItemToPaneInDirection {
  372    #[serde(default = "default_right")]
  373    pub direction: SplitDirection,
  374    #[serde(default = "default_true")]
  375    pub focus: bool,
  376    #[serde(default)]
  377    pub clone: bool,
  378}
  379
  380/// Creates a new file in a split of the desired direction.
  381#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  382#[action(namespace = workspace)]
  383#[serde(deny_unknown_fields)]
  384pub struct NewFileSplit(pub SplitDirection);
  385
  386fn default_right() -> SplitDirection {
  387    SplitDirection::Right
  388}
  389
  390/// Saves all open files in the workspace.
  391#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  392#[action(namespace = workspace)]
  393#[serde(deny_unknown_fields)]
  394pub struct SaveAll {
  395    #[serde(default)]
  396    pub save_intent: Option<SaveIntent>,
  397}
  398
  399/// Saves the current file with the specified options.
  400#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  401#[action(namespace = workspace)]
  402#[serde(deny_unknown_fields)]
  403pub struct Save {
  404    #[serde(default)]
  405    pub save_intent: Option<SaveIntent>,
  406}
  407
  408/// Moves Focus to the central panes in the workspace.
  409#[derive(Clone, Debug, PartialEq, Eq, Action)]
  410#[action(namespace = workspace)]
  411pub struct FocusCenterPane;
  412
  413///  Closes all items and panes in the workspace.
  414#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  415#[action(namespace = workspace)]
  416#[serde(deny_unknown_fields)]
  417pub struct CloseAllItemsAndPanes {
  418    #[serde(default)]
  419    pub save_intent: Option<SaveIntent>,
  420}
  421
  422/// Closes all inactive tabs and panes in the workspace.
  423#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  424#[action(namespace = workspace)]
  425#[serde(deny_unknown_fields)]
  426pub struct CloseInactiveTabsAndPanes {
  427    #[serde(default)]
  428    pub save_intent: Option<SaveIntent>,
  429}
  430
  431/// Closes the active item across all panes.
  432#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  433#[action(namespace = workspace)]
  434#[serde(deny_unknown_fields)]
  435pub struct CloseItemInAllPanes {
  436    #[serde(default)]
  437    pub save_intent: Option<SaveIntent>,
  438    #[serde(default)]
  439    pub close_pinned: bool,
  440}
  441
  442/// Sends a sequence of keystrokes to the active element.
  443#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  444#[action(namespace = workspace)]
  445pub struct SendKeystrokes(pub String);
  446
  447actions!(
  448    project_symbols,
  449    [
  450        /// Toggles the project symbols search.
  451        #[action(name = "Toggle")]
  452        ToggleProjectSymbols
  453    ]
  454);
  455
  456/// Toggles the file finder interface.
  457#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  458#[action(namespace = file_finder, name = "Toggle")]
  459#[serde(deny_unknown_fields)]
  460pub struct ToggleFileFinder {
  461    #[serde(default)]
  462    pub separate_history: bool,
  463}
  464
  465/// Opens a new terminal in the center.
  466#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  467#[action(namespace = workspace)]
  468#[serde(deny_unknown_fields)]
  469pub struct NewCenterTerminal {
  470    /// If true, creates a local terminal even in remote projects.
  471    #[serde(default)]
  472    pub local: bool,
  473}
  474
  475/// Opens a new terminal.
  476#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  477#[action(namespace = workspace)]
  478#[serde(deny_unknown_fields)]
  479pub struct NewTerminal {
  480    /// If true, creates a local terminal even in remote projects.
  481    #[serde(default)]
  482    pub local: bool,
  483}
  484
  485/// Increases size of a currently focused dock by a given amount of pixels.
  486#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  487#[action(namespace = workspace)]
  488#[serde(deny_unknown_fields)]
  489pub struct IncreaseActiveDockSize {
  490    /// For 0px parameter, uses UI font size value.
  491    #[serde(default)]
  492    pub px: u32,
  493}
  494
  495/// Decreases size of a currently focused dock by a given amount of pixels.
  496#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  497#[action(namespace = workspace)]
  498#[serde(deny_unknown_fields)]
  499pub struct DecreaseActiveDockSize {
  500    /// For 0px parameter, uses UI font size value.
  501    #[serde(default)]
  502    pub px: u32,
  503}
  504
  505/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  506#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  507#[action(namespace = workspace)]
  508#[serde(deny_unknown_fields)]
  509pub struct IncreaseOpenDocksSize {
  510    /// For 0px parameter, uses UI font size value.
  511    #[serde(default)]
  512    pub px: u32,
  513}
  514
  515/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  516#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  517#[action(namespace = workspace)]
  518#[serde(deny_unknown_fields)]
  519pub struct DecreaseOpenDocksSize {
  520    /// For 0px parameter, uses UI font size value.
  521    #[serde(default)]
  522    pub px: u32,
  523}
  524
  525actions!(
  526    workspace,
  527    [
  528        /// Activates the pane to the left.
  529        ActivatePaneLeft,
  530        /// Activates the pane to the right.
  531        ActivatePaneRight,
  532        /// Activates the pane above.
  533        ActivatePaneUp,
  534        /// Activates the pane below.
  535        ActivatePaneDown,
  536        /// Swaps the current pane with the one to the left.
  537        SwapPaneLeft,
  538        /// Swaps the current pane with the one to the right.
  539        SwapPaneRight,
  540        /// Swaps the current pane with the one above.
  541        SwapPaneUp,
  542        /// Swaps the current pane with the one below.
  543        SwapPaneDown,
  544        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  545        SwapPaneAdjacent,
  546        /// Move the current pane to be at the far left.
  547        MovePaneLeft,
  548        /// Move the current pane to be at the far right.
  549        MovePaneRight,
  550        /// Move the current pane to be at the very top.
  551        MovePaneUp,
  552        /// Move the current pane to be at the very bottom.
  553        MovePaneDown,
  554    ]
  555);
  556
  557#[derive(PartialEq, Eq, Debug)]
  558pub enum CloseIntent {
  559    /// Quit the program entirely.
  560    Quit,
  561    /// Close a window.
  562    CloseWindow,
  563    /// Replace the workspace in an existing window.
  564    ReplaceWindow,
  565}
  566
  567#[derive(Clone)]
  568pub struct Toast {
  569    id: NotificationId,
  570    msg: Cow<'static, str>,
  571    autohide: bool,
  572    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  573}
  574
  575impl Toast {
  576    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  577        Toast {
  578            id,
  579            msg: msg.into(),
  580            on_click: None,
  581            autohide: false,
  582        }
  583    }
  584
  585    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  586    where
  587        M: Into<Cow<'static, str>>,
  588        F: Fn(&mut Window, &mut App) + 'static,
  589    {
  590        self.on_click = Some((message.into(), Arc::new(on_click)));
  591        self
  592    }
  593
  594    pub fn autohide(mut self) -> Self {
  595        self.autohide = true;
  596        self
  597    }
  598}
  599
  600impl PartialEq for Toast {
  601    fn eq(&self, other: &Self) -> bool {
  602        self.id == other.id
  603            && self.msg == other.msg
  604            && self.on_click.is_some() == other.on_click.is_some()
  605    }
  606}
  607
  608/// Opens a new terminal with the specified working directory.
  609#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  610#[action(namespace = workspace)]
  611#[serde(deny_unknown_fields)]
  612pub struct OpenTerminal {
  613    pub working_directory: PathBuf,
  614    /// If true, creates a local terminal even in remote projects.
  615    #[serde(default)]
  616    pub local: bool,
  617}
  618
  619#[derive(
  620    Clone,
  621    Copy,
  622    Debug,
  623    Default,
  624    Hash,
  625    PartialEq,
  626    Eq,
  627    PartialOrd,
  628    Ord,
  629    serde::Serialize,
  630    serde::Deserialize,
  631)]
  632pub struct WorkspaceId(i64);
  633
  634impl WorkspaceId {
  635    pub fn from_i64(value: i64) -> Self {
  636        Self(value)
  637    }
  638}
  639
  640impl StaticColumnCount for WorkspaceId {}
  641impl Bind for WorkspaceId {
  642    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  643        self.0.bind(statement, start_index)
  644    }
  645}
  646impl Column for WorkspaceId {
  647    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  648        i64::column(statement, start_index)
  649            .map(|(i, next_index)| (Self(i), next_index))
  650            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  651    }
  652}
  653impl From<WorkspaceId> for i64 {
  654    fn from(val: WorkspaceId) -> Self {
  655        val.0
  656    }
  657}
  658
  659fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
  660    if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
  661        workspace_window
  662            .update(cx, |multi_workspace, window, cx| {
  663                let workspace = multi_workspace.workspace().clone();
  664                workspace.update(cx, |workspace, cx| {
  665                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  666                });
  667            })
  668            .ok();
  669    } else {
  670        let task = Workspace::new_local(
  671            Vec::new(),
  672            app_state.clone(),
  673            None,
  674            None,
  675            None,
  676            OpenMode::Activate,
  677            cx,
  678        );
  679        cx.spawn(async move |cx| {
  680            let OpenResult { window, .. } = task.await?;
  681            window.update(cx, |multi_workspace, window, cx| {
  682                window.activate_window();
  683                let workspace = multi_workspace.workspace().clone();
  684                workspace.update(cx, |workspace, cx| {
  685                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  686                });
  687            })?;
  688            anyhow::Ok(())
  689        })
  690        .detach_and_log_err(cx);
  691    }
  692}
  693
  694pub fn prompt_for_open_path_and_open(
  695    workspace: &mut Workspace,
  696    app_state: Arc<AppState>,
  697    options: PathPromptOptions,
  698    create_new_window: bool,
  699    window: &mut Window,
  700    cx: &mut Context<Workspace>,
  701) {
  702    let paths = workspace.prompt_for_open_path(
  703        options,
  704        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  705        window,
  706        cx,
  707    );
  708    let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
  709    cx.spawn_in(window, async move |this, cx| {
  710        let Some(paths) = paths.await.log_err().flatten() else {
  711            return;
  712        };
  713        if !create_new_window {
  714            if let Some(handle) = multi_workspace_handle {
  715                if let Some(task) = handle
  716                    .update(cx, |multi_workspace, window, cx| {
  717                        multi_workspace.open_project(paths, OpenMode::Activate, window, cx)
  718                    })
  719                    .log_err()
  720                {
  721                    task.await.log_err();
  722                }
  723                return;
  724            }
  725        }
  726        if let Some(task) = this
  727            .update_in(cx, |this, window, cx| {
  728                this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
  729            })
  730            .log_err()
  731        {
  732            task.await.log_err();
  733        }
  734    })
  735    .detach();
  736}
  737
  738pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  739    component::init();
  740    theme_preview::init(cx);
  741    toast_layer::init(cx);
  742    history_manager::init(app_state.fs.clone(), cx);
  743
  744    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  745        .on_action(|_: &Reload, cx| reload(cx))
  746        .on_action(|_: &Open, cx: &mut App| {
  747            let app_state = AppState::global(cx);
  748            prompt_and_open_paths(
  749                app_state,
  750                PathPromptOptions {
  751                    files: true,
  752                    directories: true,
  753                    multiple: true,
  754                    prompt: None,
  755                },
  756                cx,
  757            );
  758        })
  759        .on_action(|_: &OpenFiles, cx: &mut App| {
  760            let directories = cx.can_select_mixed_files_and_dirs();
  761            let app_state = AppState::global(cx);
  762            prompt_and_open_paths(
  763                app_state,
  764                PathPromptOptions {
  765                    files: true,
  766                    directories,
  767                    multiple: true,
  768                    prompt: None,
  769                },
  770                cx,
  771            );
  772        });
  773}
  774
  775type BuildProjectItemFn =
  776    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  777
  778type BuildProjectItemForPathFn =
  779    fn(
  780        &Entity<Project>,
  781        &ProjectPath,
  782        &mut Window,
  783        &mut App,
  784    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  785
  786#[derive(Clone, Default)]
  787struct ProjectItemRegistry {
  788    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  789    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  790}
  791
  792impl ProjectItemRegistry {
  793    fn register<T: ProjectItem>(&mut self) {
  794        self.build_project_item_fns_by_type.insert(
  795            TypeId::of::<T::Item>(),
  796            |item, project, pane, window, cx| {
  797                let item = item.downcast().unwrap();
  798                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  799                    as Box<dyn ItemHandle>
  800            },
  801        );
  802        self.build_project_item_for_path_fns
  803            .push(|project, project_path, window, cx| {
  804                let project_path = project_path.clone();
  805                let is_file = project
  806                    .read(cx)
  807                    .entry_for_path(&project_path, cx)
  808                    .is_some_and(|entry| entry.is_file());
  809                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  810                let is_local = project.read(cx).is_local();
  811                let project_item =
  812                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  813                let project = project.clone();
  814                Some(window.spawn(cx, async move |cx| {
  815                    match project_item.await.with_context(|| {
  816                        format!(
  817                            "opening project path {:?}",
  818                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  819                        )
  820                    }) {
  821                        Ok(project_item) => {
  822                            let project_item = project_item;
  823                            let project_entry_id: Option<ProjectEntryId> =
  824                                project_item.read_with(cx, project::ProjectItem::entry_id);
  825                            let build_workspace_item = Box::new(
  826                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  827                                    Box::new(cx.new(|cx| {
  828                                        T::for_project_item(
  829                                            project,
  830                                            Some(pane),
  831                                            project_item,
  832                                            window,
  833                                            cx,
  834                                        )
  835                                    })) as Box<dyn ItemHandle>
  836                                },
  837                            ) as Box<_>;
  838                            Ok((project_entry_id, build_workspace_item))
  839                        }
  840                        Err(e) => {
  841                            log::warn!("Failed to open a project item: {e:#}");
  842                            if e.error_code() == ErrorCode::Internal {
  843                                if let Some(abs_path) =
  844                                    entry_abs_path.as_deref().filter(|_| is_file)
  845                                {
  846                                    if let Some(broken_project_item_view) =
  847                                        cx.update(|window, cx| {
  848                                            T::for_broken_project_item(
  849                                                abs_path, is_local, &e, window, cx,
  850                                            )
  851                                        })?
  852                                    {
  853                                        let build_workspace_item = Box::new(
  854                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  855                                                cx.new(|_| broken_project_item_view).boxed_clone()
  856                                            },
  857                                        )
  858                                        as Box<_>;
  859                                        return Ok((None, build_workspace_item));
  860                                    }
  861                                }
  862                            }
  863                            Err(e)
  864                        }
  865                    }
  866                }))
  867            });
  868    }
  869
  870    fn open_path(
  871        &self,
  872        project: &Entity<Project>,
  873        path: &ProjectPath,
  874        window: &mut Window,
  875        cx: &mut App,
  876    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  877        let Some(open_project_item) = self
  878            .build_project_item_for_path_fns
  879            .iter()
  880            .rev()
  881            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  882        else {
  883            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  884        };
  885        open_project_item
  886    }
  887
  888    fn build_item<T: project::ProjectItem>(
  889        &self,
  890        item: Entity<T>,
  891        project: Entity<Project>,
  892        pane: Option<&Pane>,
  893        window: &mut Window,
  894        cx: &mut App,
  895    ) -> Option<Box<dyn ItemHandle>> {
  896        let build = self
  897            .build_project_item_fns_by_type
  898            .get(&TypeId::of::<T>())?;
  899        Some(build(item.into_any(), project, pane, window, cx))
  900    }
  901}
  902
  903type WorkspaceItemBuilder =
  904    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  905
  906impl Global for ProjectItemRegistry {}
  907
  908/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  909/// items will get a chance to open the file, starting from the project item that
  910/// was added last.
  911pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  912    cx.default_global::<ProjectItemRegistry>().register::<I>();
  913}
  914
  915#[derive(Default)]
  916pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  917
  918struct FollowableViewDescriptor {
  919    from_state_proto: fn(
  920        Entity<Workspace>,
  921        ViewId,
  922        &mut Option<proto::view::Variant>,
  923        &mut Window,
  924        &mut App,
  925    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  926    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  927}
  928
  929impl Global for FollowableViewRegistry {}
  930
  931impl FollowableViewRegistry {
  932    pub fn register<I: FollowableItem>(cx: &mut App) {
  933        cx.default_global::<Self>().0.insert(
  934            TypeId::of::<I>(),
  935            FollowableViewDescriptor {
  936                from_state_proto: |workspace, id, state, window, cx| {
  937                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  938                        cx.foreground_executor()
  939                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  940                    })
  941                },
  942                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  943            },
  944        );
  945    }
  946
  947    pub fn from_state_proto(
  948        workspace: Entity<Workspace>,
  949        view_id: ViewId,
  950        mut state: Option<proto::view::Variant>,
  951        window: &mut Window,
  952        cx: &mut App,
  953    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  954        cx.update_default_global(|this: &mut Self, cx| {
  955            this.0.values().find_map(|descriptor| {
  956                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  957            })
  958        })
  959    }
  960
  961    pub fn to_followable_view(
  962        view: impl Into<AnyView>,
  963        cx: &App,
  964    ) -> Option<Box<dyn FollowableItemHandle>> {
  965        let this = cx.try_global::<Self>()?;
  966        let view = view.into();
  967        let descriptor = this.0.get(&view.entity_type())?;
  968        Some((descriptor.to_followable_view)(&view))
  969    }
  970}
  971
  972#[derive(Copy, Clone)]
  973struct SerializableItemDescriptor {
  974    deserialize: fn(
  975        Entity<Project>,
  976        WeakEntity<Workspace>,
  977        WorkspaceId,
  978        ItemId,
  979        &mut Window,
  980        &mut Context<Pane>,
  981    ) -> Task<Result<Box<dyn ItemHandle>>>,
  982    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  983    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  984}
  985
  986#[derive(Default)]
  987struct SerializableItemRegistry {
  988    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  989    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  990}
  991
  992impl Global for SerializableItemRegistry {}
  993
  994impl SerializableItemRegistry {
  995    fn deserialize(
  996        item_kind: &str,
  997        project: Entity<Project>,
  998        workspace: WeakEntity<Workspace>,
  999        workspace_id: WorkspaceId,
 1000        item_item: ItemId,
 1001        window: &mut Window,
 1002        cx: &mut Context<Pane>,
 1003    ) -> Task<Result<Box<dyn ItemHandle>>> {
 1004        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1005            return Task::ready(Err(anyhow!(
 1006                "cannot deserialize {}, descriptor not found",
 1007                item_kind
 1008            )));
 1009        };
 1010
 1011        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
 1012    }
 1013
 1014    fn cleanup(
 1015        item_kind: &str,
 1016        workspace_id: WorkspaceId,
 1017        loaded_items: Vec<ItemId>,
 1018        window: &mut Window,
 1019        cx: &mut App,
 1020    ) -> Task<Result<()>> {
 1021        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1022            return Task::ready(Err(anyhow!(
 1023                "cannot cleanup {}, descriptor not found",
 1024                item_kind
 1025            )));
 1026        };
 1027
 1028        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
 1029    }
 1030
 1031    fn view_to_serializable_item_handle(
 1032        view: AnyView,
 1033        cx: &App,
 1034    ) -> Option<Box<dyn SerializableItemHandle>> {
 1035        let this = cx.try_global::<Self>()?;
 1036        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
 1037        Some((descriptor.view_to_serializable_item)(view))
 1038    }
 1039
 1040    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
 1041        let this = cx.try_global::<Self>()?;
 1042        this.descriptors_by_kind.get(item_kind).copied()
 1043    }
 1044}
 1045
 1046pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
 1047    let serialized_item_kind = I::serialized_item_kind();
 1048
 1049    let registry = cx.default_global::<SerializableItemRegistry>();
 1050    let descriptor = SerializableItemDescriptor {
 1051        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
 1052            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
 1053            cx.foreground_executor()
 1054                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 1055        },
 1056        cleanup: |workspace_id, loaded_items, window, cx| {
 1057            I::cleanup(workspace_id, loaded_items, window, cx)
 1058        },
 1059        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1060    };
 1061    registry
 1062        .descriptors_by_kind
 1063        .insert(Arc::from(serialized_item_kind), descriptor);
 1064    registry
 1065        .descriptors_by_type
 1066        .insert(TypeId::of::<I>(), descriptor);
 1067}
 1068
 1069pub struct AppState {
 1070    pub languages: Arc<LanguageRegistry>,
 1071    pub client: Arc<Client>,
 1072    pub user_store: Entity<UserStore>,
 1073    pub workspace_store: Entity<WorkspaceStore>,
 1074    pub fs: Arc<dyn fs::Fs>,
 1075    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1076    pub node_runtime: NodeRuntime,
 1077    pub session: Entity<AppSession>,
 1078}
 1079
 1080struct GlobalAppState(Arc<AppState>);
 1081
 1082impl Global for GlobalAppState {}
 1083
 1084pub struct WorkspaceStore {
 1085    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1086    client: Arc<Client>,
 1087    _subscriptions: Vec<client::Subscription>,
 1088}
 1089
 1090#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1091pub enum CollaboratorId {
 1092    PeerId(PeerId),
 1093    Agent,
 1094}
 1095
 1096impl From<PeerId> for CollaboratorId {
 1097    fn from(peer_id: PeerId) -> Self {
 1098        CollaboratorId::PeerId(peer_id)
 1099    }
 1100}
 1101
 1102impl From<&PeerId> for CollaboratorId {
 1103    fn from(peer_id: &PeerId) -> Self {
 1104        CollaboratorId::PeerId(*peer_id)
 1105    }
 1106}
 1107
 1108#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1109struct Follower {
 1110    project_id: Option<u64>,
 1111    peer_id: PeerId,
 1112}
 1113
 1114impl AppState {
 1115    #[track_caller]
 1116    pub fn global(cx: &App) -> Arc<Self> {
 1117        cx.global::<GlobalAppState>().0.clone()
 1118    }
 1119    pub fn try_global(cx: &App) -> Option<Arc<Self>> {
 1120        cx.try_global::<GlobalAppState>()
 1121            .map(|state| state.0.clone())
 1122    }
 1123    pub fn set_global(state: Arc<AppState>, cx: &mut App) {
 1124        cx.set_global(GlobalAppState(state));
 1125    }
 1126
 1127    #[cfg(any(test, feature = "test-support"))]
 1128    pub fn test(cx: &mut App) -> Arc<Self> {
 1129        use fs::Fs;
 1130        use node_runtime::NodeRuntime;
 1131        use session::Session;
 1132        use settings::SettingsStore;
 1133
 1134        if !cx.has_global::<SettingsStore>() {
 1135            let settings_store = SettingsStore::test(cx);
 1136            cx.set_global(settings_store);
 1137        }
 1138
 1139        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1140        <dyn Fs>::set_global(fs.clone(), cx);
 1141        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1142        let clock = Arc::new(clock::FakeSystemClock::new());
 1143        let http_client = http_client::FakeHttpClient::with_404_response();
 1144        let client = Client::new(clock, http_client, cx);
 1145        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1146        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1147        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1148
 1149        theme_settings::init(theme::LoadThemes::JustBase, cx);
 1150        client::init(&client, cx);
 1151
 1152        Arc::new(Self {
 1153            client,
 1154            fs,
 1155            languages,
 1156            user_store,
 1157            workspace_store,
 1158            node_runtime: NodeRuntime::unavailable(),
 1159            build_window_options: |_, _| Default::default(),
 1160            session,
 1161        })
 1162    }
 1163}
 1164
 1165struct DelayedDebouncedEditAction {
 1166    task: Option<Task<()>>,
 1167    cancel_channel: Option<oneshot::Sender<()>>,
 1168}
 1169
 1170impl DelayedDebouncedEditAction {
 1171    fn new() -> DelayedDebouncedEditAction {
 1172        DelayedDebouncedEditAction {
 1173            task: None,
 1174            cancel_channel: None,
 1175        }
 1176    }
 1177
 1178    fn fire_new<F>(
 1179        &mut self,
 1180        delay: Duration,
 1181        window: &mut Window,
 1182        cx: &mut Context<Workspace>,
 1183        func: F,
 1184    ) where
 1185        F: 'static
 1186            + Send
 1187            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1188    {
 1189        if let Some(channel) = self.cancel_channel.take() {
 1190            _ = channel.send(());
 1191        }
 1192
 1193        let (sender, mut receiver) = oneshot::channel::<()>();
 1194        self.cancel_channel = Some(sender);
 1195
 1196        let previous_task = self.task.take();
 1197        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1198            let mut timer = cx.background_executor().timer(delay).fuse();
 1199            if let Some(previous_task) = previous_task {
 1200                previous_task.await;
 1201            }
 1202
 1203            futures::select_biased! {
 1204                _ = receiver => return,
 1205                    _ = timer => {}
 1206            }
 1207
 1208            if let Some(result) = workspace
 1209                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1210                .log_err()
 1211            {
 1212                result.await.log_err();
 1213            }
 1214        }));
 1215    }
 1216}
 1217
 1218pub enum Event {
 1219    PaneAdded(Entity<Pane>),
 1220    PaneRemoved,
 1221    ItemAdded {
 1222        item: Box<dyn ItemHandle>,
 1223    },
 1224    ActiveItemChanged,
 1225    ItemRemoved {
 1226        item_id: EntityId,
 1227    },
 1228    UserSavedItem {
 1229        pane: WeakEntity<Pane>,
 1230        item: Box<dyn WeakItemHandle>,
 1231        save_intent: SaveIntent,
 1232    },
 1233    ContactRequestedJoin(u64),
 1234    WorkspaceCreated(WeakEntity<Workspace>),
 1235    OpenBundledFile {
 1236        text: Cow<'static, str>,
 1237        title: &'static str,
 1238        language: &'static str,
 1239    },
 1240    ZoomChanged,
 1241    ModalOpened,
 1242    Activate,
 1243    PanelAdded(AnyView),
 1244}
 1245
 1246#[derive(Debug, Clone)]
 1247pub enum OpenVisible {
 1248    All,
 1249    None,
 1250    OnlyFiles,
 1251    OnlyDirectories,
 1252}
 1253
 1254enum WorkspaceLocation {
 1255    // Valid local paths or SSH project to serialize
 1256    Location(SerializedWorkspaceLocation, PathList),
 1257    // No valid location found hence clear session id
 1258    DetachFromSession,
 1259    // No valid location found to serialize
 1260    None,
 1261}
 1262
 1263type PromptForNewPath = Box<
 1264    dyn Fn(
 1265        &mut Workspace,
 1266        DirectoryLister,
 1267        Option<String>,
 1268        &mut Window,
 1269        &mut Context<Workspace>,
 1270    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1271>;
 1272
 1273type PromptForOpenPath = Box<
 1274    dyn Fn(
 1275        &mut Workspace,
 1276        DirectoryLister,
 1277        &mut Window,
 1278        &mut Context<Workspace>,
 1279    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1280>;
 1281
 1282#[derive(Default)]
 1283struct DispatchingKeystrokes {
 1284    dispatched: HashSet<Vec<Keystroke>>,
 1285    queue: VecDeque<Keystroke>,
 1286    task: Option<Shared<Task<()>>>,
 1287}
 1288
 1289/// Collects everything project-related for a certain window opened.
 1290/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1291///
 1292/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1293/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1294/// that can be used to register a global action to be triggered from any place in the window.
 1295pub struct Workspace {
 1296    weak_self: WeakEntity<Self>,
 1297    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1298    zoomed: Option<AnyWeakView>,
 1299    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1300    zoomed_position: Option<DockPosition>,
 1301    center: PaneGroup,
 1302    left_dock: Entity<Dock>,
 1303    bottom_dock: Entity<Dock>,
 1304    right_dock: Entity<Dock>,
 1305    panes: Vec<Entity<Pane>>,
 1306    active_worktree_override: Option<WorktreeId>,
 1307    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1308    active_pane: Entity<Pane>,
 1309    last_active_center_pane: Option<WeakEntity<Pane>>,
 1310    last_active_view_id: Option<proto::ViewId>,
 1311    status_bar: Entity<StatusBar>,
 1312    pub(crate) modal_layer: Entity<ModalLayer>,
 1313    toast_layer: Entity<ToastLayer>,
 1314    titlebar_item: Option<AnyView>,
 1315    notifications: Notifications,
 1316    suppressed_notifications: HashSet<NotificationId>,
 1317    project: Entity<Project>,
 1318    follower_states: HashMap<CollaboratorId, FollowerState>,
 1319    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1320    window_edited: bool,
 1321    last_window_title: Option<String>,
 1322    dirty_items: HashMap<EntityId, Subscription>,
 1323    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1324    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1325    database_id: Option<WorkspaceId>,
 1326    app_state: Arc<AppState>,
 1327    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1328    _subscriptions: Vec<Subscription>,
 1329    _apply_leader_updates: Task<Result<()>>,
 1330    _observe_current_user: Task<Result<()>>,
 1331    _schedule_serialize_workspace: Option<Task<()>>,
 1332    _serialize_workspace_task: Option<Task<()>>,
 1333    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1334    pane_history_timestamp: Arc<AtomicUsize>,
 1335    bounds: Bounds<Pixels>,
 1336    pub centered_layout: bool,
 1337    bounds_save_task_queued: Option<Task<()>>,
 1338    on_prompt_for_new_path: Option<PromptForNewPath>,
 1339    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1340    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1341    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1342    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1343    _items_serializer: Task<Result<()>>,
 1344    session_id: Option<String>,
 1345    scheduled_tasks: Vec<Task<()>>,
 1346    last_open_dock_positions: Vec<DockPosition>,
 1347    removing: bool,
 1348    open_in_dev_container: bool,
 1349    _dev_container_task: Option<Task<Result<()>>>,
 1350    _panels_task: Option<Task<Result<()>>>,
 1351    sidebar_focus_handle: Option<FocusHandle>,
 1352    multi_workspace: Option<WeakEntity<MultiWorkspace>>,
 1353}
 1354
 1355impl EventEmitter<Event> for Workspace {}
 1356
 1357#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1358pub struct ViewId {
 1359    pub creator: CollaboratorId,
 1360    pub id: u64,
 1361}
 1362
 1363pub struct FollowerState {
 1364    center_pane: Entity<Pane>,
 1365    dock_pane: Option<Entity<Pane>>,
 1366    active_view_id: Option<ViewId>,
 1367    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1368}
 1369
 1370struct FollowerView {
 1371    view: Box<dyn FollowableItemHandle>,
 1372    location: Option<proto::PanelId>,
 1373}
 1374
 1375#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
 1376pub enum OpenMode {
 1377    /// Open the workspace in a new window.
 1378    NewWindow,
 1379    /// Add to the window's multi workspace without activating it (used during deserialization).
 1380    Add,
 1381    /// Add to the window's multi workspace and activate it.
 1382    #[default]
 1383    Activate,
 1384}
 1385
 1386impl Workspace {
 1387    pub fn new(
 1388        workspace_id: Option<WorkspaceId>,
 1389        project: Entity<Project>,
 1390        app_state: Arc<AppState>,
 1391        window: &mut Window,
 1392        cx: &mut Context<Self>,
 1393    ) -> Self {
 1394        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1395            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1396                if let TrustedWorktreesEvent::Trusted(..) = e {
 1397                    // Do not persist auto trusted worktrees
 1398                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1399                        worktrees_store.update(cx, |worktrees_store, cx| {
 1400                            worktrees_store.schedule_serialization(
 1401                                cx,
 1402                                |new_trusted_worktrees, cx| {
 1403                                    let timeout =
 1404                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1405                                    let db = WorkspaceDb::global(cx);
 1406                                    cx.background_spawn(async move {
 1407                                        timeout.await;
 1408                                        db.save_trusted_worktrees(new_trusted_worktrees)
 1409                                            .await
 1410                                            .log_err();
 1411                                    })
 1412                                },
 1413                            )
 1414                        });
 1415                    }
 1416                }
 1417            })
 1418            .detach();
 1419
 1420            cx.observe_global::<SettingsStore>(|_, cx| {
 1421                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1422                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1423                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1424                            trusted_worktrees.auto_trust_all(cx);
 1425                        })
 1426                    }
 1427                }
 1428            })
 1429            .detach();
 1430        }
 1431
 1432        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1433            match event {
 1434                project::Event::RemoteIdChanged(_) => {
 1435                    this.update_window_title(window, cx);
 1436                }
 1437
 1438                project::Event::CollaboratorLeft(peer_id) => {
 1439                    this.collaborator_left(*peer_id, window, cx);
 1440                }
 1441
 1442                &project::Event::WorktreeRemoved(_) => {
 1443                    this.update_window_title(window, cx);
 1444                    this.serialize_workspace(window, cx);
 1445                    this.update_history(cx);
 1446                }
 1447
 1448                &project::Event::WorktreeAdded(id) => {
 1449                    this.update_window_title(window, cx);
 1450                    if this
 1451                        .project()
 1452                        .read(cx)
 1453                        .worktree_for_id(id, cx)
 1454                        .is_some_and(|wt| wt.read(cx).is_visible())
 1455                    {
 1456                        this.serialize_workspace(window, cx);
 1457                        this.update_history(cx);
 1458                    }
 1459                }
 1460                project::Event::WorktreeUpdatedEntries(..) => {
 1461                    this.update_window_title(window, cx);
 1462                    this.serialize_workspace(window, cx);
 1463                }
 1464
 1465                project::Event::DisconnectedFromHost => {
 1466                    this.update_window_edited(window, cx);
 1467                    let leaders_to_unfollow =
 1468                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1469                    for leader_id in leaders_to_unfollow {
 1470                        this.unfollow(leader_id, window, cx);
 1471                    }
 1472                }
 1473
 1474                project::Event::DisconnectedFromRemote {
 1475                    server_not_running: _,
 1476                } => {
 1477                    this.update_window_edited(window, cx);
 1478                }
 1479
 1480                project::Event::Closed => {
 1481                    window.remove_window();
 1482                }
 1483
 1484                project::Event::DeletedEntry(_, entry_id) => {
 1485                    for pane in this.panes.iter() {
 1486                        pane.update(cx, |pane, cx| {
 1487                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1488                        });
 1489                    }
 1490                }
 1491
 1492                project::Event::Toast {
 1493                    notification_id,
 1494                    message,
 1495                    link,
 1496                } => this.show_notification(
 1497                    NotificationId::named(notification_id.clone()),
 1498                    cx,
 1499                    |cx| {
 1500                        let mut notification = MessageNotification::new(message.clone(), cx);
 1501                        if let Some(link) = link {
 1502                            notification = notification
 1503                                .more_info_message(link.label)
 1504                                .more_info_url(link.url);
 1505                        }
 1506
 1507                        cx.new(|_| notification)
 1508                    },
 1509                ),
 1510
 1511                project::Event::HideToast { notification_id } => {
 1512                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1513                }
 1514
 1515                project::Event::LanguageServerPrompt(request) => {
 1516                    struct LanguageServerPrompt;
 1517
 1518                    this.show_notification(
 1519                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1520                        cx,
 1521                        |cx| {
 1522                            cx.new(|cx| {
 1523                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1524                            })
 1525                        },
 1526                    );
 1527                }
 1528
 1529                project::Event::AgentLocationChanged => {
 1530                    this.handle_agent_location_changed(window, cx)
 1531                }
 1532
 1533                _ => {}
 1534            }
 1535            cx.notify()
 1536        })
 1537        .detach();
 1538
 1539        cx.subscribe_in(
 1540            &project.read(cx).breakpoint_store(),
 1541            window,
 1542            |workspace, _, event, window, cx| match event {
 1543                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1544                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1545                    workspace.serialize_workspace(window, cx);
 1546                }
 1547                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1548            },
 1549        )
 1550        .detach();
 1551        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1552            cx.subscribe_in(
 1553                &toolchain_store,
 1554                window,
 1555                |workspace, _, event, window, cx| match event {
 1556                    ToolchainStoreEvent::CustomToolchainsModified => {
 1557                        workspace.serialize_workspace(window, cx);
 1558                    }
 1559                    _ => {}
 1560                },
 1561            )
 1562            .detach();
 1563        }
 1564
 1565        cx.on_focus_lost(window, |this, window, cx| {
 1566            let focus_handle = this.focus_handle(cx);
 1567            window.focus(&focus_handle, cx);
 1568        })
 1569        .detach();
 1570
 1571        let weak_handle = cx.entity().downgrade();
 1572        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1573
 1574        let center_pane = cx.new(|cx| {
 1575            let mut center_pane = Pane::new(
 1576                weak_handle.clone(),
 1577                project.clone(),
 1578                pane_history_timestamp.clone(),
 1579                None,
 1580                NewFile.boxed_clone(),
 1581                true,
 1582                window,
 1583                cx,
 1584            );
 1585            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1586            center_pane.set_should_display_welcome_page(true);
 1587            center_pane
 1588        });
 1589        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1590            .detach();
 1591
 1592        window.focus(&center_pane.focus_handle(cx), cx);
 1593
 1594        cx.emit(Event::PaneAdded(center_pane.clone()));
 1595
 1596        let any_window_handle = window.window_handle();
 1597        app_state.workspace_store.update(cx, |store, _| {
 1598            store
 1599                .workspaces
 1600                .insert((any_window_handle, weak_handle.clone()));
 1601        });
 1602
 1603        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1604        let mut connection_status = app_state.client.status();
 1605        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1606            current_user.next().await;
 1607            connection_status.next().await;
 1608            let mut stream =
 1609                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1610
 1611            while stream.recv().await.is_some() {
 1612                this.update(cx, |_, cx| cx.notify())?;
 1613            }
 1614            anyhow::Ok(())
 1615        });
 1616
 1617        // All leader updates are enqueued and then processed in a single task, so
 1618        // that each asynchronous operation can be run in order.
 1619        let (leader_updates_tx, mut leader_updates_rx) =
 1620            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1621        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1622            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1623                Self::process_leader_update(&this, leader_id, update, cx)
 1624                    .await
 1625                    .log_err();
 1626            }
 1627
 1628            Ok(())
 1629        });
 1630
 1631        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1632        let modal_layer = cx.new(|_| ModalLayer::new());
 1633        let toast_layer = cx.new(|_| ToastLayer::new());
 1634        cx.subscribe(
 1635            &modal_layer,
 1636            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1637                cx.emit(Event::ModalOpened);
 1638            },
 1639        )
 1640        .detach();
 1641
 1642        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1643        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1644        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1645        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1646        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1647        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1648        let multi_workspace = window
 1649            .root::<MultiWorkspace>()
 1650            .flatten()
 1651            .map(|mw| mw.downgrade());
 1652        let status_bar = cx.new(|cx| {
 1653            let mut status_bar =
 1654                StatusBar::new(&center_pane.clone(), multi_workspace.clone(), window, cx);
 1655            status_bar.add_left_item(left_dock_buttons, window, cx);
 1656            status_bar.add_right_item(right_dock_buttons, window, cx);
 1657            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1658            status_bar
 1659        });
 1660
 1661        let session_id = app_state.session.read(cx).id().to_owned();
 1662
 1663        let mut active_call = None;
 1664        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1665            let subscriptions =
 1666                vec![
 1667                    call.0
 1668                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1669                ];
 1670            active_call = Some((call, subscriptions));
 1671        }
 1672
 1673        let (serializable_items_tx, serializable_items_rx) =
 1674            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1675        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1676            Self::serialize_items(&this, serializable_items_rx, cx).await
 1677        });
 1678
 1679        let subscriptions = vec![
 1680            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1681            cx.observe_window_bounds(window, move |this, window, cx| {
 1682                if this.bounds_save_task_queued.is_some() {
 1683                    return;
 1684                }
 1685                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1686                    cx.background_executor()
 1687                        .timer(Duration::from_millis(100))
 1688                        .await;
 1689                    this.update_in(cx, |this, window, cx| {
 1690                        this.save_window_bounds(window, cx).detach();
 1691                        this.bounds_save_task_queued.take();
 1692                    })
 1693                    .ok();
 1694                }));
 1695                cx.notify();
 1696            }),
 1697            cx.observe_window_appearance(window, |_, window, cx| {
 1698                let window_appearance = window.appearance();
 1699
 1700                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1701
 1702                theme_settings::reload_theme(cx);
 1703                theme_settings::reload_icon_theme(cx);
 1704            }),
 1705            cx.on_release({
 1706                let weak_handle = weak_handle.clone();
 1707                move |this, cx| {
 1708                    this.app_state.workspace_store.update(cx, move |store, _| {
 1709                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1710                    })
 1711                }
 1712            }),
 1713        ];
 1714
 1715        cx.defer_in(window, move |this, window, cx| {
 1716            this.update_window_title(window, cx);
 1717            this.show_initial_notifications(cx);
 1718        });
 1719
 1720        let mut center = PaneGroup::new(center_pane.clone());
 1721        center.set_is_center(true);
 1722        center.mark_positions(cx);
 1723
 1724        Workspace {
 1725            weak_self: weak_handle.clone(),
 1726            zoomed: None,
 1727            zoomed_position: None,
 1728            previous_dock_drag_coordinates: None,
 1729            center,
 1730            panes: vec![center_pane.clone()],
 1731            panes_by_item: Default::default(),
 1732            active_pane: center_pane.clone(),
 1733            last_active_center_pane: Some(center_pane.downgrade()),
 1734            last_active_view_id: None,
 1735            status_bar,
 1736            modal_layer,
 1737            toast_layer,
 1738            titlebar_item: None,
 1739            active_worktree_override: None,
 1740            notifications: Notifications::default(),
 1741            suppressed_notifications: HashSet::default(),
 1742            left_dock,
 1743            bottom_dock,
 1744            right_dock,
 1745            _panels_task: None,
 1746            project: project.clone(),
 1747            follower_states: Default::default(),
 1748            last_leaders_by_pane: Default::default(),
 1749            dispatching_keystrokes: Default::default(),
 1750            window_edited: false,
 1751            last_window_title: None,
 1752            dirty_items: Default::default(),
 1753            active_call,
 1754            database_id: workspace_id,
 1755            app_state,
 1756            _observe_current_user,
 1757            _apply_leader_updates,
 1758            _schedule_serialize_workspace: None,
 1759            _serialize_workspace_task: None,
 1760            _schedule_serialize_ssh_paths: None,
 1761            leader_updates_tx,
 1762            _subscriptions: subscriptions,
 1763            pane_history_timestamp,
 1764            workspace_actions: Default::default(),
 1765            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1766            bounds: Default::default(),
 1767            centered_layout: false,
 1768            bounds_save_task_queued: None,
 1769            on_prompt_for_new_path: None,
 1770            on_prompt_for_open_path: None,
 1771            terminal_provider: None,
 1772            debugger_provider: None,
 1773            serializable_items_tx,
 1774            _items_serializer,
 1775            session_id: Some(session_id),
 1776
 1777            scheduled_tasks: Vec::new(),
 1778            last_open_dock_positions: Vec::new(),
 1779            removing: false,
 1780            sidebar_focus_handle: None,
 1781            multi_workspace,
 1782            open_in_dev_container: false,
 1783            _dev_container_task: None,
 1784        }
 1785    }
 1786
 1787    pub fn new_local(
 1788        abs_paths: Vec<PathBuf>,
 1789        app_state: Arc<AppState>,
 1790        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1791        env: Option<HashMap<String, String>>,
 1792        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1793        open_mode: OpenMode,
 1794        cx: &mut App,
 1795    ) -> Task<anyhow::Result<OpenResult>> {
 1796        let project_handle = Project::local(
 1797            app_state.client.clone(),
 1798            app_state.node_runtime.clone(),
 1799            app_state.user_store.clone(),
 1800            app_state.languages.clone(),
 1801            app_state.fs.clone(),
 1802            env,
 1803            Default::default(),
 1804            cx,
 1805        );
 1806
 1807        let db = WorkspaceDb::global(cx);
 1808        let kvp = db::kvp::KeyValueStore::global(cx);
 1809        cx.spawn(async move |cx| {
 1810            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1811            for path in abs_paths.into_iter() {
 1812                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1813                    paths_to_open.push(canonical)
 1814                } else {
 1815                    paths_to_open.push(path)
 1816                }
 1817            }
 1818
 1819            let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
 1820
 1821            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1822                paths_to_open = paths.ordered_paths().cloned().collect();
 1823                if !paths.is_lexicographically_ordered() {
 1824                    project_handle.update(cx, |project, cx| {
 1825                        project.set_worktrees_reordered(true, cx);
 1826                    });
 1827                }
 1828            }
 1829
 1830            // Get project paths for all of the abs_paths
 1831            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1832                Vec::with_capacity(paths_to_open.len());
 1833
 1834            for path in paths_to_open.into_iter() {
 1835                if let Some((_, project_entry)) = cx
 1836                    .update(|cx| {
 1837                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1838                    })
 1839                    .await
 1840                    .log_err()
 1841                {
 1842                    project_paths.push((path, Some(project_entry)));
 1843                } else {
 1844                    project_paths.push((path, None));
 1845                }
 1846            }
 1847
 1848            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1849                serialized_workspace.id
 1850            } else {
 1851                db.next_id().await.unwrap_or_else(|_| Default::default())
 1852            };
 1853
 1854            let toolchains = db.toolchains(workspace_id).await?;
 1855
 1856            for (toolchain, worktree_path, path) in toolchains {
 1857                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1858                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1859                    this.find_worktree(&worktree_path, cx)
 1860                        .and_then(|(worktree, rel_path)| {
 1861                            if rel_path.is_empty() {
 1862                                Some(worktree.read(cx).id())
 1863                            } else {
 1864                                None
 1865                            }
 1866                        })
 1867                }) else {
 1868                    // We did not find a worktree with a given path, but that's whatever.
 1869                    continue;
 1870                };
 1871                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1872                    continue;
 1873                }
 1874
 1875                project_handle
 1876                    .update(cx, |this, cx| {
 1877                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1878                    })
 1879                    .await;
 1880            }
 1881            if let Some(workspace) = serialized_workspace.as_ref() {
 1882                project_handle.update(cx, |this, cx| {
 1883                    for (scope, toolchains) in &workspace.user_toolchains {
 1884                        for toolchain in toolchains {
 1885                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1886                        }
 1887                    }
 1888                });
 1889            }
 1890
 1891            let window_to_replace = match open_mode {
 1892                OpenMode::NewWindow => None,
 1893                _ => requesting_window,
 1894            };
 1895
 1896            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1897                if let Some(window) = window_to_replace {
 1898                    let centered_layout = serialized_workspace
 1899                        .as_ref()
 1900                        .map(|w| w.centered_layout)
 1901                        .unwrap_or(false);
 1902
 1903                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1904                        let workspace = cx.new(|cx| {
 1905                            let mut workspace = Workspace::new(
 1906                                Some(workspace_id),
 1907                                project_handle.clone(),
 1908                                app_state.clone(),
 1909                                window,
 1910                                cx,
 1911                            );
 1912
 1913                            workspace.centered_layout = centered_layout;
 1914
 1915                            // Call init callback to add items before window renders
 1916                            if let Some(init) = init {
 1917                                init(&mut workspace, window, cx);
 1918                            }
 1919
 1920                            workspace
 1921                        });
 1922                        match open_mode {
 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 project_group_key(&self, cx: &App) -> ProjectGroupKey {
 2056        self.project.read(cx).project_group_key(cx)
 2057    }
 2058
 2059    pub fn weak_handle(&self) -> WeakEntity<Self> {
 2060        self.weak_self.clone()
 2061    }
 2062
 2063    pub fn left_dock(&self) -> &Entity<Dock> {
 2064        &self.left_dock
 2065    }
 2066
 2067    pub fn bottom_dock(&self) -> &Entity<Dock> {
 2068        &self.bottom_dock
 2069    }
 2070
 2071    pub fn set_bottom_dock_layout(
 2072        &mut self,
 2073        layout: BottomDockLayout,
 2074        window: &mut Window,
 2075        cx: &mut Context<Self>,
 2076    ) {
 2077        let fs = self.project().read(cx).fs();
 2078        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 2079            content.workspace.bottom_dock_layout = Some(layout);
 2080        });
 2081
 2082        cx.notify();
 2083        self.serialize_workspace(window, cx);
 2084    }
 2085
 2086    pub fn right_dock(&self) -> &Entity<Dock> {
 2087        &self.right_dock
 2088    }
 2089
 2090    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 2091        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 2092    }
 2093
 2094    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 2095        let left_dock = self.left_dock.read(cx);
 2096        let left_visible = left_dock.is_open();
 2097        let left_active_panel = left_dock
 2098            .active_panel()
 2099            .map(|panel| panel.persistent_name().to_string());
 2100        // `zoomed_position` is kept in sync with individual panel zoom state
 2101        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2102        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2103
 2104        let right_dock = self.right_dock.read(cx);
 2105        let right_visible = right_dock.is_open();
 2106        let right_active_panel = right_dock
 2107            .active_panel()
 2108            .map(|panel| panel.persistent_name().to_string());
 2109        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2110
 2111        let bottom_dock = self.bottom_dock.read(cx);
 2112        let bottom_visible = bottom_dock.is_open();
 2113        let bottom_active_panel = bottom_dock
 2114            .active_panel()
 2115            .map(|panel| panel.persistent_name().to_string());
 2116        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2117
 2118        DockStructure {
 2119            left: DockData {
 2120                visible: left_visible,
 2121                active_panel: left_active_panel,
 2122                zoom: left_dock_zoom,
 2123            },
 2124            right: DockData {
 2125                visible: right_visible,
 2126                active_panel: right_active_panel,
 2127                zoom: right_dock_zoom,
 2128            },
 2129            bottom: DockData {
 2130                visible: bottom_visible,
 2131                active_panel: bottom_active_panel,
 2132                zoom: bottom_dock_zoom,
 2133            },
 2134        }
 2135    }
 2136
 2137    pub fn set_dock_structure(
 2138        &self,
 2139        docks: DockStructure,
 2140        window: &mut Window,
 2141        cx: &mut Context<Self>,
 2142    ) {
 2143        for (dock, data) in [
 2144            (&self.left_dock, docks.left),
 2145            (&self.bottom_dock, docks.bottom),
 2146            (&self.right_dock, docks.right),
 2147        ] {
 2148            dock.update(cx, |dock, cx| {
 2149                dock.serialized_dock = Some(data);
 2150                dock.restore_state(window, cx);
 2151            });
 2152        }
 2153    }
 2154
 2155    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2156        self.items(cx)
 2157            .filter_map(|item| {
 2158                let project_path = item.project_path(cx)?;
 2159                self.project.read(cx).absolute_path(&project_path, cx)
 2160            })
 2161            .collect()
 2162    }
 2163
 2164    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2165        match position {
 2166            DockPosition::Left => &self.left_dock,
 2167            DockPosition::Bottom => &self.bottom_dock,
 2168            DockPosition::Right => &self.right_dock,
 2169        }
 2170    }
 2171
 2172    pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
 2173        self.all_docks().into_iter().find_map(|dock| {
 2174            let dock = dock.read(cx);
 2175            dock.has_agent_panel(cx).then_some(dock.position())
 2176        })
 2177    }
 2178
 2179    pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
 2180        self.all_docks().into_iter().find_map(|dock| {
 2181            let dock = dock.read(cx);
 2182            let panel = dock.panel::<T>()?;
 2183            dock.stored_panel_size_state(&panel)
 2184        })
 2185    }
 2186
 2187    pub fn persisted_panel_size_state(
 2188        &self,
 2189        panel_key: &'static str,
 2190        cx: &App,
 2191    ) -> Option<dock::PanelSizeState> {
 2192        dock::Dock::load_persisted_size_state(self, panel_key, cx)
 2193    }
 2194
 2195    pub fn persist_panel_size_state(
 2196        &self,
 2197        panel_key: &str,
 2198        size_state: dock::PanelSizeState,
 2199        cx: &mut App,
 2200    ) {
 2201        let Some(workspace_id) = self
 2202            .database_id()
 2203            .map(|id| i64::from(id).to_string())
 2204            .or(self.session_id())
 2205        else {
 2206            return;
 2207        };
 2208
 2209        let kvp = db::kvp::KeyValueStore::global(cx);
 2210        let panel_key = panel_key.to_string();
 2211        cx.background_spawn(async move {
 2212            let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
 2213            scope
 2214                .write(
 2215                    format!("{workspace_id}:{panel_key}"),
 2216                    serde_json::to_string(&size_state)?,
 2217                )
 2218                .await
 2219        })
 2220        .detach_and_log_err(cx);
 2221    }
 2222
 2223    pub fn set_panel_size_state<T: Panel>(
 2224        &mut self,
 2225        size_state: dock::PanelSizeState,
 2226        window: &mut Window,
 2227        cx: &mut Context<Self>,
 2228    ) -> bool {
 2229        let Some(panel) = self.panel::<T>(cx) else {
 2230            return false;
 2231        };
 2232
 2233        let dock = self.dock_at_position(panel.position(window, cx));
 2234        let did_set = dock.update(cx, |dock, cx| {
 2235            dock.set_panel_size_state(&panel, size_state, cx)
 2236        });
 2237
 2238        if did_set {
 2239            self.persist_panel_size_state(T::panel_key(), size_state, cx);
 2240        }
 2241
 2242        did_set
 2243    }
 2244
 2245    pub fn toggle_dock_panel_flexible_size(
 2246        &self,
 2247        dock: &Entity<Dock>,
 2248        panel: &dyn PanelHandle,
 2249        window: &mut Window,
 2250        cx: &mut App,
 2251    ) {
 2252        let position = dock.read(cx).position();
 2253        let current_size = self.dock_size(&dock.read(cx), window, cx);
 2254        let current_flex =
 2255            current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
 2256        dock.update(cx, |dock, cx| {
 2257            dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
 2258        });
 2259    }
 2260
 2261    fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
 2262        let panel = dock.active_panel()?;
 2263        let size_state = dock
 2264            .stored_panel_size_state(panel.as_ref())
 2265            .unwrap_or_default();
 2266        let position = dock.position();
 2267
 2268        let use_flex = panel.has_flexible_size(window, cx);
 2269
 2270        if position.axis() == Axis::Horizontal
 2271            && use_flex
 2272            && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
 2273        {
 2274            let workspace_width = self.bounds.size.width;
 2275            if workspace_width <= Pixels::ZERO {
 2276                return None;
 2277            }
 2278            let flex = flex.max(0.001);
 2279            let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2280            if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2281                // Both docks are flex items sharing the full workspace width.
 2282                let total_flex = flex + 1.0 + opposite_flex;
 2283                return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
 2284            } else {
 2285                // Opposite dock is fixed-width; flex items share (W - fixed).
 2286                let opposite_fixed = opposite
 2287                    .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2288                    .unwrap_or_default();
 2289                let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
 2290                return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
 2291            }
 2292        }
 2293
 2294        Some(
 2295            size_state
 2296                .size
 2297                .unwrap_or_else(|| panel.default_size(window, cx)),
 2298        )
 2299    }
 2300
 2301    pub fn dock_flex_for_size(
 2302        &self,
 2303        position: DockPosition,
 2304        size: Pixels,
 2305        window: &Window,
 2306        cx: &App,
 2307    ) -> Option<f32> {
 2308        if position.axis() != Axis::Horizontal {
 2309            return None;
 2310        }
 2311
 2312        let workspace_width = self.bounds.size.width;
 2313        if workspace_width <= Pixels::ZERO {
 2314            return None;
 2315        }
 2316
 2317        let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2318        if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2319            let size = size.clamp(px(0.), workspace_width - px(1.));
 2320            Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
 2321        } else {
 2322            let opposite_width = opposite
 2323                .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2324                .unwrap_or_default();
 2325            let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
 2326            let remaining = (available - size).max(px(1.));
 2327            Some((size / remaining).max(0.0))
 2328        }
 2329    }
 2330
 2331    fn opposite_dock_panel_and_size_state(
 2332        &self,
 2333        position: DockPosition,
 2334        window: &Window,
 2335        cx: &App,
 2336    ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
 2337        let opposite_position = match position {
 2338            DockPosition::Left => DockPosition::Right,
 2339            DockPosition::Right => DockPosition::Left,
 2340            DockPosition::Bottom => return None,
 2341        };
 2342
 2343        let opposite_dock = self.dock_at_position(opposite_position).read(cx);
 2344        let panel = opposite_dock.visible_panel()?;
 2345        let mut size_state = opposite_dock
 2346            .stored_panel_size_state(panel.as_ref())
 2347            .unwrap_or_default();
 2348        if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
 2349            size_state.flex = self.default_dock_flex(opposite_position);
 2350        }
 2351        Some((panel.clone(), size_state))
 2352    }
 2353
 2354    pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
 2355        if position.axis() != Axis::Horizontal {
 2356            return None;
 2357        }
 2358
 2359        let pane = self.last_active_center_pane.clone()?.upgrade()?;
 2360        Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
 2361    }
 2362
 2363    pub fn is_edited(&self) -> bool {
 2364        self.window_edited
 2365    }
 2366
 2367    pub fn add_panel<T: Panel>(
 2368        &mut self,
 2369        panel: Entity<T>,
 2370        window: &mut Window,
 2371        cx: &mut Context<Self>,
 2372    ) {
 2373        let focus_handle = panel.panel_focus_handle(cx);
 2374        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2375            .detach();
 2376
 2377        let dock_position = panel.position(window, cx);
 2378        let dock = self.dock_at_position(dock_position);
 2379        let any_panel = panel.to_any();
 2380        let persisted_size_state =
 2381            self.persisted_panel_size_state(T::panel_key(), cx)
 2382                .or_else(|| {
 2383                    load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
 2384                        let state = dock::PanelSizeState {
 2385                            size: Some(size),
 2386                            flex: None,
 2387                        };
 2388                        self.persist_panel_size_state(T::panel_key(), state, cx);
 2389                        state
 2390                    })
 2391                });
 2392
 2393        dock.update(cx, |dock, cx| {
 2394            let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
 2395            if let Some(size_state) = persisted_size_state {
 2396                dock.set_panel_size_state(&panel, size_state, cx);
 2397            }
 2398            index
 2399        });
 2400
 2401        cx.emit(Event::PanelAdded(any_panel));
 2402    }
 2403
 2404    pub fn remove_panel<T: Panel>(
 2405        &mut self,
 2406        panel: &Entity<T>,
 2407        window: &mut Window,
 2408        cx: &mut Context<Self>,
 2409    ) {
 2410        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2411            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2412        }
 2413    }
 2414
 2415    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2416        &self.status_bar
 2417    }
 2418
 2419    pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
 2420        self.sidebar_focus_handle = handle;
 2421    }
 2422
 2423    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2424        StatusBarSettings::get_global(cx).show
 2425    }
 2426
 2427    pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
 2428        self.multi_workspace.as_ref()
 2429    }
 2430
 2431    pub fn set_multi_workspace(
 2432        &mut self,
 2433        multi_workspace: WeakEntity<MultiWorkspace>,
 2434        cx: &mut App,
 2435    ) {
 2436        self.status_bar.update(cx, |status_bar, cx| {
 2437            status_bar.set_multi_workspace(multi_workspace.clone(), cx);
 2438        });
 2439        self.multi_workspace = Some(multi_workspace);
 2440    }
 2441
 2442    pub fn app_state(&self) -> &Arc<AppState> {
 2443        &self.app_state
 2444    }
 2445
 2446    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2447        self._panels_task = Some(task);
 2448    }
 2449
 2450    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2451        self._panels_task.take()
 2452    }
 2453
 2454    pub fn user_store(&self) -> &Entity<UserStore> {
 2455        &self.app_state.user_store
 2456    }
 2457
 2458    pub fn project(&self) -> &Entity<Project> {
 2459        &self.project
 2460    }
 2461
 2462    pub fn path_style(&self, cx: &App) -> PathStyle {
 2463        self.project.read(cx).path_style(cx)
 2464    }
 2465
 2466    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2467        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2468
 2469        for pane_handle in &self.panes {
 2470            let pane = pane_handle.read(cx);
 2471
 2472            for entry in pane.activation_history() {
 2473                history.insert(
 2474                    entry.entity_id,
 2475                    history
 2476                        .get(&entry.entity_id)
 2477                        .cloned()
 2478                        .unwrap_or(0)
 2479                        .max(entry.timestamp),
 2480                );
 2481            }
 2482        }
 2483
 2484        history
 2485    }
 2486
 2487    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2488        let mut recent_item: Option<Entity<T>> = None;
 2489        let mut recent_timestamp = 0;
 2490        for pane_handle in &self.panes {
 2491            let pane = pane_handle.read(cx);
 2492            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2493                pane.items().map(|item| (item.item_id(), item)).collect();
 2494            for entry in pane.activation_history() {
 2495                if entry.timestamp > recent_timestamp
 2496                    && let Some(&item) = item_map.get(&entry.entity_id)
 2497                    && let Some(typed_item) = item.act_as::<T>(cx)
 2498                {
 2499                    recent_timestamp = entry.timestamp;
 2500                    recent_item = Some(typed_item);
 2501                }
 2502            }
 2503        }
 2504        recent_item
 2505    }
 2506
 2507    pub fn recent_navigation_history_iter(
 2508        &self,
 2509        cx: &App,
 2510    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2511        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2512        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2513
 2514        for pane in &self.panes {
 2515            let pane = pane.read(cx);
 2516
 2517            pane.nav_history()
 2518                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2519                    if let Some(fs_path) = &fs_path {
 2520                        abs_paths_opened
 2521                            .entry(fs_path.clone())
 2522                            .or_default()
 2523                            .insert(project_path.clone());
 2524                    }
 2525                    let timestamp = entry.timestamp;
 2526                    match history.entry(project_path) {
 2527                        hash_map::Entry::Occupied(mut entry) => {
 2528                            let (_, old_timestamp) = entry.get();
 2529                            if &timestamp > old_timestamp {
 2530                                entry.insert((fs_path, timestamp));
 2531                            }
 2532                        }
 2533                        hash_map::Entry::Vacant(entry) => {
 2534                            entry.insert((fs_path, timestamp));
 2535                        }
 2536                    }
 2537                });
 2538
 2539            if let Some(item) = pane.active_item()
 2540                && let Some(project_path) = item.project_path(cx)
 2541            {
 2542                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2543
 2544                if let Some(fs_path) = &fs_path {
 2545                    abs_paths_opened
 2546                        .entry(fs_path.clone())
 2547                        .or_default()
 2548                        .insert(project_path.clone());
 2549                }
 2550
 2551                history.insert(project_path, (fs_path, std::usize::MAX));
 2552            }
 2553        }
 2554
 2555        history
 2556            .into_iter()
 2557            .sorted_by_key(|(_, (_, order))| *order)
 2558            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2559            .rev()
 2560            .filter(move |(history_path, abs_path)| {
 2561                let latest_project_path_opened = abs_path
 2562                    .as_ref()
 2563                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2564                    .and_then(|project_paths| {
 2565                        project_paths
 2566                            .iter()
 2567                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2568                    });
 2569
 2570                latest_project_path_opened.is_none_or(|path| path == history_path)
 2571            })
 2572    }
 2573
 2574    pub fn recent_navigation_history(
 2575        &self,
 2576        limit: Option<usize>,
 2577        cx: &App,
 2578    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2579        self.recent_navigation_history_iter(cx)
 2580            .take(limit.unwrap_or(usize::MAX))
 2581            .collect()
 2582    }
 2583
 2584    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2585        for pane in &self.panes {
 2586            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2587        }
 2588    }
 2589
 2590    fn navigate_history(
 2591        &mut self,
 2592        pane: WeakEntity<Pane>,
 2593        mode: NavigationMode,
 2594        window: &mut Window,
 2595        cx: &mut Context<Workspace>,
 2596    ) -> Task<Result<()>> {
 2597        self.navigate_history_impl(
 2598            pane,
 2599            mode,
 2600            window,
 2601            &mut |history, cx| history.pop(mode, cx),
 2602            cx,
 2603        )
 2604    }
 2605
 2606    fn navigate_tag_history(
 2607        &mut self,
 2608        pane: WeakEntity<Pane>,
 2609        mode: TagNavigationMode,
 2610        window: &mut Window,
 2611        cx: &mut Context<Workspace>,
 2612    ) -> Task<Result<()>> {
 2613        self.navigate_history_impl(
 2614            pane,
 2615            NavigationMode::Normal,
 2616            window,
 2617            &mut |history, _cx| history.pop_tag(mode),
 2618            cx,
 2619        )
 2620    }
 2621
 2622    fn navigate_history_impl(
 2623        &mut self,
 2624        pane: WeakEntity<Pane>,
 2625        mode: NavigationMode,
 2626        window: &mut Window,
 2627        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2628        cx: &mut Context<Workspace>,
 2629    ) -> Task<Result<()>> {
 2630        let to_load = if let Some(pane) = pane.upgrade() {
 2631            pane.update(cx, |pane, cx| {
 2632                window.focus(&pane.focus_handle(cx), cx);
 2633                loop {
 2634                    // Retrieve the weak item handle from the history.
 2635                    let entry = cb(pane.nav_history_mut(), cx)?;
 2636
 2637                    // If the item is still present in this pane, then activate it.
 2638                    if let Some(index) = entry
 2639                        .item
 2640                        .upgrade()
 2641                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2642                    {
 2643                        let prev_active_item_index = pane.active_item_index();
 2644                        pane.nav_history_mut().set_mode(mode);
 2645                        pane.activate_item(index, true, true, window, cx);
 2646                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2647
 2648                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2649                        if let Some(data) = entry.data {
 2650                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2651                        }
 2652
 2653                        if navigated {
 2654                            break None;
 2655                        }
 2656                    } else {
 2657                        // If the item is no longer present in this pane, then retrieve its
 2658                        // path info in order to reopen it.
 2659                        break pane
 2660                            .nav_history()
 2661                            .path_for_item(entry.item.id())
 2662                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2663                    }
 2664                }
 2665            })
 2666        } else {
 2667            None
 2668        };
 2669
 2670        if let Some((project_path, abs_path, entry)) = to_load {
 2671            // If the item was no longer present, then load it again from its previous path, first try the local path
 2672            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2673
 2674            cx.spawn_in(window, async move  |workspace, cx| {
 2675                let open_by_project_path = open_by_project_path.await;
 2676                let mut navigated = false;
 2677                match open_by_project_path
 2678                    .with_context(|| format!("Navigating to {project_path:?}"))
 2679                {
 2680                    Ok((project_entry_id, build_item)) => {
 2681                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2682                            pane.nav_history_mut().set_mode(mode);
 2683                            pane.active_item().map(|p| p.item_id())
 2684                        })?;
 2685
 2686                        pane.update_in(cx, |pane, window, cx| {
 2687                            let item = pane.open_item(
 2688                                project_entry_id,
 2689                                project_path,
 2690                                true,
 2691                                entry.is_preview,
 2692                                true,
 2693                                None,
 2694                                window, cx,
 2695                                build_item,
 2696                            );
 2697                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2698                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2699                            if let Some(data) = entry.data {
 2700                                navigated |= item.navigate(data, window, cx);
 2701                            }
 2702                        })?;
 2703                    }
 2704                    Err(open_by_project_path_e) => {
 2705                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2706                        // and its worktree is now dropped
 2707                        if let Some(abs_path) = abs_path {
 2708                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2709                                pane.nav_history_mut().set_mode(mode);
 2710                                pane.active_item().map(|p| p.item_id())
 2711                            })?;
 2712                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2713                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2714                            })?;
 2715                            match open_by_abs_path
 2716                                .await
 2717                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2718                            {
 2719                                Ok(item) => {
 2720                                    pane.update_in(cx, |pane, window, cx| {
 2721                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2722                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2723                                        if let Some(data) = entry.data {
 2724                                            navigated |= item.navigate(data, window, cx);
 2725                                        }
 2726                                    })?;
 2727                                }
 2728                                Err(open_by_abs_path_e) => {
 2729                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2730                                }
 2731                            }
 2732                        }
 2733                    }
 2734                }
 2735
 2736                if !navigated {
 2737                    workspace
 2738                        .update_in(cx, |workspace, window, cx| {
 2739                            Self::navigate_history(workspace, pane, mode, window, cx)
 2740                        })?
 2741                        .await?;
 2742                }
 2743
 2744                Ok(())
 2745            })
 2746        } else {
 2747            Task::ready(Ok(()))
 2748        }
 2749    }
 2750
 2751    pub fn go_back(
 2752        &mut self,
 2753        pane: WeakEntity<Pane>,
 2754        window: &mut Window,
 2755        cx: &mut Context<Workspace>,
 2756    ) -> Task<Result<()>> {
 2757        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2758    }
 2759
 2760    pub fn go_forward(
 2761        &mut self,
 2762        pane: WeakEntity<Pane>,
 2763        window: &mut Window,
 2764        cx: &mut Context<Workspace>,
 2765    ) -> Task<Result<()>> {
 2766        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2767    }
 2768
 2769    pub fn reopen_closed_item(
 2770        &mut self,
 2771        window: &mut Window,
 2772        cx: &mut Context<Workspace>,
 2773    ) -> Task<Result<()>> {
 2774        self.navigate_history(
 2775            self.active_pane().downgrade(),
 2776            NavigationMode::ReopeningClosedItem,
 2777            window,
 2778            cx,
 2779        )
 2780    }
 2781
 2782    pub fn client(&self) -> &Arc<Client> {
 2783        &self.app_state.client
 2784    }
 2785
 2786    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2787        self.titlebar_item = Some(item);
 2788        cx.notify();
 2789    }
 2790
 2791    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2792        self.on_prompt_for_new_path = Some(prompt)
 2793    }
 2794
 2795    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2796        self.on_prompt_for_open_path = Some(prompt)
 2797    }
 2798
 2799    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2800        self.terminal_provider = Some(Box::new(provider));
 2801    }
 2802
 2803    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2804        self.debugger_provider = Some(Arc::new(provider));
 2805    }
 2806
 2807    pub fn set_open_in_dev_container(&mut self, value: bool) {
 2808        self.open_in_dev_container = value;
 2809    }
 2810
 2811    pub fn open_in_dev_container(&self) -> bool {
 2812        self.open_in_dev_container
 2813    }
 2814
 2815    pub fn set_dev_container_task(&mut self, task: Task<Result<()>>) {
 2816        self._dev_container_task = Some(task);
 2817    }
 2818
 2819    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2820        self.debugger_provider.clone()
 2821    }
 2822
 2823    pub fn prompt_for_open_path(
 2824        &mut self,
 2825        path_prompt_options: PathPromptOptions,
 2826        lister: DirectoryLister,
 2827        window: &mut Window,
 2828        cx: &mut Context<Self>,
 2829    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2830        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2831            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2832            let rx = prompt(self, lister, window, cx);
 2833            self.on_prompt_for_open_path = Some(prompt);
 2834            rx
 2835        } else {
 2836            let (tx, rx) = oneshot::channel();
 2837            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2838
 2839            cx.spawn_in(window, async move |workspace, cx| {
 2840                let Ok(result) = abs_path.await else {
 2841                    return Ok(());
 2842                };
 2843
 2844                match result {
 2845                    Ok(result) => {
 2846                        tx.send(result).ok();
 2847                    }
 2848                    Err(err) => {
 2849                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2850                            workspace.show_portal_error(err.to_string(), cx);
 2851                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2852                            let rx = prompt(workspace, lister, window, cx);
 2853                            workspace.on_prompt_for_open_path = Some(prompt);
 2854                            rx
 2855                        })?;
 2856                        if let Ok(path) = rx.await {
 2857                            tx.send(path).ok();
 2858                        }
 2859                    }
 2860                };
 2861                anyhow::Ok(())
 2862            })
 2863            .detach();
 2864
 2865            rx
 2866        }
 2867    }
 2868
 2869    pub fn prompt_for_new_path(
 2870        &mut self,
 2871        lister: DirectoryLister,
 2872        suggested_name: Option<String>,
 2873        window: &mut Window,
 2874        cx: &mut Context<Self>,
 2875    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2876        if self.project.read(cx).is_via_collab()
 2877            || self.project.read(cx).is_via_remote_server()
 2878            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2879        {
 2880            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2881            let rx = prompt(self, lister, suggested_name, window, cx);
 2882            self.on_prompt_for_new_path = Some(prompt);
 2883            return rx;
 2884        }
 2885
 2886        let (tx, rx) = oneshot::channel();
 2887        cx.spawn_in(window, async move |workspace, cx| {
 2888            let abs_path = workspace.update(cx, |workspace, cx| {
 2889                let relative_to = workspace
 2890                    .most_recent_active_path(cx)
 2891                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2892                    .or_else(|| {
 2893                        let project = workspace.project.read(cx);
 2894                        project.visible_worktrees(cx).find_map(|worktree| {
 2895                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2896                        })
 2897                    })
 2898                    .or_else(std::env::home_dir)
 2899                    .unwrap_or_else(|| PathBuf::from(""));
 2900                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2901            })?;
 2902            let abs_path = match abs_path.await? {
 2903                Ok(path) => path,
 2904                Err(err) => {
 2905                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2906                        workspace.show_portal_error(err.to_string(), cx);
 2907
 2908                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2909                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2910                        workspace.on_prompt_for_new_path = Some(prompt);
 2911                        rx
 2912                    })?;
 2913                    if let Ok(path) = rx.await {
 2914                        tx.send(path).ok();
 2915                    }
 2916                    return anyhow::Ok(());
 2917                }
 2918            };
 2919
 2920            tx.send(abs_path.map(|path| vec![path])).ok();
 2921            anyhow::Ok(())
 2922        })
 2923        .detach();
 2924
 2925        rx
 2926    }
 2927
 2928    pub fn titlebar_item(&self) -> Option<AnyView> {
 2929        self.titlebar_item.clone()
 2930    }
 2931
 2932    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2933    /// When set, git-related operations should use this worktree instead of deriving
 2934    /// the active worktree from the focused file.
 2935    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2936        self.active_worktree_override
 2937    }
 2938
 2939    pub fn set_active_worktree_override(
 2940        &mut self,
 2941        worktree_id: Option<WorktreeId>,
 2942        cx: &mut Context<Self>,
 2943    ) {
 2944        self.active_worktree_override = worktree_id;
 2945        cx.notify();
 2946    }
 2947
 2948    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2949        self.active_worktree_override = None;
 2950        cx.notify();
 2951    }
 2952
 2953    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2954    ///
 2955    /// If the given workspace has a local project, then it will be passed
 2956    /// to the callback. Otherwise, a new empty window will be created.
 2957    pub fn with_local_workspace<T, F>(
 2958        &mut self,
 2959        window: &mut Window,
 2960        cx: &mut Context<Self>,
 2961        callback: F,
 2962    ) -> Task<Result<T>>
 2963    where
 2964        T: 'static,
 2965        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2966    {
 2967        if self.project.read(cx).is_local() {
 2968            Task::ready(Ok(callback(self, window, cx)))
 2969        } else {
 2970            let env = self.project.read(cx).cli_environment(cx);
 2971            let task = Self::new_local(
 2972                Vec::new(),
 2973                self.app_state.clone(),
 2974                None,
 2975                env,
 2976                None,
 2977                OpenMode::Activate,
 2978                cx,
 2979            );
 2980            cx.spawn_in(window, async move |_vh, cx| {
 2981                let OpenResult {
 2982                    window: multi_workspace_window,
 2983                    ..
 2984                } = task.await?;
 2985                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2986                    let workspace = multi_workspace.workspace().clone();
 2987                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2988                })
 2989            })
 2990        }
 2991    }
 2992
 2993    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2994    ///
 2995    /// If the given workspace has a local project, then it will be passed
 2996    /// to the callback. Otherwise, a new empty window will be created.
 2997    pub fn with_local_or_wsl_workspace<T, F>(
 2998        &mut self,
 2999        window: &mut Window,
 3000        cx: &mut Context<Self>,
 3001        callback: F,
 3002    ) -> Task<Result<T>>
 3003    where
 3004        T: 'static,
 3005        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 3006    {
 3007        let project = self.project.read(cx);
 3008        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 3009            Task::ready(Ok(callback(self, window, cx)))
 3010        } else {
 3011            let env = self.project.read(cx).cli_environment(cx);
 3012            let task = Self::new_local(
 3013                Vec::new(),
 3014                self.app_state.clone(),
 3015                None,
 3016                env,
 3017                None,
 3018                OpenMode::Activate,
 3019                cx,
 3020            );
 3021            cx.spawn_in(window, async move |_vh, cx| {
 3022                let OpenResult {
 3023                    window: multi_workspace_window,
 3024                    ..
 3025                } = task.await?;
 3026                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 3027                    let workspace = multi_workspace.workspace().clone();
 3028                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 3029                })
 3030            })
 3031        }
 3032    }
 3033
 3034    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3035        self.project.read(cx).worktrees(cx)
 3036    }
 3037
 3038    pub fn visible_worktrees<'a>(
 3039        &self,
 3040        cx: &'a App,
 3041    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3042        self.project.read(cx).visible_worktrees(cx)
 3043    }
 3044
 3045    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 3046        let futures = self
 3047            .worktrees(cx)
 3048            .filter_map(|worktree| worktree.read(cx).as_local())
 3049            .map(|worktree| worktree.scan_complete())
 3050            .collect::<Vec<_>>();
 3051        async move {
 3052            for future in futures {
 3053                future.await;
 3054            }
 3055        }
 3056    }
 3057
 3058    pub fn close_global(cx: &mut App) {
 3059        cx.defer(|cx| {
 3060            cx.windows().iter().find(|window| {
 3061                window
 3062                    .update(cx, |_, window, _| {
 3063                        if window.is_window_active() {
 3064                            //This can only get called when the window's project connection has been lost
 3065                            //so we don't need to prompt the user for anything and instead just close the window
 3066                            window.remove_window();
 3067                            true
 3068                        } else {
 3069                            false
 3070                        }
 3071                    })
 3072                    .unwrap_or(false)
 3073            });
 3074        });
 3075    }
 3076
 3077    pub fn move_focused_panel_to_next_position(
 3078        &mut self,
 3079        _: &MoveFocusedPanelToNextPosition,
 3080        window: &mut Window,
 3081        cx: &mut Context<Self>,
 3082    ) {
 3083        let docks = self.all_docks();
 3084        let active_dock = docks
 3085            .into_iter()
 3086            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 3087
 3088        if let Some(dock) = active_dock {
 3089            dock.update(cx, |dock, cx| {
 3090                let active_panel = dock
 3091                    .active_panel()
 3092                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 3093
 3094                if let Some(panel) = active_panel {
 3095                    panel.move_to_next_position(window, cx);
 3096                }
 3097            })
 3098        }
 3099    }
 3100
 3101    pub fn prepare_to_close(
 3102        &mut self,
 3103        close_intent: CloseIntent,
 3104        window: &mut Window,
 3105        cx: &mut Context<Self>,
 3106    ) -> Task<Result<bool>> {
 3107        let active_call = self.active_global_call();
 3108
 3109        cx.spawn_in(window, async move |this, cx| {
 3110            this.update(cx, |this, _| {
 3111                if close_intent == CloseIntent::CloseWindow {
 3112                    this.removing = true;
 3113                }
 3114            })?;
 3115
 3116            let workspace_count = cx.update(|_window, cx| {
 3117                cx.windows()
 3118                    .iter()
 3119                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 3120                    .count()
 3121            })?;
 3122
 3123            #[cfg(target_os = "macos")]
 3124            let save_last_workspace = false;
 3125
 3126            // On Linux and Windows, closing the last window should restore the last workspace.
 3127            #[cfg(not(target_os = "macos"))]
 3128            let save_last_workspace = {
 3129                let remaining_workspaces = cx.update(|_window, cx| {
 3130                    cx.windows()
 3131                        .iter()
 3132                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 3133                        .filter_map(|multi_workspace| {
 3134                            multi_workspace
 3135                                .update(cx, |multi_workspace, _, cx| {
 3136                                    multi_workspace.workspace().read(cx).removing
 3137                                })
 3138                                .ok()
 3139                        })
 3140                        .filter(|removing| !removing)
 3141                        .count()
 3142                })?;
 3143
 3144                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 3145            };
 3146
 3147            if let Some(active_call) = active_call
 3148                && workspace_count == 1
 3149                && cx
 3150                    .update(|_window, cx| active_call.0.is_in_room(cx))
 3151                    .unwrap_or(false)
 3152            {
 3153                if close_intent == CloseIntent::CloseWindow {
 3154                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3155                    let answer = cx.update(|window, cx| {
 3156                        window.prompt(
 3157                            PromptLevel::Warning,
 3158                            "Do you want to leave the current call?",
 3159                            None,
 3160                            &["Close window and hang up", "Cancel"],
 3161                            cx,
 3162                        )
 3163                    })?;
 3164
 3165                    if answer.await.log_err() == Some(1) {
 3166                        return anyhow::Ok(false);
 3167                    } else {
 3168                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 3169                            task.await.log_err();
 3170                        }
 3171                    }
 3172                }
 3173                if close_intent == CloseIntent::ReplaceWindow {
 3174                    _ = cx.update(|_window, cx| {
 3175                        let multi_workspace = cx
 3176                            .windows()
 3177                            .iter()
 3178                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 3179                            .next()
 3180                            .unwrap();
 3181                        let project = multi_workspace
 3182                            .read(cx)?
 3183                            .workspace()
 3184                            .read(cx)
 3185                            .project
 3186                            .clone();
 3187                        if project.read(cx).is_shared() {
 3188                            active_call.0.unshare_project(project, cx)?;
 3189                        }
 3190                        Ok::<_, anyhow::Error>(())
 3191                    });
 3192                }
 3193            }
 3194
 3195            let save_result = this
 3196                .update_in(cx, |this, window, cx| {
 3197                    this.save_all_internal(SaveIntent::Close, window, cx)
 3198                })?
 3199                .await;
 3200
 3201            // If we're not quitting, but closing, we remove the workspace from
 3202            // the current session.
 3203            if close_intent != CloseIntent::Quit
 3204                && !save_last_workspace
 3205                && save_result.as_ref().is_ok_and(|&res| res)
 3206            {
 3207                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 3208                    .await;
 3209            }
 3210
 3211            save_result
 3212        })
 3213    }
 3214
 3215    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 3216        self.save_all_internal(
 3217            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 3218            window,
 3219            cx,
 3220        )
 3221        .detach_and_log_err(cx);
 3222    }
 3223
 3224    fn send_keystrokes(
 3225        &mut self,
 3226        action: &SendKeystrokes,
 3227        window: &mut Window,
 3228        cx: &mut Context<Self>,
 3229    ) {
 3230        let keystrokes: Vec<Keystroke> = action
 3231            .0
 3232            .split(' ')
 3233            .flat_map(|k| Keystroke::parse(k).log_err())
 3234            .map(|k| {
 3235                cx.keyboard_mapper()
 3236                    .map_key_equivalent(k, false)
 3237                    .inner()
 3238                    .clone()
 3239            })
 3240            .collect();
 3241        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 3242    }
 3243
 3244    pub fn send_keystrokes_impl(
 3245        &mut self,
 3246        keystrokes: Vec<Keystroke>,
 3247        window: &mut Window,
 3248        cx: &mut Context<Self>,
 3249    ) -> Shared<Task<()>> {
 3250        let mut state = self.dispatching_keystrokes.borrow_mut();
 3251        if !state.dispatched.insert(keystrokes.clone()) {
 3252            cx.propagate();
 3253            return state.task.clone().unwrap();
 3254        }
 3255
 3256        state.queue.extend(keystrokes);
 3257
 3258        let keystrokes = self.dispatching_keystrokes.clone();
 3259        if state.task.is_none() {
 3260            state.task = Some(
 3261                window
 3262                    .spawn(cx, async move |cx| {
 3263                        // limit to 100 keystrokes to avoid infinite recursion.
 3264                        for _ in 0..100 {
 3265                            let keystroke = {
 3266                                let mut state = keystrokes.borrow_mut();
 3267                                let Some(keystroke) = state.queue.pop_front() else {
 3268                                    state.dispatched.clear();
 3269                                    state.task.take();
 3270                                    return;
 3271                                };
 3272                                keystroke
 3273                            };
 3274                            cx.update(|window, cx| {
 3275                                let focused = window.focused(cx);
 3276                                window.dispatch_keystroke(keystroke.clone(), cx);
 3277                                if window.focused(cx) != focused {
 3278                                    // dispatch_keystroke may cause the focus to change.
 3279                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3280                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 3281                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 3282                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3283                                    // )
 3284                                    window.draw(cx).clear();
 3285                                }
 3286                            })
 3287                            .ok();
 3288
 3289                            // Yield between synthetic keystrokes so deferred focus and
 3290                            // other effects can settle before dispatching the next key.
 3291                            yield_now().await;
 3292                        }
 3293
 3294                        *keystrokes.borrow_mut() = Default::default();
 3295                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3296                    })
 3297                    .shared(),
 3298            );
 3299        }
 3300        state.task.clone().unwrap()
 3301    }
 3302
 3303    pub fn save_for_root_removal(
 3304        &mut self,
 3305        window: &mut Window,
 3306        cx: &mut Context<Self>,
 3307    ) -> Task<Result<bool>> {
 3308        self.save_all_internal(SaveIntent::Close, window, cx)
 3309    }
 3310
 3311    fn save_all_internal(
 3312        &mut self,
 3313        mut save_intent: SaveIntent,
 3314        window: &mut Window,
 3315        cx: &mut Context<Self>,
 3316    ) -> Task<Result<bool>> {
 3317        if self.project.read(cx).is_disconnected(cx) {
 3318            return Task::ready(Ok(true));
 3319        }
 3320        let dirty_items = self
 3321            .panes
 3322            .iter()
 3323            .flat_map(|pane| {
 3324                pane.read(cx).items().filter_map(|item| {
 3325                    if item.is_dirty(cx) {
 3326                        item.tab_content_text(0, cx);
 3327                        Some((pane.downgrade(), item.boxed_clone()))
 3328                    } else {
 3329                        None
 3330                    }
 3331                })
 3332            })
 3333            .collect::<Vec<_>>();
 3334
 3335        let project = self.project.clone();
 3336        cx.spawn_in(window, async move |workspace, cx| {
 3337            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3338                let (serialize_tasks, remaining_dirty_items) =
 3339                    workspace.update_in(cx, |workspace, window, cx| {
 3340                        let mut remaining_dirty_items = Vec::new();
 3341                        let mut serialize_tasks = Vec::new();
 3342                        for (pane, item) in dirty_items {
 3343                            if let Some(task) = item
 3344                                .to_serializable_item_handle(cx)
 3345                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3346                            {
 3347                                serialize_tasks.push(task);
 3348                            } else {
 3349                                remaining_dirty_items.push((pane, item));
 3350                            }
 3351                        }
 3352                        (serialize_tasks, remaining_dirty_items)
 3353                    })?;
 3354
 3355                futures::future::try_join_all(serialize_tasks).await?;
 3356
 3357                if !remaining_dirty_items.is_empty() {
 3358                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3359                }
 3360
 3361                if remaining_dirty_items.len() > 1 {
 3362                    let answer = workspace.update_in(cx, |_, window, cx| {
 3363                        let detail = Pane::file_names_for_prompt(
 3364                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3365                            cx,
 3366                        );
 3367                        window.prompt(
 3368                            PromptLevel::Warning,
 3369                            "Do you want to save all changes in the following files?",
 3370                            Some(&detail),
 3371                            &["Save all", "Discard all", "Cancel"],
 3372                            cx,
 3373                        )
 3374                    })?;
 3375                    match answer.await.log_err() {
 3376                        Some(0) => save_intent = SaveIntent::SaveAll,
 3377                        Some(1) => save_intent = SaveIntent::Skip,
 3378                        Some(2) => return Ok(false),
 3379                        _ => {}
 3380                    }
 3381                }
 3382
 3383                remaining_dirty_items
 3384            } else {
 3385                dirty_items
 3386            };
 3387
 3388            for (pane, item) in dirty_items {
 3389                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3390                    (
 3391                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3392                        item.project_entry_ids(cx),
 3393                    )
 3394                })?;
 3395                if (singleton || !project_entry_ids.is_empty())
 3396                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3397                {
 3398                    return Ok(false);
 3399                }
 3400            }
 3401            Ok(true)
 3402        })
 3403    }
 3404
 3405    pub fn open_workspace_for_paths(
 3406        &mut self,
 3407        // replace_current_window: bool,
 3408        mut open_mode: OpenMode,
 3409        paths: Vec<PathBuf>,
 3410        window: &mut Window,
 3411        cx: &mut Context<Self>,
 3412    ) -> Task<Result<Entity<Workspace>>> {
 3413        let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
 3414        let is_remote = self.project.read(cx).is_via_collab();
 3415        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3416        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3417
 3418        let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
 3419        if workspace_is_empty {
 3420            open_mode = OpenMode::Activate;
 3421        }
 3422
 3423        let app_state = self.app_state.clone();
 3424
 3425        cx.spawn(async move |_, cx| {
 3426            let OpenResult { workspace, .. } = cx
 3427                .update(|cx| {
 3428                    open_paths(
 3429                        &paths,
 3430                        app_state,
 3431                        OpenOptions {
 3432                            requesting_window,
 3433                            open_mode,
 3434                            ..Default::default()
 3435                        },
 3436                        cx,
 3437                    )
 3438                })
 3439                .await?;
 3440            Ok(workspace)
 3441        })
 3442    }
 3443
 3444    #[allow(clippy::type_complexity)]
 3445    pub fn open_paths(
 3446        &mut self,
 3447        mut abs_paths: Vec<PathBuf>,
 3448        options: OpenOptions,
 3449        pane: Option<WeakEntity<Pane>>,
 3450        window: &mut Window,
 3451        cx: &mut Context<Self>,
 3452    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3453        let fs = self.app_state.fs.clone();
 3454
 3455        let caller_ordered_abs_paths = abs_paths.clone();
 3456
 3457        // Sort the paths to ensure we add worktrees for parents before their children.
 3458        abs_paths.sort_unstable();
 3459        cx.spawn_in(window, async move |this, cx| {
 3460            let mut tasks = Vec::with_capacity(abs_paths.len());
 3461
 3462            for abs_path in &abs_paths {
 3463                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3464                    OpenVisible::All => Some(true),
 3465                    OpenVisible::None => Some(false),
 3466                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3467                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3468                        Some(None) => Some(true),
 3469                        None => None,
 3470                    },
 3471                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3472                        Some(Some(metadata)) => Some(metadata.is_dir),
 3473                        Some(None) => Some(false),
 3474                        None => None,
 3475                    },
 3476                };
 3477                let project_path = match visible {
 3478                    Some(visible) => match this
 3479                        .update(cx, |this, cx| {
 3480                            Workspace::project_path_for_path(
 3481                                this.project.clone(),
 3482                                abs_path,
 3483                                visible,
 3484                                cx,
 3485                            )
 3486                        })
 3487                        .log_err()
 3488                    {
 3489                        Some(project_path) => project_path.await.log_err(),
 3490                        None => None,
 3491                    },
 3492                    None => None,
 3493                };
 3494
 3495                let this = this.clone();
 3496                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3497                let fs = fs.clone();
 3498                let pane = pane.clone();
 3499                let task = cx.spawn(async move |cx| {
 3500                    let (_worktree, project_path) = project_path?;
 3501                    if fs.is_dir(&abs_path).await {
 3502                        // Opening a directory should not race to update the active entry.
 3503                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3504                        None
 3505                    } else {
 3506                        Some(
 3507                            this.update_in(cx, |this, window, cx| {
 3508                                this.open_path(
 3509                                    project_path,
 3510                                    pane,
 3511                                    options.focus.unwrap_or(true),
 3512                                    window,
 3513                                    cx,
 3514                                )
 3515                            })
 3516                            .ok()?
 3517                            .await,
 3518                        )
 3519                    }
 3520                });
 3521                tasks.push(task);
 3522            }
 3523
 3524            let results = futures::future::join_all(tasks).await;
 3525
 3526            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3527            let mut winner: Option<(PathBuf, bool)> = None;
 3528            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3529                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3530                    if !metadata.is_dir {
 3531                        winner = Some((abs_path, false));
 3532                        break;
 3533                    }
 3534                    if winner.is_none() {
 3535                        winner = Some((abs_path, true));
 3536                    }
 3537                } else if winner.is_none() {
 3538                    winner = Some((abs_path, false));
 3539                }
 3540            }
 3541
 3542            // Compute the winner entry id on the foreground thread and emit once, after all
 3543            // paths finish opening. This avoids races between concurrently-opening paths
 3544            // (directories in particular) and makes the resulting project panel selection
 3545            // deterministic.
 3546            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3547                'emit_winner: {
 3548                    let winner_abs_path: Arc<Path> =
 3549                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3550
 3551                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3552                        OpenVisible::All => true,
 3553                        OpenVisible::None => false,
 3554                        OpenVisible::OnlyFiles => !winner_is_dir,
 3555                        OpenVisible::OnlyDirectories => winner_is_dir,
 3556                    };
 3557
 3558                    let Some(worktree_task) = this
 3559                        .update(cx, |workspace, cx| {
 3560                            workspace.project.update(cx, |project, cx| {
 3561                                project.find_or_create_worktree(
 3562                                    winner_abs_path.as_ref(),
 3563                                    visible,
 3564                                    cx,
 3565                                )
 3566                            })
 3567                        })
 3568                        .ok()
 3569                    else {
 3570                        break 'emit_winner;
 3571                    };
 3572
 3573                    let Ok((worktree, _)) = worktree_task.await else {
 3574                        break 'emit_winner;
 3575                    };
 3576
 3577                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3578                        let worktree = worktree.read(cx);
 3579                        let worktree_abs_path = worktree.abs_path();
 3580                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3581                            worktree.root_entry()
 3582                        } else {
 3583                            winner_abs_path
 3584                                .strip_prefix(worktree_abs_path.as_ref())
 3585                                .ok()
 3586                                .and_then(|relative_path| {
 3587                                    let relative_path =
 3588                                        RelPath::new(relative_path, PathStyle::local())
 3589                                            .log_err()?;
 3590                                    worktree.entry_for_path(&relative_path)
 3591                                })
 3592                        }?;
 3593                        Some(entry.id)
 3594                    }) else {
 3595                        break 'emit_winner;
 3596                    };
 3597
 3598                    this.update(cx, |workspace, cx| {
 3599                        workspace.project.update(cx, |_, cx| {
 3600                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3601                        });
 3602                    })
 3603                    .ok();
 3604                }
 3605            }
 3606
 3607            results
 3608        })
 3609    }
 3610
 3611    pub fn open_resolved_path(
 3612        &mut self,
 3613        path: ResolvedPath,
 3614        window: &mut Window,
 3615        cx: &mut Context<Self>,
 3616    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3617        match path {
 3618            ResolvedPath::ProjectPath { project_path, .. } => {
 3619                self.open_path(project_path, None, true, window, cx)
 3620            }
 3621            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3622                PathBuf::from(path),
 3623                OpenOptions {
 3624                    visible: Some(OpenVisible::None),
 3625                    ..Default::default()
 3626                },
 3627                window,
 3628                cx,
 3629            ),
 3630        }
 3631    }
 3632
 3633    pub fn absolute_path_of_worktree(
 3634        &self,
 3635        worktree_id: WorktreeId,
 3636        cx: &mut Context<Self>,
 3637    ) -> Option<PathBuf> {
 3638        self.project
 3639            .read(cx)
 3640            .worktree_for_id(worktree_id, cx)
 3641            // TODO: use `abs_path` or `root_dir`
 3642            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3643    }
 3644
 3645    pub fn add_folder_to_project(
 3646        &mut self,
 3647        _: &AddFolderToProject,
 3648        window: &mut Window,
 3649        cx: &mut Context<Self>,
 3650    ) {
 3651        let project = self.project.read(cx);
 3652        if project.is_via_collab() {
 3653            self.show_error(
 3654                &anyhow!("You cannot add folders to someone else's project"),
 3655                cx,
 3656            );
 3657            return;
 3658        }
 3659        let paths = self.prompt_for_open_path(
 3660            PathPromptOptions {
 3661                files: false,
 3662                directories: true,
 3663                multiple: true,
 3664                prompt: None,
 3665            },
 3666            DirectoryLister::Project(self.project.clone()),
 3667            window,
 3668            cx,
 3669        );
 3670        cx.spawn_in(window, async move |this, cx| {
 3671            if let Some(paths) = paths.await.log_err().flatten() {
 3672                let results = this
 3673                    .update_in(cx, |this, window, cx| {
 3674                        this.open_paths(
 3675                            paths,
 3676                            OpenOptions {
 3677                                visible: Some(OpenVisible::All),
 3678                                ..Default::default()
 3679                            },
 3680                            None,
 3681                            window,
 3682                            cx,
 3683                        )
 3684                    })?
 3685                    .await;
 3686                for result in results.into_iter().flatten() {
 3687                    result.log_err();
 3688                }
 3689            }
 3690            anyhow::Ok(())
 3691        })
 3692        .detach_and_log_err(cx);
 3693    }
 3694
 3695    pub fn project_path_for_path(
 3696        project: Entity<Project>,
 3697        abs_path: &Path,
 3698        visible: bool,
 3699        cx: &mut App,
 3700    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3701        let entry = project.update(cx, |project, cx| {
 3702            project.find_or_create_worktree(abs_path, visible, cx)
 3703        });
 3704        cx.spawn(async move |cx| {
 3705            let (worktree, path) = entry.await?;
 3706            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3707            Ok((worktree, ProjectPath { worktree_id, path }))
 3708        })
 3709    }
 3710
 3711    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3712        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3713    }
 3714
 3715    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3716        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3717    }
 3718
 3719    pub fn items_of_type<'a, T: Item>(
 3720        &'a self,
 3721        cx: &'a App,
 3722    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3723        self.panes
 3724            .iter()
 3725            .flat_map(|pane| pane.read(cx).items_of_type())
 3726    }
 3727
 3728    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3729        self.active_pane().read(cx).active_item()
 3730    }
 3731
 3732    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3733        let item = self.active_item(cx)?;
 3734        item.to_any_view().downcast::<I>().ok()
 3735    }
 3736
 3737    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3738        self.active_item(cx).and_then(|item| item.project_path(cx))
 3739    }
 3740
 3741    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3742        self.recent_navigation_history_iter(cx)
 3743            .filter_map(|(path, abs_path)| {
 3744                let worktree = self
 3745                    .project
 3746                    .read(cx)
 3747                    .worktree_for_id(path.worktree_id, cx)?;
 3748                if worktree.read(cx).is_visible() {
 3749                    abs_path
 3750                } else {
 3751                    None
 3752                }
 3753            })
 3754            .next()
 3755    }
 3756
 3757    pub fn save_active_item(
 3758        &mut self,
 3759        save_intent: SaveIntent,
 3760        window: &mut Window,
 3761        cx: &mut App,
 3762    ) -> Task<Result<()>> {
 3763        let project = self.project.clone();
 3764        let pane = self.active_pane();
 3765        let item = pane.read(cx).active_item();
 3766        let pane = pane.downgrade();
 3767
 3768        window.spawn(cx, async move |cx| {
 3769            if let Some(item) = item {
 3770                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3771                    .await
 3772                    .map(|_| ())
 3773            } else {
 3774                Ok(())
 3775            }
 3776        })
 3777    }
 3778
 3779    pub fn close_inactive_items_and_panes(
 3780        &mut self,
 3781        action: &CloseInactiveTabsAndPanes,
 3782        window: &mut Window,
 3783        cx: &mut Context<Self>,
 3784    ) {
 3785        if let Some(task) = self.close_all_internal(
 3786            true,
 3787            action.save_intent.unwrap_or(SaveIntent::Close),
 3788            window,
 3789            cx,
 3790        ) {
 3791            task.detach_and_log_err(cx)
 3792        }
 3793    }
 3794
 3795    pub fn close_all_items_and_panes(
 3796        &mut self,
 3797        action: &CloseAllItemsAndPanes,
 3798        window: &mut Window,
 3799        cx: &mut Context<Self>,
 3800    ) {
 3801        if let Some(task) = self.close_all_internal(
 3802            false,
 3803            action.save_intent.unwrap_or(SaveIntent::Close),
 3804            window,
 3805            cx,
 3806        ) {
 3807            task.detach_and_log_err(cx)
 3808        }
 3809    }
 3810
 3811    /// Closes the active item across all panes.
 3812    pub fn close_item_in_all_panes(
 3813        &mut self,
 3814        action: &CloseItemInAllPanes,
 3815        window: &mut Window,
 3816        cx: &mut Context<Self>,
 3817    ) {
 3818        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3819            return;
 3820        };
 3821
 3822        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3823        let close_pinned = action.close_pinned;
 3824
 3825        if let Some(project_path) = active_item.project_path(cx) {
 3826            self.close_items_with_project_path(
 3827                &project_path,
 3828                save_intent,
 3829                close_pinned,
 3830                window,
 3831                cx,
 3832            );
 3833        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3834            let item_id = active_item.item_id();
 3835            self.active_pane().update(cx, |pane, cx| {
 3836                pane.close_item_by_id(item_id, save_intent, window, cx)
 3837                    .detach_and_log_err(cx);
 3838            });
 3839        }
 3840    }
 3841
 3842    /// Closes all items with the given project path across all panes.
 3843    pub fn close_items_with_project_path(
 3844        &mut self,
 3845        project_path: &ProjectPath,
 3846        save_intent: SaveIntent,
 3847        close_pinned: bool,
 3848        window: &mut Window,
 3849        cx: &mut Context<Self>,
 3850    ) {
 3851        let panes = self.panes().to_vec();
 3852        for pane in panes {
 3853            pane.update(cx, |pane, cx| {
 3854                pane.close_items_for_project_path(
 3855                    project_path,
 3856                    save_intent,
 3857                    close_pinned,
 3858                    window,
 3859                    cx,
 3860                )
 3861                .detach_and_log_err(cx);
 3862            });
 3863        }
 3864    }
 3865
 3866    fn close_all_internal(
 3867        &mut self,
 3868        retain_active_pane: bool,
 3869        save_intent: SaveIntent,
 3870        window: &mut Window,
 3871        cx: &mut Context<Self>,
 3872    ) -> Option<Task<Result<()>>> {
 3873        let current_pane = self.active_pane();
 3874
 3875        let mut tasks = Vec::new();
 3876
 3877        if retain_active_pane {
 3878            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3879                pane.close_other_items(
 3880                    &CloseOtherItems {
 3881                        save_intent: None,
 3882                        close_pinned: false,
 3883                    },
 3884                    None,
 3885                    window,
 3886                    cx,
 3887                )
 3888            });
 3889
 3890            tasks.push(current_pane_close);
 3891        }
 3892
 3893        for pane in self.panes() {
 3894            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3895                continue;
 3896            }
 3897
 3898            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3899                pane.close_all_items(
 3900                    &CloseAllItems {
 3901                        save_intent: Some(save_intent),
 3902                        close_pinned: false,
 3903                    },
 3904                    window,
 3905                    cx,
 3906                )
 3907            });
 3908
 3909            tasks.push(close_pane_items)
 3910        }
 3911
 3912        if tasks.is_empty() {
 3913            None
 3914        } else {
 3915            Some(cx.spawn_in(window, async move |_, _| {
 3916                for task in tasks {
 3917                    task.await?
 3918                }
 3919                Ok(())
 3920            }))
 3921        }
 3922    }
 3923
 3924    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3925        self.dock_at_position(position).read(cx).is_open()
 3926    }
 3927
 3928    pub fn toggle_dock(
 3929        &mut self,
 3930        dock_side: DockPosition,
 3931        window: &mut Window,
 3932        cx: &mut Context<Self>,
 3933    ) {
 3934        let mut focus_center = false;
 3935        let mut reveal_dock = false;
 3936
 3937        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3938        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3939
 3940        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3941            telemetry::event!(
 3942                "Panel Button Clicked",
 3943                name = panel.persistent_name(),
 3944                toggle_state = !was_visible
 3945            );
 3946        }
 3947        if was_visible {
 3948            self.save_open_dock_positions(cx);
 3949        }
 3950
 3951        let dock = self.dock_at_position(dock_side);
 3952        dock.update(cx, |dock, cx| {
 3953            dock.set_open(!was_visible, window, cx);
 3954
 3955            if dock.active_panel().is_none() {
 3956                let Some(panel_ix) = dock
 3957                    .first_enabled_panel_idx(cx)
 3958                    .log_with_level(log::Level::Info)
 3959                else {
 3960                    return;
 3961                };
 3962                dock.activate_panel(panel_ix, window, cx);
 3963            }
 3964
 3965            if let Some(active_panel) = dock.active_panel() {
 3966                if was_visible {
 3967                    if active_panel
 3968                        .panel_focus_handle(cx)
 3969                        .contains_focused(window, cx)
 3970                    {
 3971                        focus_center = true;
 3972                    }
 3973                } else {
 3974                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3975                    window.focus(focus_handle, cx);
 3976                    reveal_dock = true;
 3977                }
 3978            }
 3979        });
 3980
 3981        if reveal_dock {
 3982            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3983        }
 3984
 3985        if focus_center {
 3986            self.active_pane
 3987                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3988        }
 3989
 3990        cx.notify();
 3991        self.serialize_workspace(window, cx);
 3992    }
 3993
 3994    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3995        self.all_docks().into_iter().find(|&dock| {
 3996            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3997        })
 3998    }
 3999
 4000    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 4001        if let Some(dock) = self.active_dock(window, cx).cloned() {
 4002            self.save_open_dock_positions(cx);
 4003            dock.update(cx, |dock, cx| {
 4004                dock.set_open(false, window, cx);
 4005            });
 4006            return true;
 4007        }
 4008        false
 4009    }
 4010
 4011    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4012        self.save_open_dock_positions(cx);
 4013        for dock in self.all_docks() {
 4014            dock.update(cx, |dock, cx| {
 4015                dock.set_open(false, window, cx);
 4016            });
 4017        }
 4018
 4019        cx.focus_self(window);
 4020        cx.notify();
 4021        self.serialize_workspace(window, cx);
 4022    }
 4023
 4024    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 4025        self.all_docks()
 4026            .into_iter()
 4027            .filter_map(|dock| {
 4028                let dock_ref = dock.read(cx);
 4029                if dock_ref.is_open() {
 4030                    Some(dock_ref.position())
 4031                } else {
 4032                    None
 4033                }
 4034            })
 4035            .collect()
 4036    }
 4037
 4038    /// Saves the positions of currently open docks.
 4039    ///
 4040    /// Updates `last_open_dock_positions` with positions of all currently open
 4041    /// docks, to later be restored by the 'Toggle All Docks' action.
 4042    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 4043        let open_dock_positions = self.get_open_dock_positions(cx);
 4044        if !open_dock_positions.is_empty() {
 4045            self.last_open_dock_positions = open_dock_positions;
 4046        }
 4047    }
 4048
 4049    /// Toggles all docks between open and closed states.
 4050    ///
 4051    /// If any docks are open, closes all and remembers their positions. If all
 4052    /// docks are closed, restores the last remembered dock configuration.
 4053    fn toggle_all_docks(
 4054        &mut self,
 4055        _: &ToggleAllDocks,
 4056        window: &mut Window,
 4057        cx: &mut Context<Self>,
 4058    ) {
 4059        let open_dock_positions = self.get_open_dock_positions(cx);
 4060
 4061        if !open_dock_positions.is_empty() {
 4062            self.close_all_docks(window, cx);
 4063        } else if !self.last_open_dock_positions.is_empty() {
 4064            self.restore_last_open_docks(window, cx);
 4065        }
 4066    }
 4067
 4068    /// Reopens docks from the most recently remembered configuration.
 4069    ///
 4070    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 4071    /// and clears the stored positions.
 4072    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4073        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 4074
 4075        for position in positions_to_open {
 4076            let dock = self.dock_at_position(position);
 4077            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 4078        }
 4079
 4080        cx.focus_self(window);
 4081        cx.notify();
 4082        self.serialize_workspace(window, cx);
 4083    }
 4084
 4085    /// Transfer focus to the panel of the given type.
 4086    pub fn focus_panel<T: Panel>(
 4087        &mut self,
 4088        window: &mut Window,
 4089        cx: &mut Context<Self>,
 4090    ) -> Option<Entity<T>> {
 4091        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 4092        panel.to_any().downcast().ok()
 4093    }
 4094
 4095    /// Focus the panel of the given type if it isn't already focused. If it is
 4096    /// already focused, then transfer focus back to the workspace center.
 4097    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 4098    /// panel when transferring focus back to the center.
 4099    pub fn toggle_panel_focus<T: Panel>(
 4100        &mut self,
 4101        window: &mut Window,
 4102        cx: &mut Context<Self>,
 4103    ) -> bool {
 4104        let mut did_focus_panel = false;
 4105        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 4106            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 4107            did_focus_panel
 4108        });
 4109
 4110        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 4111            self.close_panel::<T>(window, cx);
 4112        }
 4113
 4114        telemetry::event!(
 4115            "Panel Button Clicked",
 4116            name = T::persistent_name(),
 4117            toggle_state = did_focus_panel
 4118        );
 4119
 4120        did_focus_panel
 4121    }
 4122
 4123    pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4124        if let Some(item) = self.active_item(cx) {
 4125            item.item_focus_handle(cx).focus(window, cx);
 4126        } else {
 4127            log::error!("Could not find a focus target when switching focus to the center panes",);
 4128        }
 4129    }
 4130
 4131    pub fn activate_panel_for_proto_id(
 4132        &mut self,
 4133        panel_id: PanelId,
 4134        window: &mut Window,
 4135        cx: &mut Context<Self>,
 4136    ) -> Option<Arc<dyn PanelHandle>> {
 4137        let mut panel = None;
 4138        for dock in self.all_docks() {
 4139            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 4140                panel = dock.update(cx, |dock, cx| {
 4141                    dock.activate_panel(panel_index, window, cx);
 4142                    dock.set_open(true, window, cx);
 4143                    dock.active_panel().cloned()
 4144                });
 4145                break;
 4146            }
 4147        }
 4148
 4149        if panel.is_some() {
 4150            cx.notify();
 4151            self.serialize_workspace(window, cx);
 4152        }
 4153
 4154        panel
 4155    }
 4156
 4157    /// Focus or unfocus the given panel type, depending on the given callback.
 4158    fn focus_or_unfocus_panel<T: Panel>(
 4159        &mut self,
 4160        window: &mut Window,
 4161        cx: &mut Context<Self>,
 4162        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 4163    ) -> Option<Arc<dyn PanelHandle>> {
 4164        let mut result_panel = None;
 4165        let mut serialize = false;
 4166        for dock in self.all_docks() {
 4167            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4168                let mut focus_center = false;
 4169                let panel = dock.update(cx, |dock, cx| {
 4170                    dock.activate_panel(panel_index, window, cx);
 4171
 4172                    let panel = dock.active_panel().cloned();
 4173                    if let Some(panel) = panel.as_ref() {
 4174                        if should_focus(&**panel, window, cx) {
 4175                            dock.set_open(true, window, cx);
 4176                            panel.panel_focus_handle(cx).focus(window, cx);
 4177                        } else {
 4178                            focus_center = true;
 4179                        }
 4180                    }
 4181                    panel
 4182                });
 4183
 4184                if focus_center {
 4185                    self.active_pane
 4186                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4187                }
 4188
 4189                result_panel = panel;
 4190                serialize = true;
 4191                break;
 4192            }
 4193        }
 4194
 4195        if serialize {
 4196            self.serialize_workspace(window, cx);
 4197        }
 4198
 4199        cx.notify();
 4200        result_panel
 4201    }
 4202
 4203    /// Open the panel of the given type
 4204    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4205        for dock in self.all_docks() {
 4206            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4207                dock.update(cx, |dock, cx| {
 4208                    dock.activate_panel(panel_index, window, cx);
 4209                    dock.set_open(true, window, cx);
 4210                });
 4211            }
 4212        }
 4213    }
 4214
 4215    /// Open the panel of the given type, dismissing any zoomed items that
 4216    /// would obscure it (e.g. a zoomed terminal).
 4217    pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4218        let dock_position = self.all_docks().iter().find_map(|dock| {
 4219            let dock = dock.read(cx);
 4220            dock.panel_index_for_type::<T>().map(|_| dock.position())
 4221        });
 4222        self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
 4223        self.open_panel::<T>(window, cx);
 4224    }
 4225
 4226    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 4227        for dock in self.all_docks().iter() {
 4228            dock.update(cx, |dock, cx| {
 4229                if dock.panel::<T>().is_some() {
 4230                    dock.set_open(false, window, cx)
 4231                }
 4232            })
 4233        }
 4234    }
 4235
 4236    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 4237        self.all_docks()
 4238            .iter()
 4239            .find_map(|dock| dock.read(cx).panel::<T>())
 4240    }
 4241
 4242    fn dismiss_zoomed_items_to_reveal(
 4243        &mut self,
 4244        dock_to_reveal: Option<DockPosition>,
 4245        window: &mut Window,
 4246        cx: &mut Context<Self>,
 4247    ) {
 4248        // If a center pane is zoomed, unzoom it.
 4249        for pane in &self.panes {
 4250            if pane != &self.active_pane || dock_to_reveal.is_some() {
 4251                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4252            }
 4253        }
 4254
 4255        // If another dock is zoomed, hide it.
 4256        let mut focus_center = false;
 4257        for dock in self.all_docks() {
 4258            dock.update(cx, |dock, cx| {
 4259                if Some(dock.position()) != dock_to_reveal
 4260                    && let Some(panel) = dock.active_panel()
 4261                    && panel.is_zoomed(window, cx)
 4262                {
 4263                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 4264                    dock.set_open(false, window, cx);
 4265                }
 4266            });
 4267        }
 4268
 4269        if focus_center {
 4270            self.active_pane
 4271                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4272        }
 4273
 4274        if self.zoomed_position != dock_to_reveal {
 4275            self.zoomed = None;
 4276            self.zoomed_position = None;
 4277            cx.emit(Event::ZoomChanged);
 4278        }
 4279
 4280        cx.notify();
 4281    }
 4282
 4283    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4284        let pane = cx.new(|cx| {
 4285            let mut pane = Pane::new(
 4286                self.weak_handle(),
 4287                self.project.clone(),
 4288                self.pane_history_timestamp.clone(),
 4289                None,
 4290                NewFile.boxed_clone(),
 4291                true,
 4292                window,
 4293                cx,
 4294            );
 4295            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4296            pane
 4297        });
 4298        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4299            .detach();
 4300        self.panes.push(pane.clone());
 4301
 4302        window.focus(&pane.focus_handle(cx), cx);
 4303
 4304        cx.emit(Event::PaneAdded(pane.clone()));
 4305        pane
 4306    }
 4307
 4308    pub fn add_item_to_center(
 4309        &mut self,
 4310        item: Box<dyn ItemHandle>,
 4311        window: &mut Window,
 4312        cx: &mut Context<Self>,
 4313    ) -> bool {
 4314        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4315            if let Some(center_pane) = center_pane.upgrade() {
 4316                center_pane.update(cx, |pane, cx| {
 4317                    pane.add_item(item, true, true, None, window, cx)
 4318                });
 4319                true
 4320            } else {
 4321                false
 4322            }
 4323        } else {
 4324            false
 4325        }
 4326    }
 4327
 4328    pub fn add_item_to_active_pane(
 4329        &mut self,
 4330        item: Box<dyn ItemHandle>,
 4331        destination_index: Option<usize>,
 4332        focus_item: bool,
 4333        window: &mut Window,
 4334        cx: &mut App,
 4335    ) {
 4336        self.add_item(
 4337            self.active_pane.clone(),
 4338            item,
 4339            destination_index,
 4340            false,
 4341            focus_item,
 4342            window,
 4343            cx,
 4344        )
 4345    }
 4346
 4347    pub fn add_item(
 4348        &mut self,
 4349        pane: Entity<Pane>,
 4350        item: Box<dyn ItemHandle>,
 4351        destination_index: Option<usize>,
 4352        activate_pane: bool,
 4353        focus_item: bool,
 4354        window: &mut Window,
 4355        cx: &mut App,
 4356    ) {
 4357        pane.update(cx, |pane, cx| {
 4358            pane.add_item(
 4359                item,
 4360                activate_pane,
 4361                focus_item,
 4362                destination_index,
 4363                window,
 4364                cx,
 4365            )
 4366        });
 4367    }
 4368
 4369    pub fn split_item(
 4370        &mut self,
 4371        split_direction: SplitDirection,
 4372        item: Box<dyn ItemHandle>,
 4373        window: &mut Window,
 4374        cx: &mut Context<Self>,
 4375    ) {
 4376        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4377        self.add_item(new_pane, item, None, true, true, window, cx);
 4378    }
 4379
 4380    pub fn open_abs_path(
 4381        &mut self,
 4382        abs_path: PathBuf,
 4383        options: OpenOptions,
 4384        window: &mut Window,
 4385        cx: &mut Context<Self>,
 4386    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4387        cx.spawn_in(window, async move |workspace, cx| {
 4388            let open_paths_task_result = workspace
 4389                .update_in(cx, |workspace, window, cx| {
 4390                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4391                })
 4392                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4393                .await;
 4394            anyhow::ensure!(
 4395                open_paths_task_result.len() == 1,
 4396                "open abs path {abs_path:?} task returned incorrect number of results"
 4397            );
 4398            match open_paths_task_result
 4399                .into_iter()
 4400                .next()
 4401                .expect("ensured single task result")
 4402            {
 4403                Some(open_result) => {
 4404                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4405                }
 4406                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4407            }
 4408        })
 4409    }
 4410
 4411    pub fn split_abs_path(
 4412        &mut self,
 4413        abs_path: PathBuf,
 4414        visible: bool,
 4415        window: &mut Window,
 4416        cx: &mut Context<Self>,
 4417    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4418        let project_path_task =
 4419            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4420        cx.spawn_in(window, async move |this, cx| {
 4421            let (_, path) = project_path_task.await?;
 4422            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4423                .await
 4424        })
 4425    }
 4426
 4427    pub fn open_path(
 4428        &mut self,
 4429        path: impl Into<ProjectPath>,
 4430        pane: Option<WeakEntity<Pane>>,
 4431        focus_item: bool,
 4432        window: &mut Window,
 4433        cx: &mut App,
 4434    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4435        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4436    }
 4437
 4438    pub fn open_path_preview(
 4439        &mut self,
 4440        path: impl Into<ProjectPath>,
 4441        pane: Option<WeakEntity<Pane>>,
 4442        focus_item: bool,
 4443        allow_preview: bool,
 4444        activate: bool,
 4445        window: &mut Window,
 4446        cx: &mut App,
 4447    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4448        let pane = pane.unwrap_or_else(|| {
 4449            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4450                self.panes
 4451                    .first()
 4452                    .expect("There must be an active pane")
 4453                    .downgrade()
 4454            })
 4455        });
 4456
 4457        let project_path = path.into();
 4458        let task = self.load_path(project_path.clone(), window, cx);
 4459        window.spawn(cx, async move |cx| {
 4460            let (project_entry_id, build_item) = task.await?;
 4461
 4462            pane.update_in(cx, |pane, window, cx| {
 4463                pane.open_item(
 4464                    project_entry_id,
 4465                    project_path,
 4466                    focus_item,
 4467                    allow_preview,
 4468                    activate,
 4469                    None,
 4470                    window,
 4471                    cx,
 4472                    build_item,
 4473                )
 4474            })
 4475        })
 4476    }
 4477
 4478    pub fn split_path(
 4479        &mut self,
 4480        path: impl Into<ProjectPath>,
 4481        window: &mut Window,
 4482        cx: &mut Context<Self>,
 4483    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4484        self.split_path_preview(path, false, None, window, cx)
 4485    }
 4486
 4487    pub fn split_path_preview(
 4488        &mut self,
 4489        path: impl Into<ProjectPath>,
 4490        allow_preview: bool,
 4491        split_direction: Option<SplitDirection>,
 4492        window: &mut Window,
 4493        cx: &mut Context<Self>,
 4494    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4495        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4496            self.panes
 4497                .first()
 4498                .expect("There must be an active pane")
 4499                .downgrade()
 4500        });
 4501
 4502        if let Member::Pane(center_pane) = &self.center.root
 4503            && center_pane.read(cx).items_len() == 0
 4504        {
 4505            return self.open_path(path, Some(pane), true, window, cx);
 4506        }
 4507
 4508        let project_path = path.into();
 4509        let task = self.load_path(project_path.clone(), window, cx);
 4510        cx.spawn_in(window, async move |this, cx| {
 4511            let (project_entry_id, build_item) = task.await?;
 4512            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4513                let pane = pane.upgrade()?;
 4514                let new_pane = this.split_pane(
 4515                    pane,
 4516                    split_direction.unwrap_or(SplitDirection::Right),
 4517                    window,
 4518                    cx,
 4519                );
 4520                new_pane.update(cx, |new_pane, cx| {
 4521                    Some(new_pane.open_item(
 4522                        project_entry_id,
 4523                        project_path,
 4524                        true,
 4525                        allow_preview,
 4526                        true,
 4527                        None,
 4528                        window,
 4529                        cx,
 4530                        build_item,
 4531                    ))
 4532                })
 4533            })
 4534            .map(|option| option.context("pane was dropped"))?
 4535        })
 4536    }
 4537
 4538    fn load_path(
 4539        &mut self,
 4540        path: ProjectPath,
 4541        window: &mut Window,
 4542        cx: &mut App,
 4543    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4544        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4545        registry.open_path(self.project(), &path, window, cx)
 4546    }
 4547
 4548    pub fn find_project_item<T>(
 4549        &self,
 4550        pane: &Entity<Pane>,
 4551        project_item: &Entity<T::Item>,
 4552        cx: &App,
 4553    ) -> Option<Entity<T>>
 4554    where
 4555        T: ProjectItem,
 4556    {
 4557        use project::ProjectItem as _;
 4558        let project_item = project_item.read(cx);
 4559        let entry_id = project_item.entry_id(cx);
 4560        let project_path = project_item.project_path(cx);
 4561
 4562        let mut item = None;
 4563        if let Some(entry_id) = entry_id {
 4564            item = pane.read(cx).item_for_entry(entry_id, cx);
 4565        }
 4566        if item.is_none()
 4567            && let Some(project_path) = project_path
 4568        {
 4569            item = pane.read(cx).item_for_path(project_path, cx);
 4570        }
 4571
 4572        item.and_then(|item| item.downcast::<T>())
 4573    }
 4574
 4575    pub fn is_project_item_open<T>(
 4576        &self,
 4577        pane: &Entity<Pane>,
 4578        project_item: &Entity<T::Item>,
 4579        cx: &App,
 4580    ) -> bool
 4581    where
 4582        T: ProjectItem,
 4583    {
 4584        self.find_project_item::<T>(pane, project_item, cx)
 4585            .is_some()
 4586    }
 4587
 4588    pub fn open_project_item<T>(
 4589        &mut self,
 4590        pane: Entity<Pane>,
 4591        project_item: Entity<T::Item>,
 4592        activate_pane: bool,
 4593        focus_item: bool,
 4594        keep_old_preview: bool,
 4595        allow_new_preview: bool,
 4596        window: &mut Window,
 4597        cx: &mut Context<Self>,
 4598    ) -> Entity<T>
 4599    where
 4600        T: ProjectItem,
 4601    {
 4602        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4603
 4604        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4605            if !keep_old_preview
 4606                && let Some(old_id) = old_item_id
 4607                && old_id != item.item_id()
 4608            {
 4609                // switching to a different item, so unpreview old active item
 4610                pane.update(cx, |pane, _| {
 4611                    pane.unpreview_item_if_preview(old_id);
 4612                });
 4613            }
 4614
 4615            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4616            if !allow_new_preview {
 4617                pane.update(cx, |pane, _| {
 4618                    pane.unpreview_item_if_preview(item.item_id());
 4619                });
 4620            }
 4621            return item;
 4622        }
 4623
 4624        let item = pane.update(cx, |pane, cx| {
 4625            cx.new(|cx| {
 4626                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4627            })
 4628        });
 4629        let mut destination_index = None;
 4630        pane.update(cx, |pane, cx| {
 4631            if !keep_old_preview && let Some(old_id) = old_item_id {
 4632                pane.unpreview_item_if_preview(old_id);
 4633            }
 4634            if allow_new_preview {
 4635                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4636            }
 4637        });
 4638
 4639        self.add_item(
 4640            pane,
 4641            Box::new(item.clone()),
 4642            destination_index,
 4643            activate_pane,
 4644            focus_item,
 4645            window,
 4646            cx,
 4647        );
 4648        item
 4649    }
 4650
 4651    pub fn open_shared_screen(
 4652        &mut self,
 4653        peer_id: PeerId,
 4654        window: &mut Window,
 4655        cx: &mut Context<Self>,
 4656    ) {
 4657        if let Some(shared_screen) =
 4658            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4659        {
 4660            self.active_pane.update(cx, |pane, cx| {
 4661                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4662            });
 4663        }
 4664    }
 4665
 4666    pub fn activate_item(
 4667        &mut self,
 4668        item: &dyn ItemHandle,
 4669        activate_pane: bool,
 4670        focus_item: bool,
 4671        window: &mut Window,
 4672        cx: &mut App,
 4673    ) -> bool {
 4674        let result = self.panes.iter().find_map(|pane| {
 4675            pane.read(cx)
 4676                .index_for_item(item)
 4677                .map(|ix| (pane.clone(), ix))
 4678        });
 4679        if let Some((pane, ix)) = result {
 4680            pane.update(cx, |pane, cx| {
 4681                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4682            });
 4683            true
 4684        } else {
 4685            false
 4686        }
 4687    }
 4688
 4689    fn activate_pane_at_index(
 4690        &mut self,
 4691        action: &ActivatePane,
 4692        window: &mut Window,
 4693        cx: &mut Context<Self>,
 4694    ) {
 4695        let panes = self.center.panes();
 4696        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4697            window.focus(&pane.focus_handle(cx), cx);
 4698        } else {
 4699            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4700                .detach();
 4701        }
 4702    }
 4703
 4704    fn move_item_to_pane_at_index(
 4705        &mut self,
 4706        action: &MoveItemToPane,
 4707        window: &mut Window,
 4708        cx: &mut Context<Self>,
 4709    ) {
 4710        let panes = self.center.panes();
 4711        let destination = match panes.get(action.destination) {
 4712            Some(&destination) => destination.clone(),
 4713            None => {
 4714                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4715                    return;
 4716                }
 4717                let direction = SplitDirection::Right;
 4718                let split_off_pane = self
 4719                    .find_pane_in_direction(direction, cx)
 4720                    .unwrap_or_else(|| self.active_pane.clone());
 4721                let new_pane = self.add_pane(window, cx);
 4722                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4723                new_pane
 4724            }
 4725        };
 4726
 4727        if action.clone {
 4728            if self
 4729                .active_pane
 4730                .read(cx)
 4731                .active_item()
 4732                .is_some_and(|item| item.can_split(cx))
 4733            {
 4734                clone_active_item(
 4735                    self.database_id(),
 4736                    &self.active_pane,
 4737                    &destination,
 4738                    action.focus,
 4739                    window,
 4740                    cx,
 4741                );
 4742                return;
 4743            }
 4744        }
 4745        move_active_item(
 4746            &self.active_pane,
 4747            &destination,
 4748            action.focus,
 4749            true,
 4750            window,
 4751            cx,
 4752        )
 4753    }
 4754
 4755    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4756        let panes = self.center.panes();
 4757        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4758            let next_ix = (ix + 1) % panes.len();
 4759            let next_pane = panes[next_ix].clone();
 4760            window.focus(&next_pane.focus_handle(cx), cx);
 4761        }
 4762    }
 4763
 4764    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4765        let panes = self.center.panes();
 4766        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4767            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4768            let prev_pane = panes[prev_ix].clone();
 4769            window.focus(&prev_pane.focus_handle(cx), cx);
 4770        }
 4771    }
 4772
 4773    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4774        let last_pane = self.center.last_pane();
 4775        window.focus(&last_pane.focus_handle(cx), cx);
 4776    }
 4777
 4778    pub fn activate_pane_in_direction(
 4779        &mut self,
 4780        direction: SplitDirection,
 4781        window: &mut Window,
 4782        cx: &mut App,
 4783    ) {
 4784        use ActivateInDirectionTarget as Target;
 4785        enum Origin {
 4786            Sidebar,
 4787            LeftDock,
 4788            RightDock,
 4789            BottomDock,
 4790            Center,
 4791        }
 4792
 4793        let origin: Origin = if self
 4794            .sidebar_focus_handle
 4795            .as_ref()
 4796            .is_some_and(|h| h.contains_focused(window, cx))
 4797        {
 4798            Origin::Sidebar
 4799        } else {
 4800            [
 4801                (&self.left_dock, Origin::LeftDock),
 4802                (&self.right_dock, Origin::RightDock),
 4803                (&self.bottom_dock, Origin::BottomDock),
 4804            ]
 4805            .into_iter()
 4806            .find_map(|(dock, origin)| {
 4807                if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4808                    Some(origin)
 4809                } else {
 4810                    None
 4811                }
 4812            })
 4813            .unwrap_or(Origin::Center)
 4814        };
 4815
 4816        let get_last_active_pane = || {
 4817            let pane = self
 4818                .last_active_center_pane
 4819                .clone()
 4820                .unwrap_or_else(|| {
 4821                    self.panes
 4822                        .first()
 4823                        .expect("There must be an active pane")
 4824                        .downgrade()
 4825                })
 4826                .upgrade()?;
 4827            (pane.read(cx).items_len() != 0).then_some(pane)
 4828        };
 4829
 4830        let try_dock =
 4831            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4832
 4833        let sidebar_target = self
 4834            .sidebar_focus_handle
 4835            .as_ref()
 4836            .map(|h| Target::Sidebar(h.clone()));
 4837
 4838        let target = match (origin, direction) {
 4839            // From the sidebar, only Right navigates into the workspace.
 4840            (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
 4841                .or_else(|| get_last_active_pane().map(Target::Pane))
 4842                .or_else(|| try_dock(&self.bottom_dock))
 4843                .or_else(|| try_dock(&self.right_dock)),
 4844
 4845            (Origin::Sidebar, _) => None,
 4846
 4847            // We're in the center, so we first try to go to a different pane,
 4848            // otherwise try to go to a dock.
 4849            (Origin::Center, direction) => {
 4850                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4851                    Some(Target::Pane(pane))
 4852                } else {
 4853                    match direction {
 4854                        SplitDirection::Up => None,
 4855                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4856                        SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
 4857                        SplitDirection::Right => try_dock(&self.right_dock),
 4858                    }
 4859                }
 4860            }
 4861
 4862            (Origin::LeftDock, SplitDirection::Right) => {
 4863                if let Some(last_active_pane) = get_last_active_pane() {
 4864                    Some(Target::Pane(last_active_pane))
 4865                } else {
 4866                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4867                }
 4868            }
 4869
 4870            (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
 4871
 4872            (Origin::LeftDock, SplitDirection::Down)
 4873            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4874
 4875            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4876            (Origin::BottomDock, SplitDirection::Left) => {
 4877                try_dock(&self.left_dock).or(sidebar_target)
 4878            }
 4879            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4880
 4881            (Origin::RightDock, SplitDirection::Left) => {
 4882                if let Some(last_active_pane) = get_last_active_pane() {
 4883                    Some(Target::Pane(last_active_pane))
 4884                } else {
 4885                    try_dock(&self.bottom_dock)
 4886                        .or_else(|| try_dock(&self.left_dock))
 4887                        .or(sidebar_target)
 4888                }
 4889            }
 4890
 4891            _ => None,
 4892        };
 4893
 4894        match target {
 4895            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4896                let pane = pane.read(cx);
 4897                if let Some(item) = pane.active_item() {
 4898                    item.item_focus_handle(cx).focus(window, cx);
 4899                } else {
 4900                    log::error!(
 4901                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4902                    );
 4903                }
 4904            }
 4905            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4906                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4907                window.defer(cx, move |window, cx| {
 4908                    let dock = dock.read(cx);
 4909                    if let Some(panel) = dock.active_panel() {
 4910                        panel.panel_focus_handle(cx).focus(window, cx);
 4911                    } else {
 4912                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4913                    }
 4914                })
 4915            }
 4916            Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
 4917                focus_handle.focus(window, cx);
 4918            }
 4919            None => {}
 4920        }
 4921    }
 4922
 4923    pub fn move_item_to_pane_in_direction(
 4924        &mut self,
 4925        action: &MoveItemToPaneInDirection,
 4926        window: &mut Window,
 4927        cx: &mut Context<Self>,
 4928    ) {
 4929        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4930            Some(destination) => destination,
 4931            None => {
 4932                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4933                    return;
 4934                }
 4935                let new_pane = self.add_pane(window, cx);
 4936                self.center
 4937                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4938                new_pane
 4939            }
 4940        };
 4941
 4942        if action.clone {
 4943            if self
 4944                .active_pane
 4945                .read(cx)
 4946                .active_item()
 4947                .is_some_and(|item| item.can_split(cx))
 4948            {
 4949                clone_active_item(
 4950                    self.database_id(),
 4951                    &self.active_pane,
 4952                    &destination,
 4953                    action.focus,
 4954                    window,
 4955                    cx,
 4956                );
 4957                return;
 4958            }
 4959        }
 4960        move_active_item(
 4961            &self.active_pane,
 4962            &destination,
 4963            action.focus,
 4964            true,
 4965            window,
 4966            cx,
 4967        );
 4968    }
 4969
 4970    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4971        self.center.bounding_box_for_pane(pane)
 4972    }
 4973
 4974    pub fn find_pane_in_direction(
 4975        &mut self,
 4976        direction: SplitDirection,
 4977        cx: &App,
 4978    ) -> Option<Entity<Pane>> {
 4979        self.center
 4980            .find_pane_in_direction(&self.active_pane, direction, cx)
 4981            .cloned()
 4982    }
 4983
 4984    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4985        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4986            self.center.swap(&self.active_pane, &to, cx);
 4987            cx.notify();
 4988        }
 4989    }
 4990
 4991    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4992        if self
 4993            .center
 4994            .move_to_border(&self.active_pane, direction, cx)
 4995            .unwrap()
 4996        {
 4997            cx.notify();
 4998        }
 4999    }
 5000
 5001    pub fn resize_pane(
 5002        &mut self,
 5003        axis: gpui::Axis,
 5004        amount: Pixels,
 5005        window: &mut Window,
 5006        cx: &mut Context<Self>,
 5007    ) {
 5008        let docks = self.all_docks();
 5009        let active_dock = docks
 5010            .into_iter()
 5011            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 5012
 5013        if let Some(dock_entity) = active_dock {
 5014            let dock = dock_entity.read(cx);
 5015            let Some(panel_size) = self.dock_size(&dock, window, cx) else {
 5016                return;
 5017            };
 5018            match dock.position() {
 5019                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 5020                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 5021                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 5022            }
 5023        } else {
 5024            self.center
 5025                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 5026        }
 5027        cx.notify();
 5028    }
 5029
 5030    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 5031        self.center.reset_pane_sizes(cx);
 5032        cx.notify();
 5033    }
 5034
 5035    fn handle_pane_focused(
 5036        &mut self,
 5037        pane: Entity<Pane>,
 5038        window: &mut Window,
 5039        cx: &mut Context<Self>,
 5040    ) {
 5041        // This is explicitly hoisted out of the following check for pane identity as
 5042        // terminal panel panes are not registered as a center panes.
 5043        self.status_bar.update(cx, |status_bar, cx| {
 5044            status_bar.set_active_pane(&pane, window, cx);
 5045        });
 5046        if self.active_pane != pane {
 5047            self.set_active_pane(&pane, window, cx);
 5048        }
 5049
 5050        if self.last_active_center_pane.is_none() {
 5051            self.last_active_center_pane = Some(pane.downgrade());
 5052        }
 5053
 5054        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 5055        // This prevents the dock from closing when focus events fire during window activation.
 5056        // We also preserve any dock whose active panel itself has focus — this covers
 5057        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 5058        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 5059            let dock_read = dock.read(cx);
 5060            if let Some(panel) = dock_read.active_panel() {
 5061                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 5062                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 5063                {
 5064                    return Some(dock_read.position());
 5065                }
 5066            }
 5067            None
 5068        });
 5069
 5070        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 5071        if pane.read(cx).is_zoomed() {
 5072            self.zoomed = Some(pane.downgrade().into());
 5073        } else {
 5074            self.zoomed = None;
 5075        }
 5076        self.zoomed_position = None;
 5077        cx.emit(Event::ZoomChanged);
 5078        self.update_active_view_for_followers(window, cx);
 5079        pane.update(cx, |pane, _| {
 5080            pane.track_alternate_file_items();
 5081        });
 5082
 5083        cx.notify();
 5084    }
 5085
 5086    fn set_active_pane(
 5087        &mut self,
 5088        pane: &Entity<Pane>,
 5089        window: &mut Window,
 5090        cx: &mut Context<Self>,
 5091    ) {
 5092        self.active_pane = pane.clone();
 5093        self.active_item_path_changed(true, window, cx);
 5094        self.last_active_center_pane = Some(pane.downgrade());
 5095    }
 5096
 5097    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5098        self.update_active_view_for_followers(window, cx);
 5099    }
 5100
 5101    fn handle_pane_event(
 5102        &mut self,
 5103        pane: &Entity<Pane>,
 5104        event: &pane::Event,
 5105        window: &mut Window,
 5106        cx: &mut Context<Self>,
 5107    ) {
 5108        let mut serialize_workspace = true;
 5109        match event {
 5110            pane::Event::AddItem { item } => {
 5111                item.added_to_pane(self, pane.clone(), window, cx);
 5112                cx.emit(Event::ItemAdded {
 5113                    item: item.boxed_clone(),
 5114                });
 5115            }
 5116            pane::Event::Split { direction, mode } => {
 5117                match mode {
 5118                    SplitMode::ClonePane => {
 5119                        self.split_and_clone(pane.clone(), *direction, window, cx)
 5120                            .detach();
 5121                    }
 5122                    SplitMode::EmptyPane => {
 5123                        self.split_pane(pane.clone(), *direction, window, cx);
 5124                    }
 5125                    SplitMode::MovePane => {
 5126                        self.split_and_move(pane.clone(), *direction, window, cx);
 5127                    }
 5128                };
 5129            }
 5130            pane::Event::JoinIntoNext => {
 5131                self.join_pane_into_next(pane.clone(), window, cx);
 5132            }
 5133            pane::Event::JoinAll => {
 5134                self.join_all_panes(window, cx);
 5135            }
 5136            pane::Event::Remove { focus_on_pane } => {
 5137                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 5138            }
 5139            pane::Event::ActivateItem {
 5140                local,
 5141                focus_changed,
 5142            } => {
 5143                window.invalidate_character_coordinates();
 5144
 5145                pane.update(cx, |pane, _| {
 5146                    pane.track_alternate_file_items();
 5147                });
 5148                if *local {
 5149                    self.unfollow_in_pane(pane, window, cx);
 5150                }
 5151                serialize_workspace = *focus_changed || pane != self.active_pane();
 5152                if pane == self.active_pane() {
 5153                    self.active_item_path_changed(*focus_changed, window, cx);
 5154                    self.update_active_view_for_followers(window, cx);
 5155                } else if *local {
 5156                    self.set_active_pane(pane, window, cx);
 5157                }
 5158            }
 5159            pane::Event::UserSavedItem { item, save_intent } => {
 5160                cx.emit(Event::UserSavedItem {
 5161                    pane: pane.downgrade(),
 5162                    item: item.boxed_clone(),
 5163                    save_intent: *save_intent,
 5164                });
 5165                serialize_workspace = false;
 5166            }
 5167            pane::Event::ChangeItemTitle => {
 5168                if *pane == self.active_pane {
 5169                    self.active_item_path_changed(false, window, cx);
 5170                }
 5171                serialize_workspace = false;
 5172            }
 5173            pane::Event::RemovedItem { item } => {
 5174                cx.emit(Event::ActiveItemChanged);
 5175                self.update_window_edited(window, cx);
 5176                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 5177                    && entry.get().entity_id() == pane.entity_id()
 5178                {
 5179                    entry.remove();
 5180                }
 5181                cx.emit(Event::ItemRemoved {
 5182                    item_id: item.item_id(),
 5183                });
 5184            }
 5185            pane::Event::Focus => {
 5186                window.invalidate_character_coordinates();
 5187                self.handle_pane_focused(pane.clone(), window, cx);
 5188            }
 5189            pane::Event::ZoomIn => {
 5190                if *pane == self.active_pane {
 5191                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 5192                    if pane.read(cx).has_focus(window, cx) {
 5193                        self.zoomed = Some(pane.downgrade().into());
 5194                        self.zoomed_position = None;
 5195                        cx.emit(Event::ZoomChanged);
 5196                    }
 5197                    cx.notify();
 5198                }
 5199            }
 5200            pane::Event::ZoomOut => {
 5201                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 5202                if self.zoomed_position.is_none() {
 5203                    self.zoomed = None;
 5204                    cx.emit(Event::ZoomChanged);
 5205                }
 5206                cx.notify();
 5207            }
 5208            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 5209        }
 5210
 5211        if serialize_workspace {
 5212            self.serialize_workspace(window, cx);
 5213        }
 5214    }
 5215
 5216    pub fn unfollow_in_pane(
 5217        &mut self,
 5218        pane: &Entity<Pane>,
 5219        window: &mut Window,
 5220        cx: &mut Context<Workspace>,
 5221    ) -> Option<CollaboratorId> {
 5222        let leader_id = self.leader_for_pane(pane)?;
 5223        self.unfollow(leader_id, window, cx);
 5224        Some(leader_id)
 5225    }
 5226
 5227    pub fn split_pane(
 5228        &mut self,
 5229        pane_to_split: Entity<Pane>,
 5230        split_direction: SplitDirection,
 5231        window: &mut Window,
 5232        cx: &mut Context<Self>,
 5233    ) -> Entity<Pane> {
 5234        let new_pane = self.add_pane(window, cx);
 5235        self.center
 5236            .split(&pane_to_split, &new_pane, split_direction, cx);
 5237        cx.notify();
 5238        new_pane
 5239    }
 5240
 5241    pub fn split_and_move(
 5242        &mut self,
 5243        pane: Entity<Pane>,
 5244        direction: SplitDirection,
 5245        window: &mut Window,
 5246        cx: &mut Context<Self>,
 5247    ) {
 5248        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 5249            return;
 5250        };
 5251        let new_pane = self.add_pane(window, cx);
 5252        new_pane.update(cx, |pane, cx| {
 5253            pane.add_item(item, true, true, None, window, cx)
 5254        });
 5255        self.center.split(&pane, &new_pane, direction, cx);
 5256        cx.notify();
 5257    }
 5258
 5259    pub fn split_and_clone(
 5260        &mut self,
 5261        pane: Entity<Pane>,
 5262        direction: SplitDirection,
 5263        window: &mut Window,
 5264        cx: &mut Context<Self>,
 5265    ) -> Task<Option<Entity<Pane>>> {
 5266        let Some(item) = pane.read(cx).active_item() else {
 5267            return Task::ready(None);
 5268        };
 5269        if !item.can_split(cx) {
 5270            return Task::ready(None);
 5271        }
 5272        let task = item.clone_on_split(self.database_id(), window, cx);
 5273        cx.spawn_in(window, async move |this, cx| {
 5274            if let Some(clone) = task.await {
 5275                this.update_in(cx, |this, window, cx| {
 5276                    let new_pane = this.add_pane(window, cx);
 5277                    let nav_history = pane.read(cx).fork_nav_history();
 5278                    new_pane.update(cx, |pane, cx| {
 5279                        pane.set_nav_history(nav_history, cx);
 5280                        pane.add_item(clone, true, true, None, window, cx)
 5281                    });
 5282                    this.center.split(&pane, &new_pane, direction, cx);
 5283                    cx.notify();
 5284                    new_pane
 5285                })
 5286                .ok()
 5287            } else {
 5288                None
 5289            }
 5290        })
 5291    }
 5292
 5293    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5294        let active_item = self.active_pane.read(cx).active_item();
 5295        for pane in &self.panes {
 5296            join_pane_into_active(&self.active_pane, pane, window, cx);
 5297        }
 5298        if let Some(active_item) = active_item {
 5299            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5300        }
 5301        cx.notify();
 5302    }
 5303
 5304    pub fn join_pane_into_next(
 5305        &mut self,
 5306        pane: Entity<Pane>,
 5307        window: &mut Window,
 5308        cx: &mut Context<Self>,
 5309    ) {
 5310        let next_pane = self
 5311            .find_pane_in_direction(SplitDirection::Right, cx)
 5312            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5313            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5314            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5315        let Some(next_pane) = next_pane else {
 5316            return;
 5317        };
 5318        move_all_items(&pane, &next_pane, window, cx);
 5319        cx.notify();
 5320    }
 5321
 5322    fn remove_pane(
 5323        &mut self,
 5324        pane: Entity<Pane>,
 5325        focus_on: Option<Entity<Pane>>,
 5326        window: &mut Window,
 5327        cx: &mut Context<Self>,
 5328    ) {
 5329        if self.center.remove(&pane, cx).unwrap() {
 5330            self.force_remove_pane(&pane, &focus_on, window, cx);
 5331            self.unfollow_in_pane(&pane, window, cx);
 5332            self.last_leaders_by_pane.remove(&pane.downgrade());
 5333            for removed_item in pane.read(cx).items() {
 5334                self.panes_by_item.remove(&removed_item.item_id());
 5335            }
 5336
 5337            cx.notify();
 5338        } else {
 5339            self.active_item_path_changed(true, window, cx);
 5340        }
 5341        cx.emit(Event::PaneRemoved);
 5342    }
 5343
 5344    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5345        &mut self.panes
 5346    }
 5347
 5348    pub fn panes(&self) -> &[Entity<Pane>] {
 5349        &self.panes
 5350    }
 5351
 5352    pub fn active_pane(&self) -> &Entity<Pane> {
 5353        &self.active_pane
 5354    }
 5355
 5356    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5357        for dock in self.all_docks() {
 5358            if dock.focus_handle(cx).contains_focused(window, cx)
 5359                && let Some(pane) = dock
 5360                    .read(cx)
 5361                    .active_panel()
 5362                    .and_then(|panel| panel.pane(cx))
 5363            {
 5364                return pane;
 5365            }
 5366        }
 5367        self.active_pane().clone()
 5368    }
 5369
 5370    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5371        self.find_pane_in_direction(SplitDirection::Right, cx)
 5372            .unwrap_or_else(|| {
 5373                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5374            })
 5375    }
 5376
 5377    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5378        self.pane_for_item_id(handle.item_id())
 5379    }
 5380
 5381    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5382        let weak_pane = self.panes_by_item.get(&item_id)?;
 5383        weak_pane.upgrade()
 5384    }
 5385
 5386    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5387        self.panes
 5388            .iter()
 5389            .find(|pane| pane.entity_id() == entity_id)
 5390            .cloned()
 5391    }
 5392
 5393    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5394        self.follower_states.retain(|leader_id, state| {
 5395            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5396                for item in state.items_by_leader_view_id.values() {
 5397                    item.view.set_leader_id(None, window, cx);
 5398                }
 5399                false
 5400            } else {
 5401                true
 5402            }
 5403        });
 5404        cx.notify();
 5405    }
 5406
 5407    pub fn start_following(
 5408        &mut self,
 5409        leader_id: impl Into<CollaboratorId>,
 5410        window: &mut Window,
 5411        cx: &mut Context<Self>,
 5412    ) -> Option<Task<Result<()>>> {
 5413        let leader_id = leader_id.into();
 5414        let pane = self.active_pane().clone();
 5415
 5416        self.last_leaders_by_pane
 5417            .insert(pane.downgrade(), leader_id);
 5418        self.unfollow(leader_id, window, cx);
 5419        self.unfollow_in_pane(&pane, window, cx);
 5420        self.follower_states.insert(
 5421            leader_id,
 5422            FollowerState {
 5423                center_pane: pane.clone(),
 5424                dock_pane: None,
 5425                active_view_id: None,
 5426                items_by_leader_view_id: Default::default(),
 5427            },
 5428        );
 5429        cx.notify();
 5430
 5431        match leader_id {
 5432            CollaboratorId::PeerId(leader_peer_id) => {
 5433                let room_id = self.active_call()?.room_id(cx)?;
 5434                let project_id = self.project.read(cx).remote_id();
 5435                let request = self.app_state.client.request(proto::Follow {
 5436                    room_id,
 5437                    project_id,
 5438                    leader_id: Some(leader_peer_id),
 5439                });
 5440
 5441                Some(cx.spawn_in(window, async move |this, cx| {
 5442                    let response = request.await?;
 5443                    this.update(cx, |this, _| {
 5444                        let state = this
 5445                            .follower_states
 5446                            .get_mut(&leader_id)
 5447                            .context("following interrupted")?;
 5448                        state.active_view_id = response
 5449                            .active_view
 5450                            .as_ref()
 5451                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5452                        anyhow::Ok(())
 5453                    })??;
 5454                    if let Some(view) = response.active_view {
 5455                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5456                    }
 5457                    this.update_in(cx, |this, window, cx| {
 5458                        this.leader_updated(leader_id, window, cx)
 5459                    })?;
 5460                    Ok(())
 5461                }))
 5462            }
 5463            CollaboratorId::Agent => {
 5464                self.leader_updated(leader_id, window, cx)?;
 5465                Some(Task::ready(Ok(())))
 5466            }
 5467        }
 5468    }
 5469
 5470    pub fn follow_next_collaborator(
 5471        &mut self,
 5472        _: &FollowNextCollaborator,
 5473        window: &mut Window,
 5474        cx: &mut Context<Self>,
 5475    ) {
 5476        let collaborators = self.project.read(cx).collaborators();
 5477        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5478            let mut collaborators = collaborators.keys().copied();
 5479            for peer_id in collaborators.by_ref() {
 5480                if CollaboratorId::PeerId(peer_id) == leader_id {
 5481                    break;
 5482                }
 5483            }
 5484            collaborators.next().map(CollaboratorId::PeerId)
 5485        } else if let Some(last_leader_id) =
 5486            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5487        {
 5488            match last_leader_id {
 5489                CollaboratorId::PeerId(peer_id) => {
 5490                    if collaborators.contains_key(peer_id) {
 5491                        Some(*last_leader_id)
 5492                    } else {
 5493                        None
 5494                    }
 5495                }
 5496                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5497            }
 5498        } else {
 5499            None
 5500        };
 5501
 5502        let pane = self.active_pane.clone();
 5503        let Some(leader_id) = next_leader_id.or_else(|| {
 5504            Some(CollaboratorId::PeerId(
 5505                collaborators.keys().copied().next()?,
 5506            ))
 5507        }) else {
 5508            return;
 5509        };
 5510        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5511            return;
 5512        }
 5513        if let Some(task) = self.start_following(leader_id, window, cx) {
 5514            task.detach_and_log_err(cx)
 5515        }
 5516    }
 5517
 5518    pub fn follow(
 5519        &mut self,
 5520        leader_id: impl Into<CollaboratorId>,
 5521        window: &mut Window,
 5522        cx: &mut Context<Self>,
 5523    ) {
 5524        let leader_id = leader_id.into();
 5525
 5526        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5527            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5528                return;
 5529            };
 5530            let Some(remote_participant) =
 5531                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5532            else {
 5533                return;
 5534            };
 5535
 5536            let project = self.project.read(cx);
 5537
 5538            let other_project_id = match remote_participant.location {
 5539                ParticipantLocation::External => None,
 5540                ParticipantLocation::UnsharedProject => None,
 5541                ParticipantLocation::SharedProject { project_id } => {
 5542                    if Some(project_id) == project.remote_id() {
 5543                        None
 5544                    } else {
 5545                        Some(project_id)
 5546                    }
 5547                }
 5548            };
 5549
 5550            // if they are active in another project, follow there.
 5551            if let Some(project_id) = other_project_id {
 5552                let app_state = self.app_state.clone();
 5553                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5554                    .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
 5555                        Some(format!("{error:#}"))
 5556                    });
 5557            }
 5558        }
 5559
 5560        // if you're already following, find the right pane and focus it.
 5561        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5562            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5563
 5564            return;
 5565        }
 5566
 5567        // Otherwise, follow.
 5568        if let Some(task) = self.start_following(leader_id, window, cx) {
 5569            task.detach_and_log_err(cx)
 5570        }
 5571    }
 5572
 5573    pub fn unfollow(
 5574        &mut self,
 5575        leader_id: impl Into<CollaboratorId>,
 5576        window: &mut Window,
 5577        cx: &mut Context<Self>,
 5578    ) -> Option<()> {
 5579        cx.notify();
 5580
 5581        let leader_id = leader_id.into();
 5582        let state = self.follower_states.remove(&leader_id)?;
 5583        for (_, item) in state.items_by_leader_view_id {
 5584            item.view.set_leader_id(None, window, cx);
 5585        }
 5586
 5587        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5588            let project_id = self.project.read(cx).remote_id();
 5589            let room_id = self.active_call()?.room_id(cx)?;
 5590            self.app_state
 5591                .client
 5592                .send(proto::Unfollow {
 5593                    room_id,
 5594                    project_id,
 5595                    leader_id: Some(leader_peer_id),
 5596                })
 5597                .log_err();
 5598        }
 5599
 5600        Some(())
 5601    }
 5602
 5603    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5604        self.follower_states.contains_key(&id.into())
 5605    }
 5606
 5607    fn active_item_path_changed(
 5608        &mut self,
 5609        focus_changed: bool,
 5610        window: &mut Window,
 5611        cx: &mut Context<Self>,
 5612    ) {
 5613        cx.emit(Event::ActiveItemChanged);
 5614        let active_entry = self.active_project_path(cx);
 5615        self.project.update(cx, |project, cx| {
 5616            project.set_active_path(active_entry.clone(), cx)
 5617        });
 5618
 5619        if focus_changed && let Some(project_path) = &active_entry {
 5620            let git_store_entity = self.project.read(cx).git_store().clone();
 5621            git_store_entity.update(cx, |git_store, cx| {
 5622                git_store.set_active_repo_for_path(project_path, cx);
 5623            });
 5624        }
 5625
 5626        self.update_window_title(window, cx);
 5627    }
 5628
 5629    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5630        let project = self.project().read(cx);
 5631        let mut title = String::new();
 5632
 5633        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5634            let name = {
 5635                let settings_location = SettingsLocation {
 5636                    worktree_id: worktree.read(cx).id(),
 5637                    path: RelPath::empty(),
 5638                };
 5639
 5640                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5641                match &settings.project_name {
 5642                    Some(name) => name.as_str(),
 5643                    None => worktree.read(cx).root_name_str(),
 5644                }
 5645            };
 5646            if i > 0 {
 5647                title.push_str(", ");
 5648            }
 5649            title.push_str(name);
 5650        }
 5651
 5652        if title.is_empty() {
 5653            title = "empty project".to_string();
 5654        }
 5655
 5656        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5657            let filename = path.path.file_name().or_else(|| {
 5658                Some(
 5659                    project
 5660                        .worktree_for_id(path.worktree_id, cx)?
 5661                        .read(cx)
 5662                        .root_name_str(),
 5663                )
 5664            });
 5665
 5666            if let Some(filename) = filename {
 5667                title.push_str("");
 5668                title.push_str(filename.as_ref());
 5669            }
 5670        }
 5671
 5672        if project.is_via_collab() {
 5673            title.push_str("");
 5674        } else if project.is_shared() {
 5675            title.push_str("");
 5676        }
 5677
 5678        if let Some(last_title) = self.last_window_title.as_ref()
 5679            && &title == last_title
 5680        {
 5681            return;
 5682        }
 5683        window.set_window_title(&title);
 5684        SystemWindowTabController::update_tab_title(
 5685            cx,
 5686            window.window_handle().window_id(),
 5687            SharedString::from(&title),
 5688        );
 5689        self.last_window_title = Some(title);
 5690    }
 5691
 5692    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5693        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5694        if is_edited != self.window_edited {
 5695            self.window_edited = is_edited;
 5696            window.set_window_edited(self.window_edited)
 5697        }
 5698    }
 5699
 5700    fn update_item_dirty_state(
 5701        &mut self,
 5702        item: &dyn ItemHandle,
 5703        window: &mut Window,
 5704        cx: &mut App,
 5705    ) {
 5706        let is_dirty = item.is_dirty(cx);
 5707        let item_id = item.item_id();
 5708        let was_dirty = self.dirty_items.contains_key(&item_id);
 5709        if is_dirty == was_dirty {
 5710            return;
 5711        }
 5712        if was_dirty {
 5713            self.dirty_items.remove(&item_id);
 5714            self.update_window_edited(window, cx);
 5715            return;
 5716        }
 5717
 5718        let workspace = self.weak_handle();
 5719        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5720            return;
 5721        };
 5722        let on_release_callback = Box::new(move |cx: &mut App| {
 5723            window_handle
 5724                .update(cx, |_, window, cx| {
 5725                    workspace
 5726                        .update(cx, |workspace, cx| {
 5727                            workspace.dirty_items.remove(&item_id);
 5728                            workspace.update_window_edited(window, cx)
 5729                        })
 5730                        .ok();
 5731                })
 5732                .ok();
 5733        });
 5734
 5735        let s = item.on_release(cx, on_release_callback);
 5736        self.dirty_items.insert(item_id, s);
 5737        self.update_window_edited(window, cx);
 5738    }
 5739
 5740    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5741        if self.notifications.is_empty() {
 5742            None
 5743        } else {
 5744            Some(
 5745                div()
 5746                    .absolute()
 5747                    .right_3()
 5748                    .bottom_3()
 5749                    .w_112()
 5750                    .h_full()
 5751                    .flex()
 5752                    .flex_col()
 5753                    .justify_end()
 5754                    .gap_2()
 5755                    .children(
 5756                        self.notifications
 5757                            .iter()
 5758                            .map(|(_, notification)| notification.clone().into_any()),
 5759                    ),
 5760            )
 5761        }
 5762    }
 5763
 5764    // RPC handlers
 5765
 5766    fn active_view_for_follower(
 5767        &self,
 5768        follower_project_id: Option<u64>,
 5769        window: &mut Window,
 5770        cx: &mut Context<Self>,
 5771    ) -> Option<proto::View> {
 5772        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5773        let item = item?;
 5774        let leader_id = self
 5775            .pane_for(&*item)
 5776            .and_then(|pane| self.leader_for_pane(&pane));
 5777        let leader_peer_id = match leader_id {
 5778            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5779            Some(CollaboratorId::Agent) | None => None,
 5780        };
 5781
 5782        let item_handle = item.to_followable_item_handle(cx)?;
 5783        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5784        let variant = item_handle.to_state_proto(window, cx)?;
 5785
 5786        if item_handle.is_project_item(window, cx)
 5787            && (follower_project_id.is_none()
 5788                || follower_project_id != self.project.read(cx).remote_id())
 5789        {
 5790            return None;
 5791        }
 5792
 5793        Some(proto::View {
 5794            id: id.to_proto(),
 5795            leader_id: leader_peer_id,
 5796            variant: Some(variant),
 5797            panel_id: panel_id.map(|id| id as i32),
 5798        })
 5799    }
 5800
 5801    fn handle_follow(
 5802        &mut self,
 5803        follower_project_id: Option<u64>,
 5804        window: &mut Window,
 5805        cx: &mut Context<Self>,
 5806    ) -> proto::FollowResponse {
 5807        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5808
 5809        cx.notify();
 5810        proto::FollowResponse {
 5811            views: active_view.iter().cloned().collect(),
 5812            active_view,
 5813        }
 5814    }
 5815
 5816    fn handle_update_followers(
 5817        &mut self,
 5818        leader_id: PeerId,
 5819        message: proto::UpdateFollowers,
 5820        _window: &mut Window,
 5821        _cx: &mut Context<Self>,
 5822    ) {
 5823        self.leader_updates_tx
 5824            .unbounded_send((leader_id, message))
 5825            .ok();
 5826    }
 5827
 5828    async fn process_leader_update(
 5829        this: &WeakEntity<Self>,
 5830        leader_id: PeerId,
 5831        update: proto::UpdateFollowers,
 5832        cx: &mut AsyncWindowContext,
 5833    ) -> Result<()> {
 5834        match update.variant.context("invalid update")? {
 5835            proto::update_followers::Variant::CreateView(view) => {
 5836                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5837                let should_add_view = this.update(cx, |this, _| {
 5838                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5839                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5840                    } else {
 5841                        anyhow::Ok(false)
 5842                    }
 5843                })??;
 5844
 5845                if should_add_view {
 5846                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5847                }
 5848            }
 5849            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5850                let should_add_view = this.update(cx, |this, _| {
 5851                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5852                        state.active_view_id = update_active_view
 5853                            .view
 5854                            .as_ref()
 5855                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5856
 5857                        if state.active_view_id.is_some_and(|view_id| {
 5858                            !state.items_by_leader_view_id.contains_key(&view_id)
 5859                        }) {
 5860                            anyhow::Ok(true)
 5861                        } else {
 5862                            anyhow::Ok(false)
 5863                        }
 5864                    } else {
 5865                        anyhow::Ok(false)
 5866                    }
 5867                })??;
 5868
 5869                if should_add_view && let Some(view) = update_active_view.view {
 5870                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5871                }
 5872            }
 5873            proto::update_followers::Variant::UpdateView(update_view) => {
 5874                let variant = update_view.variant.context("missing update view variant")?;
 5875                let id = update_view.id.context("missing update view id")?;
 5876                let mut tasks = Vec::new();
 5877                this.update_in(cx, |this, window, cx| {
 5878                    let project = this.project.clone();
 5879                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5880                        let view_id = ViewId::from_proto(id.clone())?;
 5881                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5882                            tasks.push(item.view.apply_update_proto(
 5883                                &project,
 5884                                variant.clone(),
 5885                                window,
 5886                                cx,
 5887                            ));
 5888                        }
 5889                    }
 5890                    anyhow::Ok(())
 5891                })??;
 5892                try_join_all(tasks).await.log_err();
 5893            }
 5894        }
 5895        this.update_in(cx, |this, window, cx| {
 5896            this.leader_updated(leader_id, window, cx)
 5897        })?;
 5898        Ok(())
 5899    }
 5900
 5901    async fn add_view_from_leader(
 5902        this: WeakEntity<Self>,
 5903        leader_id: PeerId,
 5904        view: &proto::View,
 5905        cx: &mut AsyncWindowContext,
 5906    ) -> Result<()> {
 5907        let this = this.upgrade().context("workspace dropped")?;
 5908
 5909        let Some(id) = view.id.clone() else {
 5910            anyhow::bail!("no id for view");
 5911        };
 5912        let id = ViewId::from_proto(id)?;
 5913        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5914
 5915        let pane = this.update(cx, |this, _cx| {
 5916            let state = this
 5917                .follower_states
 5918                .get(&leader_id.into())
 5919                .context("stopped following")?;
 5920            anyhow::Ok(state.pane().clone())
 5921        })?;
 5922        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5923            let client = this.read(cx).client().clone();
 5924            pane.items().find_map(|item| {
 5925                let item = item.to_followable_item_handle(cx)?;
 5926                if item.remote_id(&client, window, cx) == Some(id) {
 5927                    Some(item)
 5928                } else {
 5929                    None
 5930                }
 5931            })
 5932        })?;
 5933        let item = if let Some(existing_item) = existing_item {
 5934            existing_item
 5935        } else {
 5936            let variant = view.variant.clone();
 5937            anyhow::ensure!(variant.is_some(), "missing view variant");
 5938
 5939            let task = cx.update(|window, cx| {
 5940                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5941            })?;
 5942
 5943            let Some(task) = task else {
 5944                anyhow::bail!(
 5945                    "failed to construct view from leader (maybe from a different version of zed?)"
 5946                );
 5947            };
 5948
 5949            let mut new_item = task.await?;
 5950            pane.update_in(cx, |pane, window, cx| {
 5951                let mut item_to_remove = None;
 5952                for (ix, item) in pane.items().enumerate() {
 5953                    if let Some(item) = item.to_followable_item_handle(cx) {
 5954                        match new_item.dedup(item.as_ref(), window, cx) {
 5955                            Some(item::Dedup::KeepExisting) => {
 5956                                new_item =
 5957                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5958                                break;
 5959                            }
 5960                            Some(item::Dedup::ReplaceExisting) => {
 5961                                item_to_remove = Some((ix, item.item_id()));
 5962                                break;
 5963                            }
 5964                            None => {}
 5965                        }
 5966                    }
 5967                }
 5968
 5969                if let Some((ix, id)) = item_to_remove {
 5970                    pane.remove_item(id, false, false, window, cx);
 5971                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5972                }
 5973            })?;
 5974
 5975            new_item
 5976        };
 5977
 5978        this.update_in(cx, |this, window, cx| {
 5979            let state = this.follower_states.get_mut(&leader_id.into())?;
 5980            item.set_leader_id(Some(leader_id.into()), window, cx);
 5981            state.items_by_leader_view_id.insert(
 5982                id,
 5983                FollowerView {
 5984                    view: item,
 5985                    location: panel_id,
 5986                },
 5987            );
 5988
 5989            Some(())
 5990        })
 5991        .context("no follower state")?;
 5992
 5993        Ok(())
 5994    }
 5995
 5996    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5997        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5998            return;
 5999        };
 6000
 6001        if let Some(agent_location) = self.project.read(cx).agent_location() {
 6002            let buffer_entity_id = agent_location.buffer.entity_id();
 6003            let view_id = ViewId {
 6004                creator: CollaboratorId::Agent,
 6005                id: buffer_entity_id.as_u64(),
 6006            };
 6007            follower_state.active_view_id = Some(view_id);
 6008
 6009            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 6010                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 6011                hash_map::Entry::Vacant(entry) => {
 6012                    let existing_view =
 6013                        follower_state
 6014                            .center_pane
 6015                            .read(cx)
 6016                            .items()
 6017                            .find_map(|item| {
 6018                                let item = item.to_followable_item_handle(cx)?;
 6019                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 6020                                    && item.project_item_model_ids(cx).as_slice()
 6021                                        == [buffer_entity_id]
 6022                                {
 6023                                    Some(item)
 6024                                } else {
 6025                                    None
 6026                                }
 6027                            });
 6028                    let view = existing_view.or_else(|| {
 6029                        agent_location.buffer.upgrade().and_then(|buffer| {
 6030                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 6031                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 6032                            })?
 6033                            .to_followable_item_handle(cx)
 6034                        })
 6035                    });
 6036
 6037                    view.map(|view| {
 6038                        entry.insert(FollowerView {
 6039                            view,
 6040                            location: None,
 6041                        })
 6042                    })
 6043                }
 6044            };
 6045
 6046            if let Some(item) = item {
 6047                item.view
 6048                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 6049                item.view
 6050                    .update_agent_location(agent_location.position, window, cx);
 6051            }
 6052        } else {
 6053            follower_state.active_view_id = None;
 6054        }
 6055
 6056        self.leader_updated(CollaboratorId::Agent, window, cx);
 6057    }
 6058
 6059    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 6060        let mut is_project_item = true;
 6061        let mut update = proto::UpdateActiveView::default();
 6062        if window.is_window_active() {
 6063            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 6064
 6065            if let Some(item) = active_item
 6066                && item.item_focus_handle(cx).contains_focused(window, cx)
 6067            {
 6068                let leader_id = self
 6069                    .pane_for(&*item)
 6070                    .and_then(|pane| self.leader_for_pane(&pane));
 6071                let leader_peer_id = match leader_id {
 6072                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 6073                    Some(CollaboratorId::Agent) | None => None,
 6074                };
 6075
 6076                if let Some(item) = item.to_followable_item_handle(cx) {
 6077                    let id = item
 6078                        .remote_id(&self.app_state.client, window, cx)
 6079                        .map(|id| id.to_proto());
 6080
 6081                    if let Some(id) = id
 6082                        && let Some(variant) = item.to_state_proto(window, cx)
 6083                    {
 6084                        let view = Some(proto::View {
 6085                            id,
 6086                            leader_id: leader_peer_id,
 6087                            variant: Some(variant),
 6088                            panel_id: panel_id.map(|id| id as i32),
 6089                        });
 6090
 6091                        is_project_item = item.is_project_item(window, cx);
 6092                        update = proto::UpdateActiveView { view };
 6093                    };
 6094                }
 6095            }
 6096        }
 6097
 6098        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 6099        if active_view_id != self.last_active_view_id.as_ref() {
 6100            self.last_active_view_id = active_view_id.cloned();
 6101            self.update_followers(
 6102                is_project_item,
 6103                proto::update_followers::Variant::UpdateActiveView(update),
 6104                window,
 6105                cx,
 6106            );
 6107        }
 6108    }
 6109
 6110    fn active_item_for_followers(
 6111        &self,
 6112        window: &mut Window,
 6113        cx: &mut App,
 6114    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 6115        let mut active_item = None;
 6116        let mut panel_id = None;
 6117        for dock in self.all_docks() {
 6118            if dock.focus_handle(cx).contains_focused(window, cx)
 6119                && let Some(panel) = dock.read(cx).active_panel()
 6120                && let Some(pane) = panel.pane(cx)
 6121                && let Some(item) = pane.read(cx).active_item()
 6122            {
 6123                active_item = Some(item);
 6124                panel_id = panel.remote_id();
 6125                break;
 6126            }
 6127        }
 6128
 6129        if active_item.is_none() {
 6130            active_item = self.active_pane().read(cx).active_item();
 6131        }
 6132        (active_item, panel_id)
 6133    }
 6134
 6135    fn update_followers(
 6136        &self,
 6137        project_only: bool,
 6138        update: proto::update_followers::Variant,
 6139        _: &mut Window,
 6140        cx: &mut App,
 6141    ) -> Option<()> {
 6142        // If this update only applies to for followers in the current project,
 6143        // then skip it unless this project is shared. If it applies to all
 6144        // followers, regardless of project, then set `project_id` to none,
 6145        // indicating that it goes to all followers.
 6146        let project_id = if project_only {
 6147            Some(self.project.read(cx).remote_id()?)
 6148        } else {
 6149            None
 6150        };
 6151        self.app_state().workspace_store.update(cx, |store, cx| {
 6152            store.update_followers(project_id, update, cx)
 6153        })
 6154    }
 6155
 6156    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 6157        self.follower_states.iter().find_map(|(leader_id, state)| {
 6158            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 6159                Some(*leader_id)
 6160            } else {
 6161                None
 6162            }
 6163        })
 6164    }
 6165
 6166    fn leader_updated(
 6167        &mut self,
 6168        leader_id: impl Into<CollaboratorId>,
 6169        window: &mut Window,
 6170        cx: &mut Context<Self>,
 6171    ) -> Option<Box<dyn ItemHandle>> {
 6172        cx.notify();
 6173
 6174        let leader_id = leader_id.into();
 6175        let (panel_id, item) = match leader_id {
 6176            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 6177            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 6178        };
 6179
 6180        let state = self.follower_states.get(&leader_id)?;
 6181        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 6182        let pane;
 6183        if let Some(panel_id) = panel_id {
 6184            pane = self
 6185                .activate_panel_for_proto_id(panel_id, window, cx)?
 6186                .pane(cx)?;
 6187            let state = self.follower_states.get_mut(&leader_id)?;
 6188            state.dock_pane = Some(pane.clone());
 6189        } else {
 6190            pane = state.center_pane.clone();
 6191            let state = self.follower_states.get_mut(&leader_id)?;
 6192            if let Some(dock_pane) = state.dock_pane.take() {
 6193                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 6194            }
 6195        }
 6196
 6197        pane.update(cx, |pane, cx| {
 6198            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 6199            if let Some(index) = pane.index_for_item(item.as_ref()) {
 6200                pane.activate_item(index, false, false, window, cx);
 6201            } else {
 6202                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 6203            }
 6204
 6205            if focus_active_item {
 6206                pane.focus_active_item(window, cx)
 6207            }
 6208        });
 6209
 6210        Some(item)
 6211    }
 6212
 6213    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 6214        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 6215        let active_view_id = state.active_view_id?;
 6216        Some(
 6217            state
 6218                .items_by_leader_view_id
 6219                .get(&active_view_id)?
 6220                .view
 6221                .boxed_clone(),
 6222        )
 6223    }
 6224
 6225    fn active_item_for_peer(
 6226        &self,
 6227        peer_id: PeerId,
 6228        window: &mut Window,
 6229        cx: &mut Context<Self>,
 6230    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 6231        let call = self.active_call()?;
 6232        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 6233        let leader_in_this_app;
 6234        let leader_in_this_project;
 6235        match participant.location {
 6236            ParticipantLocation::SharedProject { project_id } => {
 6237                leader_in_this_app = true;
 6238                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 6239            }
 6240            ParticipantLocation::UnsharedProject => {
 6241                leader_in_this_app = true;
 6242                leader_in_this_project = false;
 6243            }
 6244            ParticipantLocation::External => {
 6245                leader_in_this_app = false;
 6246                leader_in_this_project = false;
 6247            }
 6248        };
 6249        let state = self.follower_states.get(&peer_id.into())?;
 6250        let mut item_to_activate = None;
 6251        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 6252            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 6253                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 6254            {
 6255                item_to_activate = Some((item.location, item.view.boxed_clone()));
 6256            }
 6257        } else if let Some(shared_screen) =
 6258            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 6259        {
 6260            item_to_activate = Some((None, Box::new(shared_screen)));
 6261        }
 6262        item_to_activate
 6263    }
 6264
 6265    fn shared_screen_for_peer(
 6266        &self,
 6267        peer_id: PeerId,
 6268        pane: &Entity<Pane>,
 6269        window: &mut Window,
 6270        cx: &mut App,
 6271    ) -> Option<Entity<SharedScreen>> {
 6272        self.active_call()?
 6273            .create_shared_screen(peer_id, pane, window, cx)
 6274    }
 6275
 6276    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6277        if window.is_window_active() {
 6278            self.update_active_view_for_followers(window, cx);
 6279
 6280            if let Some(database_id) = self.database_id {
 6281                let db = WorkspaceDb::global(cx);
 6282                cx.background_spawn(async move { db.update_timestamp(database_id).await })
 6283                    .detach();
 6284            }
 6285        } else {
 6286            for pane in &self.panes {
 6287                pane.update(cx, |pane, cx| {
 6288                    if let Some(item) = pane.active_item() {
 6289                        item.workspace_deactivated(window, cx);
 6290                    }
 6291                    for item in pane.items() {
 6292                        if matches!(
 6293                            item.workspace_settings(cx).autosave,
 6294                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6295                        ) {
 6296                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6297                                .detach_and_log_err(cx);
 6298                        }
 6299                    }
 6300                });
 6301            }
 6302        }
 6303    }
 6304
 6305    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6306        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6307    }
 6308
 6309    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6310        self.active_call.as_ref().map(|(call, _)| call.clone())
 6311    }
 6312
 6313    fn on_active_call_event(
 6314        &mut self,
 6315        event: &ActiveCallEvent,
 6316        window: &mut Window,
 6317        cx: &mut Context<Self>,
 6318    ) {
 6319        match event {
 6320            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6321            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6322                self.leader_updated(participant_id, window, cx);
 6323            }
 6324        }
 6325    }
 6326
 6327    pub fn database_id(&self) -> Option<WorkspaceId> {
 6328        self.database_id
 6329    }
 6330
 6331    #[cfg(any(test, feature = "test-support"))]
 6332    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6333        self.database_id = Some(id);
 6334    }
 6335
 6336    pub fn session_id(&self) -> Option<String> {
 6337        self.session_id.clone()
 6338    }
 6339
 6340    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6341        let Some(display) = window.display(cx) else {
 6342            return Task::ready(());
 6343        };
 6344        let Ok(display_uuid) = display.uuid() else {
 6345            return Task::ready(());
 6346        };
 6347
 6348        let window_bounds = window.inner_window_bounds();
 6349        let database_id = self.database_id;
 6350        let has_paths = !self.root_paths(cx).is_empty();
 6351        let db = WorkspaceDb::global(cx);
 6352        let kvp = db::kvp::KeyValueStore::global(cx);
 6353
 6354        cx.background_executor().spawn(async move {
 6355            if !has_paths {
 6356                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6357                    .await
 6358                    .log_err();
 6359            }
 6360            if let Some(database_id) = database_id {
 6361                db.set_window_open_status(
 6362                    database_id,
 6363                    SerializedWindowBounds(window_bounds),
 6364                    display_uuid,
 6365                )
 6366                .await
 6367                .log_err();
 6368            } else {
 6369                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6370                    .await
 6371                    .log_err();
 6372            }
 6373        })
 6374    }
 6375
 6376    /// Bypass the 200ms serialization throttle and write workspace state to
 6377    /// the DB immediately. Returns a task the caller can await to ensure the
 6378    /// write completes. Used by the quit handler so the most recent state
 6379    /// isn't lost to a pending throttle timer when the process exits.
 6380    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6381        self._schedule_serialize_workspace.take();
 6382        self._serialize_workspace_task.take();
 6383        self.bounds_save_task_queued.take();
 6384
 6385        let bounds_task = self.save_window_bounds(window, cx);
 6386        let serialize_task = self.serialize_workspace_internal(window, cx);
 6387        cx.spawn(async move |_| {
 6388            bounds_task.await;
 6389            serialize_task.await;
 6390        })
 6391    }
 6392
 6393    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6394        let project = self.project().read(cx);
 6395        project
 6396            .visible_worktrees(cx)
 6397            .map(|worktree| worktree.read(cx).abs_path())
 6398            .collect::<Vec<_>>()
 6399    }
 6400
 6401    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6402        match member {
 6403            Member::Axis(PaneAxis { members, .. }) => {
 6404                for child in members.iter() {
 6405                    self.remove_panes(child.clone(), window, cx)
 6406                }
 6407            }
 6408            Member::Pane(pane) => {
 6409                self.force_remove_pane(&pane, &None, window, cx);
 6410            }
 6411        }
 6412    }
 6413
 6414    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6415        self.session_id.take();
 6416        self.serialize_workspace_internal(window, cx)
 6417    }
 6418
 6419    fn force_remove_pane(
 6420        &mut self,
 6421        pane: &Entity<Pane>,
 6422        focus_on: &Option<Entity<Pane>>,
 6423        window: &mut Window,
 6424        cx: &mut Context<Workspace>,
 6425    ) {
 6426        self.panes.retain(|p| p != pane);
 6427        if let Some(focus_on) = focus_on {
 6428            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6429        } else if self.active_pane() == pane {
 6430            self.panes
 6431                .last()
 6432                .unwrap()
 6433                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6434        }
 6435        if self.last_active_center_pane == Some(pane.downgrade()) {
 6436            self.last_active_center_pane = None;
 6437        }
 6438        cx.notify();
 6439    }
 6440
 6441    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6442        if self._schedule_serialize_workspace.is_none() {
 6443            self._schedule_serialize_workspace =
 6444                Some(cx.spawn_in(window, async move |this, cx| {
 6445                    cx.background_executor()
 6446                        .timer(SERIALIZATION_THROTTLE_TIME)
 6447                        .await;
 6448                    this.update_in(cx, |this, window, cx| {
 6449                        this._serialize_workspace_task =
 6450                            Some(this.serialize_workspace_internal(window, cx));
 6451                        this._schedule_serialize_workspace.take();
 6452                    })
 6453                    .log_err();
 6454                }));
 6455        }
 6456    }
 6457
 6458    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6459        let Some(database_id) = self.database_id() else {
 6460            return Task::ready(());
 6461        };
 6462
 6463        fn serialize_pane_handle(
 6464            pane_handle: &Entity<Pane>,
 6465            window: &mut Window,
 6466            cx: &mut App,
 6467        ) -> SerializedPane {
 6468            let (items, active, pinned_count) = {
 6469                let pane = pane_handle.read(cx);
 6470                let active_item_id = pane.active_item().map(|item| item.item_id());
 6471                (
 6472                    pane.items()
 6473                        .filter_map(|handle| {
 6474                            let handle = handle.to_serializable_item_handle(cx)?;
 6475
 6476                            Some(SerializedItem {
 6477                                kind: Arc::from(handle.serialized_item_kind()),
 6478                                item_id: handle.item_id().as_u64(),
 6479                                active: Some(handle.item_id()) == active_item_id,
 6480                                preview: pane.is_active_preview_item(handle.item_id()),
 6481                            })
 6482                        })
 6483                        .collect::<Vec<_>>(),
 6484                    pane.has_focus(window, cx),
 6485                    pane.pinned_count(),
 6486                )
 6487            };
 6488
 6489            SerializedPane::new(items, active, pinned_count)
 6490        }
 6491
 6492        fn build_serialized_pane_group(
 6493            pane_group: &Member,
 6494            window: &mut Window,
 6495            cx: &mut App,
 6496        ) -> SerializedPaneGroup {
 6497            match pane_group {
 6498                Member::Axis(PaneAxis {
 6499                    axis,
 6500                    members,
 6501                    flexes,
 6502                    bounding_boxes: _,
 6503                }) => SerializedPaneGroup::Group {
 6504                    axis: SerializedAxis(*axis),
 6505                    children: members
 6506                        .iter()
 6507                        .map(|member| build_serialized_pane_group(member, window, cx))
 6508                        .collect::<Vec<_>>(),
 6509                    flexes: Some(flexes.lock().clone()),
 6510                },
 6511                Member::Pane(pane_handle) => {
 6512                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6513                }
 6514            }
 6515        }
 6516
 6517        fn build_serialized_docks(
 6518            this: &Workspace,
 6519            window: &mut Window,
 6520            cx: &mut App,
 6521        ) -> DockStructure {
 6522            this.capture_dock_state(window, cx)
 6523        }
 6524
 6525        match self.workspace_location(cx) {
 6526            WorkspaceLocation::Location(location, paths) => {
 6527                let breakpoints = self.project.update(cx, |project, cx| {
 6528                    project
 6529                        .breakpoint_store()
 6530                        .read(cx)
 6531                        .all_source_breakpoints(cx)
 6532                });
 6533                let user_toolchains = self
 6534                    .project
 6535                    .read(cx)
 6536                    .user_toolchains(cx)
 6537                    .unwrap_or_default();
 6538
 6539                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6540                let docks = build_serialized_docks(self, window, cx);
 6541                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6542
 6543                let serialized_workspace = SerializedWorkspace {
 6544                    id: database_id,
 6545                    location,
 6546                    paths,
 6547                    center_group,
 6548                    window_bounds,
 6549                    display: Default::default(),
 6550                    docks,
 6551                    centered_layout: self.centered_layout,
 6552                    session_id: self.session_id.clone(),
 6553                    breakpoints,
 6554                    window_id: Some(window.window_handle().window_id().as_u64()),
 6555                    user_toolchains,
 6556                };
 6557
 6558                let db = WorkspaceDb::global(cx);
 6559                window.spawn(cx, async move |_| {
 6560                    db.save_workspace(serialized_workspace).await;
 6561                })
 6562            }
 6563            WorkspaceLocation::DetachFromSession => {
 6564                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6565                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6566                // Save dock state for empty local workspaces
 6567                let docks = build_serialized_docks(self, window, cx);
 6568                let db = WorkspaceDb::global(cx);
 6569                let kvp = db::kvp::KeyValueStore::global(cx);
 6570                window.spawn(cx, async move |_| {
 6571                    db.set_window_open_status(
 6572                        database_id,
 6573                        window_bounds,
 6574                        display.unwrap_or_default(),
 6575                    )
 6576                    .await
 6577                    .log_err();
 6578                    db.set_session_id(database_id, None).await.log_err();
 6579                    persistence::write_default_dock_state(&kvp, docks)
 6580                        .await
 6581                        .log_err();
 6582                })
 6583            }
 6584            WorkspaceLocation::None => {
 6585                // Save dock state for empty non-local workspaces
 6586                let docks = build_serialized_docks(self, window, cx);
 6587                let kvp = db::kvp::KeyValueStore::global(cx);
 6588                window.spawn(cx, async move |_| {
 6589                    persistence::write_default_dock_state(&kvp, docks)
 6590                        .await
 6591                        .log_err();
 6592                })
 6593            }
 6594        }
 6595    }
 6596
 6597    fn has_any_items_open(&self, cx: &App) -> bool {
 6598        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6599    }
 6600
 6601    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6602        let paths = PathList::new(&self.root_paths(cx));
 6603        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6604            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6605        } else if self.project.read(cx).is_local() {
 6606            if !paths.is_empty() || self.has_any_items_open(cx) {
 6607                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6608            } else {
 6609                WorkspaceLocation::DetachFromSession
 6610            }
 6611        } else {
 6612            WorkspaceLocation::None
 6613        }
 6614    }
 6615
 6616    fn update_history(&self, cx: &mut App) {
 6617        let Some(id) = self.database_id() else {
 6618            return;
 6619        };
 6620        if !self.project.read(cx).is_local() {
 6621            return;
 6622        }
 6623        if let Some(manager) = HistoryManager::global(cx) {
 6624            let paths = PathList::new(&self.root_paths(cx));
 6625            manager.update(cx, |this, cx| {
 6626                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6627            });
 6628        }
 6629    }
 6630
 6631    async fn serialize_items(
 6632        this: &WeakEntity<Self>,
 6633        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6634        cx: &mut AsyncWindowContext,
 6635    ) -> Result<()> {
 6636        const CHUNK_SIZE: usize = 200;
 6637
 6638        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6639
 6640        while let Some(items_received) = serializable_items.next().await {
 6641            let unique_items =
 6642                items_received
 6643                    .into_iter()
 6644                    .fold(HashMap::default(), |mut acc, item| {
 6645                        acc.entry(item.item_id()).or_insert(item);
 6646                        acc
 6647                    });
 6648
 6649            // We use into_iter() here so that the references to the items are moved into
 6650            // the tasks and not kept alive while we're sleeping.
 6651            for (_, item) in unique_items.into_iter() {
 6652                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6653                    item.serialize(workspace, false, window, cx)
 6654                }) {
 6655                    cx.background_spawn(async move { task.await.log_err() })
 6656                        .detach();
 6657                }
 6658            }
 6659
 6660            cx.background_executor()
 6661                .timer(SERIALIZATION_THROTTLE_TIME)
 6662                .await;
 6663        }
 6664
 6665        Ok(())
 6666    }
 6667
 6668    pub(crate) fn enqueue_item_serialization(
 6669        &mut self,
 6670        item: Box<dyn SerializableItemHandle>,
 6671    ) -> Result<()> {
 6672        self.serializable_items_tx
 6673            .unbounded_send(item)
 6674            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6675    }
 6676
 6677    pub(crate) fn load_workspace(
 6678        serialized_workspace: SerializedWorkspace,
 6679        paths_to_open: Vec<Option<ProjectPath>>,
 6680        window: &mut Window,
 6681        cx: &mut Context<Workspace>,
 6682    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6683        cx.spawn_in(window, async move |workspace, cx| {
 6684            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6685
 6686            let mut center_group = None;
 6687            let mut center_items = None;
 6688
 6689            // Traverse the splits tree and add to things
 6690            if let Some((group, active_pane, items)) = serialized_workspace
 6691                .center_group
 6692                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6693                .await
 6694            {
 6695                center_items = Some(items);
 6696                center_group = Some((group, active_pane))
 6697            }
 6698
 6699            let mut items_by_project_path = HashMap::default();
 6700            let mut item_ids_by_kind = HashMap::default();
 6701            let mut all_deserialized_items = Vec::default();
 6702            cx.update(|_, cx| {
 6703                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6704                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6705                        item_ids_by_kind
 6706                            .entry(serializable_item_handle.serialized_item_kind())
 6707                            .or_insert(Vec::new())
 6708                            .push(item.item_id().as_u64() as ItemId);
 6709                    }
 6710
 6711                    if let Some(project_path) = item.project_path(cx) {
 6712                        items_by_project_path.insert(project_path, item.clone());
 6713                    }
 6714                    all_deserialized_items.push(item);
 6715                }
 6716            })?;
 6717
 6718            let opened_items = paths_to_open
 6719                .into_iter()
 6720                .map(|path_to_open| {
 6721                    path_to_open
 6722                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6723                })
 6724                .collect::<Vec<_>>();
 6725
 6726            // Remove old panes from workspace panes list
 6727            workspace.update_in(cx, |workspace, window, cx| {
 6728                if let Some((center_group, active_pane)) = center_group {
 6729                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6730
 6731                    // Swap workspace center group
 6732                    workspace.center = PaneGroup::with_root(center_group);
 6733                    workspace.center.set_is_center(true);
 6734                    workspace.center.mark_positions(cx);
 6735
 6736                    if let Some(active_pane) = active_pane {
 6737                        workspace.set_active_pane(&active_pane, window, cx);
 6738                        cx.focus_self(window);
 6739                    } else {
 6740                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6741                    }
 6742                }
 6743
 6744                let docks = serialized_workspace.docks;
 6745
 6746                for (dock, serialized_dock) in [
 6747                    (&mut workspace.right_dock, docks.right),
 6748                    (&mut workspace.left_dock, docks.left),
 6749                    (&mut workspace.bottom_dock, docks.bottom),
 6750                ]
 6751                .iter_mut()
 6752                {
 6753                    dock.update(cx, |dock, cx| {
 6754                        dock.serialized_dock = Some(serialized_dock.clone());
 6755                        dock.restore_state(window, cx);
 6756                    });
 6757                }
 6758
 6759                cx.notify();
 6760            })?;
 6761
 6762            let _ = project
 6763                .update(cx, |project, cx| {
 6764                    project
 6765                        .breakpoint_store()
 6766                        .update(cx, |breakpoint_store, cx| {
 6767                            breakpoint_store
 6768                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6769                        })
 6770                })
 6771                .await;
 6772
 6773            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6774            // after loading the items, we might have different items and in order to avoid
 6775            // the database filling up, we delete items that haven't been loaded now.
 6776            //
 6777            // The items that have been loaded, have been saved after they've been added to the workspace.
 6778            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6779                item_ids_by_kind
 6780                    .into_iter()
 6781                    .map(|(item_kind, loaded_items)| {
 6782                        SerializableItemRegistry::cleanup(
 6783                            item_kind,
 6784                            serialized_workspace.id,
 6785                            loaded_items,
 6786                            window,
 6787                            cx,
 6788                        )
 6789                        .log_err()
 6790                    })
 6791                    .collect::<Vec<_>>()
 6792            })?;
 6793
 6794            futures::future::join_all(clean_up_tasks).await;
 6795
 6796            workspace
 6797                .update_in(cx, |workspace, window, cx| {
 6798                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6799                    workspace.serialize_workspace_internal(window, cx).detach();
 6800
 6801                    // Ensure that we mark the window as edited if we did load dirty items
 6802                    workspace.update_window_edited(window, cx);
 6803                })
 6804                .ok();
 6805
 6806            Ok(opened_items)
 6807        })
 6808    }
 6809
 6810    pub fn key_context(&self, cx: &App) -> KeyContext {
 6811        let mut context = KeyContext::new_with_defaults();
 6812        context.add("Workspace");
 6813        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6814        if let Some(status) = self
 6815            .debugger_provider
 6816            .as_ref()
 6817            .and_then(|provider| provider.active_thread_state(cx))
 6818        {
 6819            match status {
 6820                ThreadStatus::Running | ThreadStatus::Stepping => {
 6821                    context.add("debugger_running");
 6822                }
 6823                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6824                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6825            }
 6826        }
 6827
 6828        if self.left_dock.read(cx).is_open() {
 6829            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6830                context.set("left_dock", active_panel.panel_key());
 6831            }
 6832        }
 6833
 6834        if self.right_dock.read(cx).is_open() {
 6835            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6836                context.set("right_dock", active_panel.panel_key());
 6837            }
 6838        }
 6839
 6840        if self.bottom_dock.read(cx).is_open() {
 6841            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6842                context.set("bottom_dock", active_panel.panel_key());
 6843            }
 6844        }
 6845
 6846        context
 6847    }
 6848
 6849    /// Multiworkspace uses this to add workspace action handling to itself
 6850    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6851        self.add_workspace_actions_listeners(div, window, cx)
 6852            .on_action(cx.listener(
 6853                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6854                    for action in &action_sequence.0 {
 6855                        window.dispatch_action(action.boxed_clone(), cx);
 6856                    }
 6857                },
 6858            ))
 6859            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6860            .on_action(cx.listener(Self::close_all_items_and_panes))
 6861            .on_action(cx.listener(Self::close_item_in_all_panes))
 6862            .on_action(cx.listener(Self::save_all))
 6863            .on_action(cx.listener(Self::send_keystrokes))
 6864            .on_action(cx.listener(Self::add_folder_to_project))
 6865            .on_action(cx.listener(Self::follow_next_collaborator))
 6866            .on_action(cx.listener(Self::activate_pane_at_index))
 6867            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6868            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6869            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6870            .on_action(cx.listener(Self::toggle_theme_mode))
 6871            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6872                let pane = workspace.active_pane().clone();
 6873                workspace.unfollow_in_pane(&pane, window, cx);
 6874            }))
 6875            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6876                workspace
 6877                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6878                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6879            }))
 6880            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6881                workspace
 6882                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6883                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6884            }))
 6885            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6886                workspace
 6887                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6888                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6889            }))
 6890            .on_action(
 6891                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6892                    workspace.activate_previous_pane(window, cx)
 6893                }),
 6894            )
 6895            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6896                workspace.activate_next_pane(window, cx)
 6897            }))
 6898            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6899                workspace.activate_last_pane(window, cx)
 6900            }))
 6901            .on_action(
 6902                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6903                    workspace.activate_next_window(cx)
 6904                }),
 6905            )
 6906            .on_action(
 6907                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6908                    workspace.activate_previous_window(cx)
 6909                }),
 6910            )
 6911            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6912                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6913            }))
 6914            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6915                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6916            }))
 6917            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6918                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6919            }))
 6920            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6921                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6922            }))
 6923            .on_action(cx.listener(
 6924                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6925                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6926                },
 6927            ))
 6928            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6929                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6930            }))
 6931            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6932                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6933            }))
 6934            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6935                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6936            }))
 6937            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6938                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6939            }))
 6940            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6941                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6942                    SplitDirection::Down,
 6943                    SplitDirection::Up,
 6944                    SplitDirection::Right,
 6945                    SplitDirection::Left,
 6946                ];
 6947                for dir in DIRECTION_PRIORITY {
 6948                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6949                        workspace.swap_pane_in_direction(dir, cx);
 6950                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6951                        break;
 6952                    }
 6953                }
 6954            }))
 6955            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6956                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6957            }))
 6958            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6959                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6960            }))
 6961            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6962                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6963            }))
 6964            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6965                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6966            }))
 6967            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6968                this.toggle_dock(DockPosition::Left, window, cx);
 6969            }))
 6970            .on_action(cx.listener(
 6971                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6972                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6973                },
 6974            ))
 6975            .on_action(cx.listener(
 6976                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6977                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6978                },
 6979            ))
 6980            .on_action(cx.listener(
 6981                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6982                    if !workspace.close_active_dock(window, cx) {
 6983                        cx.propagate();
 6984                    }
 6985                },
 6986            ))
 6987            .on_action(
 6988                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6989                    workspace.close_all_docks(window, cx);
 6990                }),
 6991            )
 6992            .on_action(cx.listener(Self::toggle_all_docks))
 6993            .on_action(cx.listener(
 6994                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6995                    workspace.clear_all_notifications(cx);
 6996                },
 6997            ))
 6998            .on_action(cx.listener(
 6999                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 7000                    workspace.clear_navigation_history(window, cx);
 7001                },
 7002            ))
 7003            .on_action(cx.listener(
 7004                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 7005                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 7006                        workspace.suppress_notification(&notification_id, cx);
 7007                    }
 7008                },
 7009            ))
 7010            .on_action(cx.listener(
 7011                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 7012                    workspace.show_worktree_trust_security_modal(true, window, cx);
 7013                },
 7014            ))
 7015            .on_action(
 7016                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 7017                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 7018                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 7019                            trusted_worktrees.clear_trusted_paths()
 7020                        });
 7021                        let db = WorkspaceDb::global(cx);
 7022                        cx.spawn(async move |_, cx| {
 7023                            if db.clear_trusted_worktrees().await.log_err().is_some() {
 7024                                cx.update(|cx| reload(cx));
 7025                            }
 7026                        })
 7027                        .detach();
 7028                    }
 7029                }),
 7030            )
 7031            .on_action(cx.listener(
 7032                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 7033                    workspace.reopen_closed_item(window, cx).detach();
 7034                },
 7035            ))
 7036            .on_action(cx.listener(
 7037                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 7038                    for dock in workspace.all_docks() {
 7039                        if dock.focus_handle(cx).contains_focused(window, cx) {
 7040                            let panel = dock.read(cx).active_panel().cloned();
 7041                            if let Some(panel) = panel {
 7042                                dock.update(cx, |dock, cx| {
 7043                                    dock.set_panel_size_state(
 7044                                        panel.as_ref(),
 7045                                        dock::PanelSizeState::default(),
 7046                                        cx,
 7047                                    );
 7048                                });
 7049                            }
 7050                            return;
 7051                        }
 7052                    }
 7053                },
 7054            ))
 7055            .on_action(cx.listener(
 7056                |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
 7057                    for dock in workspace.all_docks() {
 7058                        let panel = dock.read(cx).visible_panel().cloned();
 7059                        if let Some(panel) = panel {
 7060                            dock.update(cx, |dock, cx| {
 7061                                dock.set_panel_size_state(
 7062                                    panel.as_ref(),
 7063                                    dock::PanelSizeState::default(),
 7064                                    cx,
 7065                                );
 7066                            });
 7067                        }
 7068                    }
 7069                },
 7070            ))
 7071            .on_action(cx.listener(
 7072                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 7073                    adjust_active_dock_size_by_px(
 7074                        px_with_ui_font_fallback(act.px, cx),
 7075                        workspace,
 7076                        window,
 7077                        cx,
 7078                    );
 7079                },
 7080            ))
 7081            .on_action(cx.listener(
 7082                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 7083                    adjust_active_dock_size_by_px(
 7084                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7085                        workspace,
 7086                        window,
 7087                        cx,
 7088                    );
 7089                },
 7090            ))
 7091            .on_action(cx.listener(
 7092                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 7093                    adjust_open_docks_size_by_px(
 7094                        px_with_ui_font_fallback(act.px, cx),
 7095                        workspace,
 7096                        window,
 7097                        cx,
 7098                    );
 7099                },
 7100            ))
 7101            .on_action(cx.listener(
 7102                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 7103                    adjust_open_docks_size_by_px(
 7104                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7105                        workspace,
 7106                        window,
 7107                        cx,
 7108                    );
 7109                },
 7110            ))
 7111            .on_action(cx.listener(Workspace::toggle_centered_layout))
 7112            .on_action(cx.listener(
 7113                |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
 7114                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7115                        let dock = active_dock.read(cx);
 7116                        if let Some(active_panel) = dock.active_panel() {
 7117                            if active_panel.pane(cx).is_none() {
 7118                                let mut recent_pane: Option<Entity<Pane>> = None;
 7119                                let mut recent_timestamp = 0;
 7120                                for pane_handle in workspace.panes() {
 7121                                    let pane = pane_handle.read(cx);
 7122                                    for entry in pane.activation_history() {
 7123                                        if entry.timestamp > recent_timestamp {
 7124                                            recent_timestamp = entry.timestamp;
 7125                                            recent_pane = Some(pane_handle.clone());
 7126                                        }
 7127                                    }
 7128                                }
 7129
 7130                                if let Some(pane) = recent_pane {
 7131                                    let wrap_around = action.wrap_around;
 7132                                    pane.update(cx, |pane, cx| {
 7133                                        let current_index = pane.active_item_index();
 7134                                        let items_len = pane.items_len();
 7135                                        if items_len > 0 {
 7136                                            let next_index = if current_index + 1 < items_len {
 7137                                                current_index + 1
 7138                                            } else if wrap_around {
 7139                                                0
 7140                                            } else {
 7141                                                return;
 7142                                            };
 7143                                            pane.activate_item(
 7144                                                next_index, false, false, window, cx,
 7145                                            );
 7146                                        }
 7147                                    });
 7148                                    return;
 7149                                }
 7150                            }
 7151                        }
 7152                    }
 7153                    cx.propagate();
 7154                },
 7155            ))
 7156            .on_action(cx.listener(
 7157                |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
 7158                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7159                        let dock = active_dock.read(cx);
 7160                        if let Some(active_panel) = dock.active_panel() {
 7161                            if active_panel.pane(cx).is_none() {
 7162                                let mut recent_pane: Option<Entity<Pane>> = None;
 7163                                let mut recent_timestamp = 0;
 7164                                for pane_handle in workspace.panes() {
 7165                                    let pane = pane_handle.read(cx);
 7166                                    for entry in pane.activation_history() {
 7167                                        if entry.timestamp > recent_timestamp {
 7168                                            recent_timestamp = entry.timestamp;
 7169                                            recent_pane = Some(pane_handle.clone());
 7170                                        }
 7171                                    }
 7172                                }
 7173
 7174                                if let Some(pane) = recent_pane {
 7175                                    let wrap_around = action.wrap_around;
 7176                                    pane.update(cx, |pane, cx| {
 7177                                        let current_index = pane.active_item_index();
 7178                                        let items_len = pane.items_len();
 7179                                        if items_len > 0 {
 7180                                            let prev_index = if current_index > 0 {
 7181                                                current_index - 1
 7182                                            } else if wrap_around {
 7183                                                items_len.saturating_sub(1)
 7184                                            } else {
 7185                                                return;
 7186                                            };
 7187                                            pane.activate_item(
 7188                                                prev_index, false, false, window, cx,
 7189                                            );
 7190                                        }
 7191                                    });
 7192                                    return;
 7193                                }
 7194                            }
 7195                        }
 7196                    }
 7197                    cx.propagate();
 7198                },
 7199            ))
 7200            .on_action(cx.listener(
 7201                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 7202                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7203                        let dock = active_dock.read(cx);
 7204                        if let Some(active_panel) = dock.active_panel() {
 7205                            if active_panel.pane(cx).is_none() {
 7206                                let active_pane = workspace.active_pane().clone();
 7207                                active_pane.update(cx, |pane, cx| {
 7208                                    pane.close_active_item(action, window, cx)
 7209                                        .detach_and_log_err(cx);
 7210                                });
 7211                                return;
 7212                            }
 7213                        }
 7214                    }
 7215                    cx.propagate();
 7216                },
 7217            ))
 7218            .on_action(
 7219                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 7220                    let pane = workspace.active_pane().clone();
 7221                    if let Some(item) = pane.read(cx).active_item() {
 7222                        item.toggle_read_only(window, cx);
 7223                    }
 7224                }),
 7225            )
 7226            .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
 7227                workspace.focus_center_pane(window, cx);
 7228            }))
 7229            .on_action(cx.listener(Workspace::cancel))
 7230    }
 7231
 7232    #[cfg(any(test, feature = "test-support"))]
 7233    pub fn set_random_database_id(&mut self) {
 7234        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 7235    }
 7236
 7237    #[cfg(any(test, feature = "test-support"))]
 7238    pub(crate) fn test_new(
 7239        project: Entity<Project>,
 7240        window: &mut Window,
 7241        cx: &mut Context<Self>,
 7242    ) -> Self {
 7243        use node_runtime::NodeRuntime;
 7244        use session::Session;
 7245
 7246        let client = project.read(cx).client();
 7247        let user_store = project.read(cx).user_store();
 7248        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 7249        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 7250        window.activate_window();
 7251        let app_state = Arc::new(AppState {
 7252            languages: project.read(cx).languages().clone(),
 7253            workspace_store,
 7254            client,
 7255            user_store,
 7256            fs: project.read(cx).fs().clone(),
 7257            build_window_options: |_, _| Default::default(),
 7258            node_runtime: NodeRuntime::unavailable(),
 7259            session,
 7260        });
 7261        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 7262        workspace
 7263            .active_pane
 7264            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 7265        workspace
 7266    }
 7267
 7268    pub fn register_action<A: Action>(
 7269        &mut self,
 7270        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 7271    ) -> &mut Self {
 7272        let callback = Arc::new(callback);
 7273
 7274        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 7275            let callback = callback.clone();
 7276            div.on_action(cx.listener(move |workspace, event, window, cx| {
 7277                (callback)(workspace, event, window, cx)
 7278            }))
 7279        }));
 7280        self
 7281    }
 7282    pub fn register_action_renderer(
 7283        &mut self,
 7284        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 7285    ) -> &mut Self {
 7286        self.workspace_actions.push(Box::new(callback));
 7287        self
 7288    }
 7289
 7290    fn add_workspace_actions_listeners(
 7291        &self,
 7292        mut div: Div,
 7293        window: &mut Window,
 7294        cx: &mut Context<Self>,
 7295    ) -> Div {
 7296        for action in self.workspace_actions.iter() {
 7297            div = (action)(div, self, window, cx)
 7298        }
 7299        div
 7300    }
 7301
 7302    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 7303        self.modal_layer.read(cx).has_active_modal()
 7304    }
 7305
 7306    pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
 7307        self.modal_layer
 7308            .read(cx)
 7309            .is_active_modal_command_palette(cx)
 7310    }
 7311
 7312    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7313        self.modal_layer.read(cx).active_modal()
 7314    }
 7315
 7316    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7317    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7318    /// If no modal is active, the new modal will be shown.
 7319    ///
 7320    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7321    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7322    /// will not be shown.
 7323    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7324    where
 7325        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7326    {
 7327        self.modal_layer.update(cx, |modal_layer, cx| {
 7328            modal_layer.toggle_modal(window, cx, build)
 7329        })
 7330    }
 7331
 7332    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7333        self.modal_layer
 7334            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7335    }
 7336
 7337    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7338        self.toast_layer
 7339            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7340    }
 7341
 7342    pub fn toggle_centered_layout(
 7343        &mut self,
 7344        _: &ToggleCenteredLayout,
 7345        _: &mut Window,
 7346        cx: &mut Context<Self>,
 7347    ) {
 7348        self.centered_layout = !self.centered_layout;
 7349        if let Some(database_id) = self.database_id() {
 7350            let db = WorkspaceDb::global(cx);
 7351            let centered_layout = self.centered_layout;
 7352            cx.background_spawn(async move {
 7353                db.set_centered_layout(database_id, centered_layout).await
 7354            })
 7355            .detach_and_log_err(cx);
 7356        }
 7357        cx.notify();
 7358    }
 7359
 7360    fn adjust_padding(padding: Option<f32>) -> f32 {
 7361        padding
 7362            .unwrap_or(CenteredPaddingSettings::default().0)
 7363            .clamp(
 7364                CenteredPaddingSettings::MIN_PADDING,
 7365                CenteredPaddingSettings::MAX_PADDING,
 7366            )
 7367    }
 7368
 7369    fn render_dock(
 7370        &self,
 7371        position: DockPosition,
 7372        dock: &Entity<Dock>,
 7373        window: &mut Window,
 7374        cx: &mut App,
 7375    ) -> Option<Div> {
 7376        if self.zoomed_position == Some(position) {
 7377            return None;
 7378        }
 7379
 7380        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7381            let pane = panel.pane(cx)?;
 7382            let follower_states = &self.follower_states;
 7383            leader_border_for_pane(follower_states, &pane, window, cx)
 7384        });
 7385
 7386        let mut container = div()
 7387            .flex()
 7388            .overflow_hidden()
 7389            .flex_none()
 7390            .child(dock.clone())
 7391            .children(leader_border);
 7392
 7393        // Apply sizing only when the dock is open. When closed the dock is still
 7394        // included in the element tree so its focus handle remains mounted — without
 7395        // this, toggle_panel_focus cannot focus the panel when the dock is closed.
 7396        let dock = dock.read(cx);
 7397        if let Some(panel) = dock.visible_panel() {
 7398            let size_state = dock.stored_panel_size_state(panel.as_ref());
 7399            if position.axis() == Axis::Horizontal {
 7400                let use_flexible = panel.has_flexible_size(window, cx);
 7401                let flex_grow = if use_flexible {
 7402                    size_state
 7403                        .and_then(|state| state.flex)
 7404                        .or_else(|| self.default_dock_flex(position))
 7405                } else {
 7406                    None
 7407                };
 7408                if let Some(grow) = flex_grow {
 7409                    let grow = grow.max(0.001);
 7410                    let style = container.style();
 7411                    style.flex_grow = Some(grow);
 7412                    style.flex_shrink = Some(1.0);
 7413                    style.flex_basis = Some(relative(0.).into());
 7414                } else {
 7415                    let size = size_state
 7416                        .and_then(|state| state.size)
 7417                        .unwrap_or_else(|| panel.default_size(window, cx));
 7418                    container = container.w(size);
 7419                }
 7420            } else {
 7421                let size = size_state
 7422                    .and_then(|state| state.size)
 7423                    .unwrap_or_else(|| panel.default_size(window, cx));
 7424                container = container.h(size);
 7425            }
 7426        }
 7427
 7428        Some(container)
 7429    }
 7430
 7431    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7432        window
 7433            .root::<MultiWorkspace>()
 7434            .flatten()
 7435            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7436    }
 7437
 7438    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7439        self.zoomed.as_ref()
 7440    }
 7441
 7442    pub fn activate_next_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 next_window =
 7448            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7449                || {
 7450                    windows
 7451                        .iter()
 7452                        .cycle()
 7453                        .skip_while(|window| window.window_id() != current_window_id)
 7454                        .nth(1)
 7455                },
 7456            );
 7457
 7458        if let Some(window) = next_window {
 7459            window
 7460                .update(cx, |_, window, _| window.activate_window())
 7461                .ok();
 7462        }
 7463    }
 7464
 7465    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7466        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7467            return;
 7468        };
 7469        let windows = cx.windows();
 7470        let prev_window =
 7471            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7472                || {
 7473                    windows
 7474                        .iter()
 7475                        .rev()
 7476                        .cycle()
 7477                        .skip_while(|window| window.window_id() != current_window_id)
 7478                        .nth(1)
 7479                },
 7480            );
 7481
 7482        if let Some(window) = prev_window {
 7483            window
 7484                .update(cx, |_, window, _| window.activate_window())
 7485                .ok();
 7486        }
 7487    }
 7488
 7489    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7490        if cx.stop_active_drag(window) {
 7491        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7492            dismiss_app_notification(&notification_id, cx);
 7493        } else {
 7494            cx.propagate();
 7495        }
 7496    }
 7497
 7498    fn resize_dock(
 7499        &mut self,
 7500        dock_pos: DockPosition,
 7501        new_size: Pixels,
 7502        window: &mut Window,
 7503        cx: &mut Context<Self>,
 7504    ) {
 7505        match dock_pos {
 7506            DockPosition::Left => self.resize_left_dock(new_size, window, cx),
 7507            DockPosition::Right => self.resize_right_dock(new_size, window, cx),
 7508            DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
 7509        }
 7510    }
 7511
 7512    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7513        let workspace_width = self.bounds.size.width;
 7514        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7515
 7516        self.right_dock.read_with(cx, |right_dock, cx| {
 7517            let right_dock_size = right_dock
 7518                .stored_active_panel_size(window, cx)
 7519                .unwrap_or(Pixels::ZERO);
 7520            if right_dock_size + size > workspace_width {
 7521                size = workspace_width - right_dock_size
 7522            }
 7523        });
 7524
 7525        let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
 7526        self.left_dock.update(cx, |left_dock, cx| {
 7527            if WorkspaceSettings::get_global(cx)
 7528                .resize_all_panels_in_dock
 7529                .contains(&DockPosition::Left)
 7530            {
 7531                left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7532            } else {
 7533                left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7534            }
 7535        });
 7536    }
 7537
 7538    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7539        let workspace_width = self.bounds.size.width;
 7540        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7541        self.left_dock.read_with(cx, |left_dock, cx| {
 7542            let left_dock_size = left_dock
 7543                .stored_active_panel_size(window, cx)
 7544                .unwrap_or(Pixels::ZERO);
 7545            if left_dock_size + size > workspace_width {
 7546                size = workspace_width - left_dock_size
 7547            }
 7548        });
 7549        let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
 7550        self.right_dock.update(cx, |right_dock, cx| {
 7551            if WorkspaceSettings::get_global(cx)
 7552                .resize_all_panels_in_dock
 7553                .contains(&DockPosition::Right)
 7554            {
 7555                right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7556            } else {
 7557                right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7558            }
 7559        });
 7560    }
 7561
 7562    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7563        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7564        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7565            if WorkspaceSettings::get_global(cx)
 7566                .resize_all_panels_in_dock
 7567                .contains(&DockPosition::Bottom)
 7568            {
 7569                bottom_dock.resize_all_panels(Some(size), None, window, cx);
 7570            } else {
 7571                bottom_dock.resize_active_panel(Some(size), None, window, cx);
 7572            }
 7573        });
 7574    }
 7575
 7576    fn toggle_edit_predictions_all_files(
 7577        &mut self,
 7578        _: &ToggleEditPrediction,
 7579        _window: &mut Window,
 7580        cx: &mut Context<Self>,
 7581    ) {
 7582        let fs = self.project().read(cx).fs().clone();
 7583        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7584        update_settings_file(fs, cx, move |file, _| {
 7585            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7586        });
 7587    }
 7588
 7589    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7590        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7591        let next_mode = match current_mode {
 7592            Some(theme_settings::ThemeAppearanceMode::Light) => {
 7593                theme_settings::ThemeAppearanceMode::Dark
 7594            }
 7595            Some(theme_settings::ThemeAppearanceMode::Dark) => {
 7596                theme_settings::ThemeAppearanceMode::Light
 7597            }
 7598            Some(theme_settings::ThemeAppearanceMode::System) | None => {
 7599                match cx.theme().appearance() {
 7600                    theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
 7601                    theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
 7602                }
 7603            }
 7604        };
 7605
 7606        let fs = self.project().read(cx).fs().clone();
 7607        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7608            theme_settings::set_mode(settings, next_mode);
 7609        });
 7610    }
 7611
 7612    pub fn show_worktree_trust_security_modal(
 7613        &mut self,
 7614        toggle: bool,
 7615        window: &mut Window,
 7616        cx: &mut Context<Self>,
 7617    ) {
 7618        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7619            if toggle {
 7620                security_modal.update(cx, |security_modal, cx| {
 7621                    security_modal.dismiss(cx);
 7622                })
 7623            } else {
 7624                security_modal.update(cx, |security_modal, cx| {
 7625                    security_modal.refresh_restricted_paths(cx);
 7626                });
 7627            }
 7628        } else {
 7629            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7630                .map(|trusted_worktrees| {
 7631                    trusted_worktrees
 7632                        .read(cx)
 7633                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7634                })
 7635                .unwrap_or(false);
 7636            if has_restricted_worktrees {
 7637                let project = self.project().read(cx);
 7638                let remote_host = project
 7639                    .remote_connection_options(cx)
 7640                    .map(RemoteHostLocation::from);
 7641                let worktree_store = project.worktree_store().downgrade();
 7642                self.toggle_modal(window, cx, |_, cx| {
 7643                    SecurityModal::new(worktree_store, remote_host, cx)
 7644                });
 7645            }
 7646        }
 7647    }
 7648}
 7649
 7650pub trait AnyActiveCall {
 7651    fn entity(&self) -> AnyEntity;
 7652    fn is_in_room(&self, _: &App) -> bool;
 7653    fn room_id(&self, _: &App) -> Option<u64>;
 7654    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7655    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7656    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7657    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7658    fn is_sharing_project(&self, _: &App) -> bool;
 7659    fn has_remote_participants(&self, _: &App) -> bool;
 7660    fn local_participant_is_guest(&self, _: &App) -> bool;
 7661    fn client(&self, _: &App) -> Arc<Client>;
 7662    fn share_on_join(&self, _: &App) -> bool;
 7663    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7664    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7665    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7666    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7667    fn join_project(
 7668        &self,
 7669        _: u64,
 7670        _: Arc<LanguageRegistry>,
 7671        _: Arc<dyn Fs>,
 7672        _: &mut App,
 7673    ) -> Task<Result<Entity<Project>>>;
 7674    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7675    fn subscribe(
 7676        &self,
 7677        _: &mut Window,
 7678        _: &mut Context<Workspace>,
 7679        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7680    ) -> Subscription;
 7681    fn create_shared_screen(
 7682        &self,
 7683        _: PeerId,
 7684        _: &Entity<Pane>,
 7685        _: &mut Window,
 7686        _: &mut App,
 7687    ) -> Option<Entity<SharedScreen>>;
 7688}
 7689
 7690#[derive(Clone)]
 7691pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7692impl Global for GlobalAnyActiveCall {}
 7693
 7694impl GlobalAnyActiveCall {
 7695    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7696        cx.try_global()
 7697    }
 7698
 7699    pub(crate) fn global(cx: &App) -> &Self {
 7700        cx.global()
 7701    }
 7702}
 7703
 7704pub fn merge_conflict_notification_id() -> NotificationId {
 7705    struct MergeConflictNotification;
 7706    NotificationId::unique::<MergeConflictNotification>()
 7707}
 7708
 7709/// Workspace-local view of a remote participant's location.
 7710#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7711pub enum ParticipantLocation {
 7712    SharedProject { project_id: u64 },
 7713    UnsharedProject,
 7714    External,
 7715}
 7716
 7717impl ParticipantLocation {
 7718    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7719        match location
 7720            .and_then(|l| l.variant)
 7721            .context("participant location was not provided")?
 7722        {
 7723            proto::participant_location::Variant::SharedProject(project) => {
 7724                Ok(Self::SharedProject {
 7725                    project_id: project.id,
 7726                })
 7727            }
 7728            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7729            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7730        }
 7731    }
 7732}
 7733/// Workspace-local view of a remote collaborator's state.
 7734/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7735#[derive(Clone)]
 7736pub struct RemoteCollaborator {
 7737    pub user: Arc<User>,
 7738    pub peer_id: PeerId,
 7739    pub location: ParticipantLocation,
 7740    pub participant_index: ParticipantIndex,
 7741}
 7742
 7743pub enum ActiveCallEvent {
 7744    ParticipantLocationChanged { participant_id: PeerId },
 7745    RemoteVideoTracksChanged { participant_id: PeerId },
 7746}
 7747
 7748fn leader_border_for_pane(
 7749    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7750    pane: &Entity<Pane>,
 7751    _: &Window,
 7752    cx: &App,
 7753) -> Option<Div> {
 7754    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7755        if state.pane() == pane {
 7756            Some((*leader_id, state))
 7757        } else {
 7758            None
 7759        }
 7760    })?;
 7761
 7762    let mut leader_color = match leader_id {
 7763        CollaboratorId::PeerId(leader_peer_id) => {
 7764            let leader = GlobalAnyActiveCall::try_global(cx)?
 7765                .0
 7766                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7767
 7768            cx.theme()
 7769                .players()
 7770                .color_for_participant(leader.participant_index.0)
 7771                .cursor
 7772        }
 7773        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7774    };
 7775    leader_color.fade_out(0.3);
 7776    Some(
 7777        div()
 7778            .absolute()
 7779            .size_full()
 7780            .left_0()
 7781            .top_0()
 7782            .border_2()
 7783            .border_color(leader_color),
 7784    )
 7785}
 7786
 7787fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7788    ZED_WINDOW_POSITION
 7789        .zip(*ZED_WINDOW_SIZE)
 7790        .map(|(position, size)| Bounds {
 7791            origin: position,
 7792            size,
 7793        })
 7794}
 7795
 7796fn open_items(
 7797    serialized_workspace: Option<SerializedWorkspace>,
 7798    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7799    window: &mut Window,
 7800    cx: &mut Context<Workspace>,
 7801) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7802    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7803        Workspace::load_workspace(
 7804            serialized_workspace,
 7805            project_paths_to_open
 7806                .iter()
 7807                .map(|(_, project_path)| project_path)
 7808                .cloned()
 7809                .collect(),
 7810            window,
 7811            cx,
 7812        )
 7813    });
 7814
 7815    cx.spawn_in(window, async move |workspace, cx| {
 7816        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7817
 7818        if let Some(restored_items) = restored_items {
 7819            let restored_items = restored_items.await?;
 7820
 7821            let restored_project_paths = restored_items
 7822                .iter()
 7823                .filter_map(|item| {
 7824                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7825                        .ok()
 7826                        .flatten()
 7827                })
 7828                .collect::<HashSet<_>>();
 7829
 7830            for restored_item in restored_items {
 7831                opened_items.push(restored_item.map(Ok));
 7832            }
 7833
 7834            project_paths_to_open
 7835                .iter_mut()
 7836                .for_each(|(_, project_path)| {
 7837                    if let Some(project_path_to_open) = project_path
 7838                        && restored_project_paths.contains(project_path_to_open)
 7839                    {
 7840                        *project_path = None;
 7841                    }
 7842                });
 7843        } else {
 7844            for _ in 0..project_paths_to_open.len() {
 7845                opened_items.push(None);
 7846            }
 7847        }
 7848        assert!(opened_items.len() == project_paths_to_open.len());
 7849
 7850        let tasks =
 7851            project_paths_to_open
 7852                .into_iter()
 7853                .enumerate()
 7854                .map(|(ix, (abs_path, project_path))| {
 7855                    let workspace = workspace.clone();
 7856                    cx.spawn(async move |cx| {
 7857                        let file_project_path = project_path?;
 7858                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7859                            workspace.project().update(cx, |project, cx| {
 7860                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7861                            })
 7862                        });
 7863
 7864                        // We only want to open file paths here. If one of the items
 7865                        // here is a directory, it was already opened further above
 7866                        // with a `find_or_create_worktree`.
 7867                        if let Ok(task) = abs_path_task
 7868                            && task.await.is_none_or(|p| p.is_file())
 7869                        {
 7870                            return Some((
 7871                                ix,
 7872                                workspace
 7873                                    .update_in(cx, |workspace, window, cx| {
 7874                                        workspace.open_path(
 7875                                            file_project_path,
 7876                                            None,
 7877                                            true,
 7878                                            window,
 7879                                            cx,
 7880                                        )
 7881                                    })
 7882                                    .log_err()?
 7883                                    .await,
 7884                            ));
 7885                        }
 7886                        None
 7887                    })
 7888                });
 7889
 7890        let tasks = tasks.collect::<Vec<_>>();
 7891
 7892        let tasks = futures::future::join_all(tasks);
 7893        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7894            opened_items[ix] = Some(path_open_result);
 7895        }
 7896
 7897        Ok(opened_items)
 7898    })
 7899}
 7900
 7901#[derive(Clone)]
 7902enum ActivateInDirectionTarget {
 7903    Pane(Entity<Pane>),
 7904    Dock(Entity<Dock>),
 7905    Sidebar(FocusHandle),
 7906}
 7907
 7908fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7909    window
 7910        .update(cx, |multi_workspace, _, cx| {
 7911            let workspace = multi_workspace.workspace().clone();
 7912            workspace.update(cx, |workspace, cx| {
 7913                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7914                    struct DatabaseFailedNotification;
 7915
 7916                    workspace.show_notification(
 7917                        NotificationId::unique::<DatabaseFailedNotification>(),
 7918                        cx,
 7919                        |cx| {
 7920                            cx.new(|cx| {
 7921                                MessageNotification::new("Failed to load the database file.", cx)
 7922                                    .primary_message("File an Issue")
 7923                                    .primary_icon(IconName::Plus)
 7924                                    .primary_on_click(|window, cx| {
 7925                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7926                                    })
 7927                            })
 7928                        },
 7929                    );
 7930                }
 7931            });
 7932        })
 7933        .log_err();
 7934}
 7935
 7936fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7937    if val == 0 {
 7938        ThemeSettings::get_global(cx).ui_font_size(cx)
 7939    } else {
 7940        px(val as f32)
 7941    }
 7942}
 7943
 7944fn adjust_active_dock_size_by_px(
 7945    px: Pixels,
 7946    workspace: &mut Workspace,
 7947    window: &mut Window,
 7948    cx: &mut Context<Workspace>,
 7949) {
 7950    let Some(active_dock) = workspace
 7951        .all_docks()
 7952        .into_iter()
 7953        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7954    else {
 7955        return;
 7956    };
 7957    let dock = active_dock.read(cx);
 7958    let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
 7959        return;
 7960    };
 7961    workspace.resize_dock(dock.position(), panel_size + px, window, cx);
 7962}
 7963
 7964fn adjust_open_docks_size_by_px(
 7965    px: Pixels,
 7966    workspace: &mut Workspace,
 7967    window: &mut Window,
 7968    cx: &mut Context<Workspace>,
 7969) {
 7970    let docks = workspace
 7971        .all_docks()
 7972        .into_iter()
 7973        .filter_map(|dock_entity| {
 7974            let dock = dock_entity.read(cx);
 7975            if dock.is_open() {
 7976                let dock_pos = dock.position();
 7977                let panel_size = workspace.dock_size(&dock, window, cx)?;
 7978                Some((dock_pos, panel_size + px))
 7979            } else {
 7980                None
 7981            }
 7982        })
 7983        .collect::<Vec<_>>();
 7984
 7985    for (position, new_size) in docks {
 7986        workspace.resize_dock(position, new_size, window, cx);
 7987    }
 7988}
 7989
 7990impl Focusable for Workspace {
 7991    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7992        self.active_pane.focus_handle(cx)
 7993    }
 7994}
 7995
 7996#[derive(Clone)]
 7997struct DraggedDock(DockPosition);
 7998
 7999impl Render for DraggedDock {
 8000    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 8001        gpui::Empty
 8002    }
 8003}
 8004
 8005impl Render for Workspace {
 8006    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 8007        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 8008        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 8009            log::info!("Rendered first frame");
 8010        }
 8011
 8012        let centered_layout = self.centered_layout
 8013            && self.center.panes().len() == 1
 8014            && self.active_item(cx).is_some();
 8015        let render_padding = |size| {
 8016            (size > 0.0).then(|| {
 8017                div()
 8018                    .h_full()
 8019                    .w(relative(size))
 8020                    .bg(cx.theme().colors().editor_background)
 8021                    .border_color(cx.theme().colors().pane_group_border)
 8022            })
 8023        };
 8024        let paddings = if centered_layout {
 8025            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 8026            (
 8027                render_padding(Self::adjust_padding(
 8028                    settings.left_padding.map(|padding| padding.0),
 8029                )),
 8030                render_padding(Self::adjust_padding(
 8031                    settings.right_padding.map(|padding| padding.0),
 8032                )),
 8033            )
 8034        } else {
 8035            (None, None)
 8036        };
 8037        let ui_font = theme_settings::setup_ui_font(window, cx);
 8038
 8039        let theme = cx.theme().clone();
 8040        let colors = theme.colors();
 8041        let notification_entities = self
 8042            .notifications
 8043            .iter()
 8044            .map(|(_, notification)| notification.entity_id())
 8045            .collect::<Vec<_>>();
 8046        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 8047
 8048        div()
 8049            .relative()
 8050            .size_full()
 8051            .flex()
 8052            .flex_col()
 8053            .font(ui_font)
 8054            .gap_0()
 8055                .justify_start()
 8056                .items_start()
 8057                .text_color(colors.text)
 8058                .overflow_hidden()
 8059                .children(self.titlebar_item.clone())
 8060                .on_modifiers_changed(move |_, _, cx| {
 8061                    for &id in &notification_entities {
 8062                        cx.notify(id);
 8063                    }
 8064                })
 8065                .child(
 8066                    div()
 8067                        .size_full()
 8068                        .relative()
 8069                        .flex_1()
 8070                        .flex()
 8071                        .flex_col()
 8072                        .child(
 8073                            div()
 8074                                .id("workspace")
 8075                                .bg(colors.background)
 8076                                .relative()
 8077                                .flex_1()
 8078                                .w_full()
 8079                                .flex()
 8080                                .flex_col()
 8081                                .overflow_hidden()
 8082                                .border_t_1()
 8083                                .border_b_1()
 8084                                .border_color(colors.border)
 8085                                .child({
 8086                                    let this = cx.entity();
 8087                                    canvas(
 8088                                        move |bounds, window, cx| {
 8089                                            this.update(cx, |this, cx| {
 8090                                                let bounds_changed = this.bounds != bounds;
 8091                                                this.bounds = bounds;
 8092
 8093                                                if bounds_changed {
 8094                                                    this.left_dock.update(cx, |dock, cx| {
 8095                                                        dock.clamp_panel_size(
 8096                                                            bounds.size.width,
 8097                                                            window,
 8098                                                            cx,
 8099                                                        )
 8100                                                    });
 8101
 8102                                                    this.right_dock.update(cx, |dock, cx| {
 8103                                                        dock.clamp_panel_size(
 8104                                                            bounds.size.width,
 8105                                                            window,
 8106                                                            cx,
 8107                                                        )
 8108                                                    });
 8109
 8110                                                    this.bottom_dock.update(cx, |dock, cx| {
 8111                                                        dock.clamp_panel_size(
 8112                                                            bounds.size.height,
 8113                                                            window,
 8114                                                            cx,
 8115                                                        )
 8116                                                    });
 8117                                                }
 8118                                            })
 8119                                        },
 8120                                        |_, _, _, _| {},
 8121                                    )
 8122                                    .absolute()
 8123                                    .size_full()
 8124                                })
 8125                                .when(self.zoomed.is_none(), |this| {
 8126                                    this.on_drag_move(cx.listener(
 8127                                        move |workspace,
 8128                                              e: &DragMoveEvent<DraggedDock>,
 8129                                              window,
 8130                                              cx| {
 8131                                            if workspace.previous_dock_drag_coordinates
 8132                                                != Some(e.event.position)
 8133                                            {
 8134                                                workspace.previous_dock_drag_coordinates =
 8135                                                    Some(e.event.position);
 8136
 8137                                                match e.drag(cx).0 {
 8138                                                    DockPosition::Left => {
 8139                                                        workspace.resize_left_dock(
 8140                                                            e.event.position.x
 8141                                                                - workspace.bounds.left(),
 8142                                                            window,
 8143                                                            cx,
 8144                                                        );
 8145                                                    }
 8146                                                    DockPosition::Right => {
 8147                                                        workspace.resize_right_dock(
 8148                                                            workspace.bounds.right()
 8149                                                                - e.event.position.x,
 8150                                                            window,
 8151                                                            cx,
 8152                                                        );
 8153                                                    }
 8154                                                    DockPosition::Bottom => {
 8155                                                        workspace.resize_bottom_dock(
 8156                                                            workspace.bounds.bottom()
 8157                                                                - e.event.position.y,
 8158                                                            window,
 8159                                                            cx,
 8160                                                        );
 8161                                                    }
 8162                                                };
 8163                                                workspace.serialize_workspace(window, cx);
 8164                                            }
 8165                                        },
 8166                                    ))
 8167
 8168                                })
 8169                                .child({
 8170                                    match bottom_dock_layout {
 8171                                        BottomDockLayout::Full => div()
 8172                                            .flex()
 8173                                            .flex_col()
 8174                                            .h_full()
 8175                                            .child(
 8176                                                div()
 8177                                                    .flex()
 8178                                                    .flex_row()
 8179                                                    .flex_1()
 8180                                                    .overflow_hidden()
 8181                                                    .children(self.render_dock(
 8182                                                        DockPosition::Left,
 8183                                                        &self.left_dock,
 8184                                                        window,
 8185                                                        cx,
 8186                                                    ))
 8187
 8188                                                    .child(
 8189                                                        div()
 8190                                                            .flex()
 8191                                                            .flex_col()
 8192                                                            .flex_1()
 8193                                                            .overflow_hidden()
 8194                                                            .child(
 8195                                                                h_flex()
 8196                                                                    .flex_1()
 8197                                                                    .when_some(
 8198                                                                        paddings.0,
 8199                                                                        |this, p| {
 8200                                                                            this.child(
 8201                                                                                p.border_r_1(),
 8202                                                                            )
 8203                                                                        },
 8204                                                                    )
 8205                                                                    .child(self.center.render(
 8206                                                                        self.zoomed.as_ref(),
 8207                                                                        &PaneRenderContext {
 8208                                                                            follower_states:
 8209                                                                                &self.follower_states,
 8210                                                                            active_call: self.active_call(),
 8211                                                                            active_pane: &self.active_pane,
 8212                                                                            app_state: &self.app_state,
 8213                                                                            project: &self.project,
 8214                                                                            workspace: &self.weak_self,
 8215                                                                        },
 8216                                                                        window,
 8217                                                                        cx,
 8218                                                                    ))
 8219                                                                    .when_some(
 8220                                                                        paddings.1,
 8221                                                                        |this, p| {
 8222                                                                            this.child(
 8223                                                                                p.border_l_1(),
 8224                                                                            )
 8225                                                                        },
 8226                                                                    ),
 8227                                                            ),
 8228                                                    )
 8229
 8230                                                    .children(self.render_dock(
 8231                                                        DockPosition::Right,
 8232                                                        &self.right_dock,
 8233                                                        window,
 8234                                                        cx,
 8235                                                    )),
 8236                                            )
 8237                                            .child(div().w_full().children(self.render_dock(
 8238                                                DockPosition::Bottom,
 8239                                                &self.bottom_dock,
 8240                                                window,
 8241                                                cx
 8242                                            ))),
 8243
 8244                                        BottomDockLayout::LeftAligned => div()
 8245                                            .flex()
 8246                                            .flex_row()
 8247                                            .h_full()
 8248                                            .child(
 8249                                                div()
 8250                                                    .flex()
 8251                                                    .flex_col()
 8252                                                    .flex_1()
 8253                                                    .h_full()
 8254                                                    .child(
 8255                                                        div()
 8256                                                            .flex()
 8257                                                            .flex_row()
 8258                                                            .flex_1()
 8259                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 8260
 8261                                                            .child(
 8262                                                                div()
 8263                                                                    .flex()
 8264                                                                    .flex_col()
 8265                                                                    .flex_1()
 8266                                                                    .overflow_hidden()
 8267                                                                    .child(
 8268                                                                        h_flex()
 8269                                                                            .flex_1()
 8270                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8271                                                                            .child(self.center.render(
 8272                                                                                self.zoomed.as_ref(),
 8273                                                                                &PaneRenderContext {
 8274                                                                                    follower_states:
 8275                                                                                        &self.follower_states,
 8276                                                                                    active_call: self.active_call(),
 8277                                                                                    active_pane: &self.active_pane,
 8278                                                                                    app_state: &self.app_state,
 8279                                                                                    project: &self.project,
 8280                                                                                    workspace: &self.weak_self,
 8281                                                                                },
 8282                                                                                window,
 8283                                                                                cx,
 8284                                                                            ))
 8285                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8286                                                                    )
 8287                                                            )
 8288
 8289                                                    )
 8290                                                    .child(
 8291                                                        div()
 8292                                                            .w_full()
 8293                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8294                                                    ),
 8295                                            )
 8296                                            .children(self.render_dock(
 8297                                                DockPosition::Right,
 8298                                                &self.right_dock,
 8299                                                window,
 8300                                                cx,
 8301                                            )),
 8302                                        BottomDockLayout::RightAligned => div()
 8303                                            .flex()
 8304                                            .flex_row()
 8305                                            .h_full()
 8306                                            .children(self.render_dock(
 8307                                                DockPosition::Left,
 8308                                                &self.left_dock,
 8309                                                window,
 8310                                                cx,
 8311                                            ))
 8312
 8313                                            .child(
 8314                                                div()
 8315                                                    .flex()
 8316                                                    .flex_col()
 8317                                                    .flex_1()
 8318                                                    .h_full()
 8319                                                    .child(
 8320                                                        div()
 8321                                                            .flex()
 8322                                                            .flex_row()
 8323                                                            .flex_1()
 8324                                                            .child(
 8325                                                                div()
 8326                                                                    .flex()
 8327                                                                    .flex_col()
 8328                                                                    .flex_1()
 8329                                                                    .overflow_hidden()
 8330                                                                    .child(
 8331                                                                        h_flex()
 8332                                                                            .flex_1()
 8333                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8334                                                                            .child(self.center.render(
 8335                                                                                self.zoomed.as_ref(),
 8336                                                                                &PaneRenderContext {
 8337                                                                                    follower_states:
 8338                                                                                        &self.follower_states,
 8339                                                                                    active_call: self.active_call(),
 8340                                                                                    active_pane: &self.active_pane,
 8341                                                                                    app_state: &self.app_state,
 8342                                                                                    project: &self.project,
 8343                                                                                    workspace: &self.weak_self,
 8344                                                                                },
 8345                                                                                window,
 8346                                                                                cx,
 8347                                                                            ))
 8348                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8349                                                                    )
 8350                                                            )
 8351
 8352                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 8353                                                    )
 8354                                                    .child(
 8355                                                        div()
 8356                                                            .w_full()
 8357                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8358                                                    ),
 8359                                            ),
 8360                                        BottomDockLayout::Contained => div()
 8361                                            .flex()
 8362                                            .flex_row()
 8363                                            .h_full()
 8364                                            .children(self.render_dock(
 8365                                                DockPosition::Left,
 8366                                                &self.left_dock,
 8367                                                window,
 8368                                                cx,
 8369                                            ))
 8370
 8371                                            .child(
 8372                                                div()
 8373                                                    .flex()
 8374                                                    .flex_col()
 8375                                                    .flex_1()
 8376                                                    .overflow_hidden()
 8377                                                    .child(
 8378                                                        h_flex()
 8379                                                            .flex_1()
 8380                                                            .when_some(paddings.0, |this, p| {
 8381                                                                this.child(p.border_r_1())
 8382                                                            })
 8383                                                            .child(self.center.render(
 8384                                                                self.zoomed.as_ref(),
 8385                                                                &PaneRenderContext {
 8386                                                                    follower_states:
 8387                                                                        &self.follower_states,
 8388                                                                    active_call: self.active_call(),
 8389                                                                    active_pane: &self.active_pane,
 8390                                                                    app_state: &self.app_state,
 8391                                                                    project: &self.project,
 8392                                                                    workspace: &self.weak_self,
 8393                                                                },
 8394                                                                window,
 8395                                                                cx,
 8396                                                            ))
 8397                                                            .when_some(paddings.1, |this, p| {
 8398                                                                this.child(p.border_l_1())
 8399                                                            }),
 8400                                                    )
 8401                                                    .children(self.render_dock(
 8402                                                        DockPosition::Bottom,
 8403                                                        &self.bottom_dock,
 8404                                                        window,
 8405                                                        cx,
 8406                                                    )),
 8407                                            )
 8408
 8409                                            .children(self.render_dock(
 8410                                                DockPosition::Right,
 8411                                                &self.right_dock,
 8412                                                window,
 8413                                                cx,
 8414                                            )),
 8415                                    }
 8416                                })
 8417                                .children(self.zoomed.as_ref().and_then(|view| {
 8418                                    let zoomed_view = view.upgrade()?;
 8419                                    let div = div()
 8420                                        .occlude()
 8421                                        .absolute()
 8422                                        .overflow_hidden()
 8423                                        .border_color(colors.border)
 8424                                        .bg(colors.background)
 8425                                        .child(zoomed_view)
 8426                                        .inset_0()
 8427                                        .shadow_lg();
 8428
 8429                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8430                                       return Some(div);
 8431                                    }
 8432
 8433                                    Some(match self.zoomed_position {
 8434                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8435                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8436                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8437                                        None => {
 8438                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8439                                        }
 8440                                    })
 8441                                }))
 8442                                .children(self.render_notifications(window, cx)),
 8443                        )
 8444                        .when(self.status_bar_visible(cx), |parent| {
 8445                            parent.child(self.status_bar.clone())
 8446                        })
 8447                        .child(self.toast_layer.clone()),
 8448                )
 8449    }
 8450}
 8451
 8452impl WorkspaceStore {
 8453    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8454        Self {
 8455            workspaces: Default::default(),
 8456            _subscriptions: vec![
 8457                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8458                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8459            ],
 8460            client,
 8461        }
 8462    }
 8463
 8464    pub fn update_followers(
 8465        &self,
 8466        project_id: Option<u64>,
 8467        update: proto::update_followers::Variant,
 8468        cx: &App,
 8469    ) -> Option<()> {
 8470        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8471        let room_id = active_call.0.room_id(cx)?;
 8472        self.client
 8473            .send(proto::UpdateFollowers {
 8474                room_id,
 8475                project_id,
 8476                variant: Some(update),
 8477            })
 8478            .log_err()
 8479    }
 8480
 8481    pub async fn handle_follow(
 8482        this: Entity<Self>,
 8483        envelope: TypedEnvelope<proto::Follow>,
 8484        mut cx: AsyncApp,
 8485    ) -> Result<proto::FollowResponse> {
 8486        this.update(&mut cx, |this, cx| {
 8487            let follower = Follower {
 8488                project_id: envelope.payload.project_id,
 8489                peer_id: envelope.original_sender_id()?,
 8490            };
 8491
 8492            let mut response = proto::FollowResponse::default();
 8493
 8494            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8495                let Some(workspace) = weak_workspace.upgrade() else {
 8496                    return false;
 8497                };
 8498                window_handle
 8499                    .update(cx, |_, window, cx| {
 8500                        workspace.update(cx, |workspace, cx| {
 8501                            let handler_response =
 8502                                workspace.handle_follow(follower.project_id, window, cx);
 8503                            if let Some(active_view) = handler_response.active_view
 8504                                && workspace.project.read(cx).remote_id() == follower.project_id
 8505                            {
 8506                                response.active_view = Some(active_view)
 8507                            }
 8508                        });
 8509                    })
 8510                    .is_ok()
 8511            });
 8512
 8513            Ok(response)
 8514        })
 8515    }
 8516
 8517    async fn handle_update_followers(
 8518        this: Entity<Self>,
 8519        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8520        mut cx: AsyncApp,
 8521    ) -> Result<()> {
 8522        let leader_id = envelope.original_sender_id()?;
 8523        let update = envelope.payload;
 8524
 8525        this.update(&mut cx, |this, cx| {
 8526            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8527                let Some(workspace) = weak_workspace.upgrade() else {
 8528                    return false;
 8529                };
 8530                window_handle
 8531                    .update(cx, |_, window, cx| {
 8532                        workspace.update(cx, |workspace, cx| {
 8533                            let project_id = workspace.project.read(cx).remote_id();
 8534                            if update.project_id != project_id && update.project_id.is_some() {
 8535                                return;
 8536                            }
 8537                            workspace.handle_update_followers(
 8538                                leader_id,
 8539                                update.clone(),
 8540                                window,
 8541                                cx,
 8542                            );
 8543                        });
 8544                    })
 8545                    .is_ok()
 8546            });
 8547            Ok(())
 8548        })
 8549    }
 8550
 8551    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8552        self.workspaces.iter().map(|(_, weak)| weak)
 8553    }
 8554
 8555    pub fn workspaces_with_windows(
 8556        &self,
 8557    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8558        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8559    }
 8560}
 8561
 8562impl ViewId {
 8563    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8564        Ok(Self {
 8565            creator: message
 8566                .creator
 8567                .map(CollaboratorId::PeerId)
 8568                .context("creator is missing")?,
 8569            id: message.id,
 8570        })
 8571    }
 8572
 8573    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8574        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8575            Some(proto::ViewId {
 8576                creator: Some(peer_id),
 8577                id: self.id,
 8578            })
 8579        } else {
 8580            None
 8581        }
 8582    }
 8583}
 8584
 8585impl FollowerState {
 8586    fn pane(&self) -> &Entity<Pane> {
 8587        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8588    }
 8589}
 8590
 8591pub trait WorkspaceHandle {
 8592    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8593}
 8594
 8595impl WorkspaceHandle for Entity<Workspace> {
 8596    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8597        self.read(cx)
 8598            .worktrees(cx)
 8599            .flat_map(|worktree| {
 8600                let worktree_id = worktree.read(cx).id();
 8601                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8602                    worktree_id,
 8603                    path: f.path.clone(),
 8604                })
 8605            })
 8606            .collect::<Vec<_>>()
 8607    }
 8608}
 8609
 8610pub async fn last_opened_workspace_location(
 8611    db: &WorkspaceDb,
 8612    fs: &dyn fs::Fs,
 8613) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8614    db.last_workspace(fs)
 8615        .await
 8616        .log_err()
 8617        .flatten()
 8618        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8619}
 8620
 8621pub async fn last_session_workspace_locations(
 8622    db: &WorkspaceDb,
 8623    last_session_id: &str,
 8624    last_session_window_stack: Option<Vec<WindowId>>,
 8625    fs: &dyn fs::Fs,
 8626) -> Option<Vec<SessionWorkspace>> {
 8627    db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8628        .await
 8629        .log_err()
 8630}
 8631
 8632pub struct MultiWorkspaceRestoreResult {
 8633    pub window_handle: WindowHandle<MultiWorkspace>,
 8634    pub errors: Vec<anyhow::Error>,
 8635}
 8636
 8637pub async fn restore_multiworkspace(
 8638    multi_workspace: SerializedMultiWorkspace,
 8639    app_state: Arc<AppState>,
 8640    cx: &mut AsyncApp,
 8641) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8642    let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
 8643    let mut group_iter = workspaces.into_iter();
 8644    let first = group_iter
 8645        .next()
 8646        .context("window group must not be empty")?;
 8647
 8648    let window_handle = if first.paths.is_empty() {
 8649        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8650            .await?
 8651    } else {
 8652        let OpenResult { window, .. } = cx
 8653            .update(|cx| {
 8654                Workspace::new_local(
 8655                    first.paths.paths().to_vec(),
 8656                    app_state.clone(),
 8657                    None,
 8658                    None,
 8659                    None,
 8660                    OpenMode::Activate,
 8661                    cx,
 8662                )
 8663            })
 8664            .await?;
 8665        window
 8666    };
 8667
 8668    let mut errors = Vec::new();
 8669
 8670    for session_workspace in group_iter {
 8671        let error = if session_workspace.paths.is_empty() {
 8672            cx.update(|cx| {
 8673                open_workspace_by_id(
 8674                    session_workspace.workspace_id,
 8675                    app_state.clone(),
 8676                    Some(window_handle),
 8677                    cx,
 8678                )
 8679            })
 8680            .await
 8681            .err()
 8682        } else {
 8683            cx.update(|cx| {
 8684                Workspace::new_local(
 8685                    session_workspace.paths.paths().to_vec(),
 8686                    app_state.clone(),
 8687                    Some(window_handle),
 8688                    None,
 8689                    None,
 8690                    OpenMode::Add,
 8691                    cx,
 8692                )
 8693            })
 8694            .await
 8695            .err()
 8696        };
 8697
 8698        if let Some(error) = error {
 8699            errors.push(error);
 8700        }
 8701    }
 8702
 8703    if let Some(target_id) = state.active_workspace_id {
 8704        window_handle
 8705            .update(cx, |multi_workspace, window, cx| {
 8706                let target_index = multi_workspace
 8707                    .workspaces()
 8708                    .iter()
 8709                    .position(|ws| ws.read(cx).database_id() == Some(target_id));
 8710                let index = target_index.unwrap_or(0);
 8711                if let Some(workspace) = multi_workspace.workspaces().get(index).cloned() {
 8712                    multi_workspace.activate(workspace, window, cx);
 8713                }
 8714            })
 8715            .ok();
 8716    } else {
 8717        window_handle
 8718            .update(cx, |multi_workspace, window, cx| {
 8719                if let Some(workspace) = multi_workspace.workspaces().first().cloned() {
 8720                    multi_workspace.activate(workspace, window, cx);
 8721                }
 8722            })
 8723            .ok();
 8724    }
 8725
 8726    if state.sidebar_open {
 8727        window_handle
 8728            .update(cx, |multi_workspace, _, cx| {
 8729                multi_workspace.open_sidebar(cx);
 8730            })
 8731            .ok();
 8732    }
 8733
 8734    if let Some(sidebar_state) = &state.sidebar_state {
 8735        let sidebar_state = sidebar_state.clone();
 8736        window_handle
 8737            .update(cx, |multi_workspace, window, cx| {
 8738                if let Some(sidebar) = multi_workspace.sidebar() {
 8739                    sidebar.restore_serialized_state(&sidebar_state, window, cx);
 8740                }
 8741                multi_workspace.serialize(cx);
 8742            })
 8743            .ok();
 8744    }
 8745
 8746    window_handle
 8747        .update(cx, |_, window, _cx| {
 8748            window.activate_window();
 8749        })
 8750        .ok();
 8751
 8752    Ok(MultiWorkspaceRestoreResult {
 8753        window_handle,
 8754        errors,
 8755    })
 8756}
 8757
 8758actions!(
 8759    collab,
 8760    [
 8761        /// Opens the channel notes for the current call.
 8762        ///
 8763        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8764        /// channel in the collab panel.
 8765        ///
 8766        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8767        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8768        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8769        OpenChannelNotes,
 8770        /// Mutes your microphone.
 8771        Mute,
 8772        /// Deafens yourself (mute both microphone and speakers).
 8773        Deafen,
 8774        /// Leaves the current call.
 8775        LeaveCall,
 8776        /// Shares the current project with collaborators.
 8777        ShareProject,
 8778        /// Shares your screen with collaborators.
 8779        ScreenShare,
 8780        /// Copies the current room name and session id for debugging purposes.
 8781        CopyRoomId,
 8782    ]
 8783);
 8784
 8785/// Opens the channel notes for a specific channel by its ID.
 8786#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8787#[action(namespace = collab)]
 8788#[serde(deny_unknown_fields)]
 8789pub struct OpenChannelNotesById {
 8790    pub channel_id: u64,
 8791}
 8792
 8793actions!(
 8794    zed,
 8795    [
 8796        /// Opens the Zed log file.
 8797        OpenLog,
 8798        /// Reveals the Zed log file in the system file manager.
 8799        RevealLogInFileManager
 8800    ]
 8801);
 8802
 8803async fn join_channel_internal(
 8804    channel_id: ChannelId,
 8805    app_state: &Arc<AppState>,
 8806    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8807    requesting_workspace: Option<WeakEntity<Workspace>>,
 8808    active_call: &dyn AnyActiveCall,
 8809    cx: &mut AsyncApp,
 8810) -> Result<bool> {
 8811    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8812        if !active_call.is_in_room(cx) {
 8813            return (false, false);
 8814        }
 8815
 8816        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8817        let should_prompt = active_call.is_sharing_project(cx)
 8818            && active_call.has_remote_participants(cx)
 8819            && !already_in_channel;
 8820        (should_prompt, already_in_channel)
 8821    });
 8822
 8823    if already_in_channel {
 8824        let task = cx.update(|cx| {
 8825            if let Some((project, host)) = active_call.most_active_project(cx) {
 8826                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8827            } else {
 8828                None
 8829            }
 8830        });
 8831        if let Some(task) = task {
 8832            task.await?;
 8833        }
 8834        return anyhow::Ok(true);
 8835    }
 8836
 8837    if should_prompt {
 8838        if let Some(multi_workspace) = requesting_window {
 8839            let answer = multi_workspace
 8840                .update(cx, |_, window, cx| {
 8841                    window.prompt(
 8842                        PromptLevel::Warning,
 8843                        "Do you want to switch channels?",
 8844                        Some("Leaving this call will unshare your current project."),
 8845                        &["Yes, Join Channel", "Cancel"],
 8846                        cx,
 8847                    )
 8848                })?
 8849                .await;
 8850
 8851            if answer == Ok(1) {
 8852                return Ok(false);
 8853            }
 8854        } else {
 8855            return Ok(false);
 8856        }
 8857    }
 8858
 8859    let client = cx.update(|cx| active_call.client(cx));
 8860
 8861    let mut client_status = client.status();
 8862
 8863    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8864    'outer: loop {
 8865        let Some(status) = client_status.recv().await else {
 8866            anyhow::bail!("error connecting");
 8867        };
 8868
 8869        match status {
 8870            Status::Connecting
 8871            | Status::Authenticating
 8872            | Status::Authenticated
 8873            | Status::Reconnecting
 8874            | Status::Reauthenticating
 8875            | Status::Reauthenticated => continue,
 8876            Status::Connected { .. } => break 'outer,
 8877            Status::SignedOut | Status::AuthenticationError => {
 8878                return Err(ErrorCode::SignedOut.into());
 8879            }
 8880            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8881            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8882                return Err(ErrorCode::Disconnected.into());
 8883            }
 8884        }
 8885    }
 8886
 8887    let joined = cx
 8888        .update(|cx| active_call.join_channel(channel_id, cx))
 8889        .await?;
 8890
 8891    if !joined {
 8892        return anyhow::Ok(true);
 8893    }
 8894
 8895    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8896
 8897    let task = cx.update(|cx| {
 8898        if let Some((project, host)) = active_call.most_active_project(cx) {
 8899            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8900        }
 8901
 8902        // If you are the first to join a channel, see if you should share your project.
 8903        if !active_call.has_remote_participants(cx)
 8904            && !active_call.local_participant_is_guest(cx)
 8905            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8906        {
 8907            let project = workspace.update(cx, |workspace, cx| {
 8908                let project = workspace.project.read(cx);
 8909
 8910                if !active_call.share_on_join(cx) {
 8911                    return None;
 8912                }
 8913
 8914                if (project.is_local() || project.is_via_remote_server())
 8915                    && project.visible_worktrees(cx).any(|tree| {
 8916                        tree.read(cx)
 8917                            .root_entry()
 8918                            .is_some_and(|entry| entry.is_dir())
 8919                    })
 8920                {
 8921                    Some(workspace.project.clone())
 8922                } else {
 8923                    None
 8924                }
 8925            });
 8926            if let Some(project) = project {
 8927                let share_task = active_call.share_project(project, cx);
 8928                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8929                    share_task.await?;
 8930                    Ok(())
 8931                }));
 8932            }
 8933        }
 8934
 8935        None
 8936    });
 8937    if let Some(task) = task {
 8938        task.await?;
 8939        return anyhow::Ok(true);
 8940    }
 8941    anyhow::Ok(false)
 8942}
 8943
 8944pub fn join_channel(
 8945    channel_id: ChannelId,
 8946    app_state: Arc<AppState>,
 8947    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8948    requesting_workspace: Option<WeakEntity<Workspace>>,
 8949    cx: &mut App,
 8950) -> Task<Result<()>> {
 8951    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8952    cx.spawn(async move |cx| {
 8953        let result = join_channel_internal(
 8954            channel_id,
 8955            &app_state,
 8956            requesting_window,
 8957            requesting_workspace,
 8958            &*active_call.0,
 8959            cx,
 8960        )
 8961        .await;
 8962
 8963        // join channel succeeded, and opened a window
 8964        if matches!(result, Ok(true)) {
 8965            return anyhow::Ok(());
 8966        }
 8967
 8968        // find an existing workspace to focus and show call controls
 8969        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8970        if active_window.is_none() {
 8971            // no open workspaces, make one to show the error in (blergh)
 8972            let OpenResult {
 8973                window: window_handle,
 8974                ..
 8975            } = cx
 8976                .update(|cx| {
 8977                    Workspace::new_local(
 8978                        vec![],
 8979                        app_state.clone(),
 8980                        requesting_window,
 8981                        None,
 8982                        None,
 8983                        OpenMode::Activate,
 8984                        cx,
 8985                    )
 8986                })
 8987                .await?;
 8988
 8989            window_handle
 8990                .update(cx, |_, window, _cx| {
 8991                    window.activate_window();
 8992                })
 8993                .ok();
 8994
 8995            if result.is_ok() {
 8996                cx.update(|cx| {
 8997                    cx.dispatch_action(&OpenChannelNotes);
 8998                });
 8999            }
 9000
 9001            active_window = Some(window_handle);
 9002        }
 9003
 9004        if let Err(err) = result {
 9005            log::error!("failed to join channel: {}", err);
 9006            if let Some(active_window) = active_window {
 9007                active_window
 9008                    .update(cx, |_, window, cx| {
 9009                        let detail: SharedString = match err.error_code() {
 9010                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 9011                            ErrorCode::UpgradeRequired => concat!(
 9012                                "Your are running an unsupported version of Zed. ",
 9013                                "Please update to continue."
 9014                            )
 9015                            .into(),
 9016                            ErrorCode::NoSuchChannel => concat!(
 9017                                "No matching channel was found. ",
 9018                                "Please check the link and try again."
 9019                            )
 9020                            .into(),
 9021                            ErrorCode::Forbidden => concat!(
 9022                                "This channel is private, and you do not have access. ",
 9023                                "Please ask someone to add you and try again."
 9024                            )
 9025                            .into(),
 9026                            ErrorCode::Disconnected => {
 9027                                "Please check your internet connection and try again.".into()
 9028                            }
 9029                            _ => format!("{}\n\nPlease try again.", err).into(),
 9030                        };
 9031                        window.prompt(
 9032                            PromptLevel::Critical,
 9033                            "Failed to join channel",
 9034                            Some(&detail),
 9035                            &["Ok"],
 9036                            cx,
 9037                        )
 9038                    })?
 9039                    .await
 9040                    .ok();
 9041            }
 9042        }
 9043
 9044        // return ok, we showed the error to the user.
 9045        anyhow::Ok(())
 9046    })
 9047}
 9048
 9049pub async fn get_any_active_multi_workspace(
 9050    app_state: Arc<AppState>,
 9051    mut cx: AsyncApp,
 9052) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 9053    // find an existing workspace to focus and show call controls
 9054    let active_window = activate_any_workspace_window(&mut cx);
 9055    if active_window.is_none() {
 9056        cx.update(|cx| {
 9057            Workspace::new_local(
 9058                vec![],
 9059                app_state.clone(),
 9060                None,
 9061                None,
 9062                None,
 9063                OpenMode::Activate,
 9064                cx,
 9065            )
 9066        })
 9067        .await?;
 9068    }
 9069    activate_any_workspace_window(&mut cx).context("could not open zed")
 9070}
 9071
 9072fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 9073    cx.update(|cx| {
 9074        if let Some(workspace_window) = cx
 9075            .active_window()
 9076            .and_then(|window| window.downcast::<MultiWorkspace>())
 9077        {
 9078            return Some(workspace_window);
 9079        }
 9080
 9081        for window in cx.windows() {
 9082            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 9083                workspace_window
 9084                    .update(cx, |_, window, _| window.activate_window())
 9085                    .ok();
 9086                return Some(workspace_window);
 9087            }
 9088        }
 9089        None
 9090    })
 9091}
 9092
 9093pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 9094    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 9095}
 9096
 9097pub fn workspace_windows_for_location(
 9098    serialized_location: &SerializedWorkspaceLocation,
 9099    cx: &App,
 9100) -> Vec<WindowHandle<MultiWorkspace>> {
 9101    cx.windows()
 9102        .into_iter()
 9103        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9104        .filter(|multi_workspace| {
 9105            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 9106                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 9107                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 9108                }
 9109                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 9110                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 9111                    a.distro_name == b.distro_name
 9112                }
 9113                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 9114                    a.container_id == b.container_id
 9115                }
 9116                #[cfg(any(test, feature = "test-support"))]
 9117                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 9118                    a.id == b.id
 9119                }
 9120                _ => false,
 9121            };
 9122
 9123            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 9124                multi_workspace.workspaces().iter().any(|workspace| {
 9125                    match workspace.read(cx).workspace_location(cx) {
 9126                        WorkspaceLocation::Location(location, _) => {
 9127                            match (&location, serialized_location) {
 9128                                (
 9129                                    SerializedWorkspaceLocation::Local,
 9130                                    SerializedWorkspaceLocation::Local,
 9131                                ) => true,
 9132                                (
 9133                                    SerializedWorkspaceLocation::Remote(a),
 9134                                    SerializedWorkspaceLocation::Remote(b),
 9135                                ) => same_host(a, b),
 9136                                _ => false,
 9137                            }
 9138                        }
 9139                        _ => false,
 9140                    }
 9141                })
 9142            })
 9143        })
 9144        .collect()
 9145}
 9146
 9147pub async fn find_existing_workspace(
 9148    abs_paths: &[PathBuf],
 9149    open_options: &OpenOptions,
 9150    location: &SerializedWorkspaceLocation,
 9151    cx: &mut AsyncApp,
 9152) -> (
 9153    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 9154    OpenVisible,
 9155) {
 9156    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 9157    let mut open_visible = OpenVisible::All;
 9158    let mut best_match = None;
 9159
 9160    if open_options.open_new_workspace != Some(true) {
 9161        cx.update(|cx| {
 9162            for window in workspace_windows_for_location(location, cx) {
 9163                if let Ok(multi_workspace) = window.read(cx) {
 9164                    for workspace in multi_workspace.workspaces() {
 9165                        let project = workspace.read(cx).project.read(cx);
 9166                        let m = project.visibility_for_paths(
 9167                            abs_paths,
 9168                            open_options.open_new_workspace == None,
 9169                            cx,
 9170                        );
 9171                        if m > best_match {
 9172                            existing = Some((window, workspace.clone()));
 9173                            best_match = m;
 9174                        } else if best_match.is_none()
 9175                            && open_options.open_new_workspace == Some(false)
 9176                        {
 9177                            existing = Some((window, workspace.clone()))
 9178                        }
 9179                    }
 9180                }
 9181            }
 9182        });
 9183
 9184        let all_paths_are_files = existing
 9185            .as_ref()
 9186            .and_then(|(_, target_workspace)| {
 9187                cx.update(|cx| {
 9188                    let workspace = target_workspace.read(cx);
 9189                    let project = workspace.project.read(cx);
 9190                    let path_style = workspace.path_style(cx);
 9191                    Some(!abs_paths.iter().any(|path| {
 9192                        let path = util::paths::SanitizedPath::new(path);
 9193                        project.worktrees(cx).any(|worktree| {
 9194                            let worktree = worktree.read(cx);
 9195                            let abs_path = worktree.abs_path();
 9196                            path_style
 9197                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 9198                                .and_then(|rel| worktree.entry_for_path(&rel))
 9199                                .is_some_and(|e| e.is_dir())
 9200                        })
 9201                    }))
 9202                })
 9203            })
 9204            .unwrap_or(false);
 9205
 9206        if open_options.open_new_workspace.is_none()
 9207            && existing.is_some()
 9208            && open_options.wait
 9209            && all_paths_are_files
 9210        {
 9211            cx.update(|cx| {
 9212                let windows = workspace_windows_for_location(location, cx);
 9213                let window = cx
 9214                    .active_window()
 9215                    .and_then(|window| window.downcast::<MultiWorkspace>())
 9216                    .filter(|window| windows.contains(window))
 9217                    .or_else(|| windows.into_iter().next());
 9218                if let Some(window) = window {
 9219                    if let Ok(multi_workspace) = window.read(cx) {
 9220                        let active_workspace = multi_workspace.workspace().clone();
 9221                        existing = Some((window, active_workspace));
 9222                        open_visible = OpenVisible::None;
 9223                    }
 9224                }
 9225            });
 9226        }
 9227    }
 9228    (existing, open_visible)
 9229}
 9230
 9231#[derive(Default, Clone)]
 9232pub struct OpenOptions {
 9233    pub visible: Option<OpenVisible>,
 9234    pub focus: Option<bool>,
 9235    pub open_new_workspace: Option<bool>,
 9236    pub wait: bool,
 9237    pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9238    pub open_mode: OpenMode,
 9239    pub env: Option<HashMap<String, String>>,
 9240    pub open_in_dev_container: bool,
 9241}
 9242
 9243/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 9244/// or [`Workspace::open_workspace_for_paths`].
 9245pub struct OpenResult {
 9246    pub window: WindowHandle<MultiWorkspace>,
 9247    pub workspace: Entity<Workspace>,
 9248    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 9249}
 9250
 9251/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 9252pub fn open_workspace_by_id(
 9253    workspace_id: WorkspaceId,
 9254    app_state: Arc<AppState>,
 9255    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9256    cx: &mut App,
 9257) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 9258    let project_handle = Project::local(
 9259        app_state.client.clone(),
 9260        app_state.node_runtime.clone(),
 9261        app_state.user_store.clone(),
 9262        app_state.languages.clone(),
 9263        app_state.fs.clone(),
 9264        None,
 9265        project::LocalProjectFlags {
 9266            init_worktree_trust: true,
 9267            ..project::LocalProjectFlags::default()
 9268        },
 9269        cx,
 9270    );
 9271
 9272    let db = WorkspaceDb::global(cx);
 9273    let kvp = db::kvp::KeyValueStore::global(cx);
 9274    cx.spawn(async move |cx| {
 9275        let serialized_workspace = db
 9276            .workspace_for_id(workspace_id)
 9277            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 9278
 9279        let centered_layout = serialized_workspace.centered_layout;
 9280
 9281        let (window, workspace) = if let Some(window) = requesting_window {
 9282            let workspace = window.update(cx, |multi_workspace, window, cx| {
 9283                let workspace = cx.new(|cx| {
 9284                    let mut workspace = Workspace::new(
 9285                        Some(workspace_id),
 9286                        project_handle.clone(),
 9287                        app_state.clone(),
 9288                        window,
 9289                        cx,
 9290                    );
 9291                    workspace.centered_layout = centered_layout;
 9292                    workspace
 9293                });
 9294                multi_workspace.add(workspace.clone(), &*window, cx);
 9295                workspace
 9296            })?;
 9297            (window, workspace)
 9298        } else {
 9299            let window_bounds_override = window_bounds_env_override();
 9300
 9301            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 9302                (Some(WindowBounds::Windowed(bounds)), None)
 9303            } else if let Some(display) = serialized_workspace.display
 9304                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 9305            {
 9306                (Some(bounds.0), Some(display))
 9307            } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
 9308                (Some(bounds), Some(display))
 9309            } else {
 9310                (None, None)
 9311            };
 9312
 9313            let options = cx.update(|cx| {
 9314                let mut options = (app_state.build_window_options)(display, cx);
 9315                options.window_bounds = window_bounds;
 9316                options
 9317            });
 9318
 9319            let window = cx.open_window(options, {
 9320                let app_state = app_state.clone();
 9321                let project_handle = project_handle.clone();
 9322                move |window, cx| {
 9323                    let workspace = cx.new(|cx| {
 9324                        let mut workspace = Workspace::new(
 9325                            Some(workspace_id),
 9326                            project_handle,
 9327                            app_state,
 9328                            window,
 9329                            cx,
 9330                        );
 9331                        workspace.centered_layout = centered_layout;
 9332                        workspace
 9333                    });
 9334                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9335                }
 9336            })?;
 9337
 9338            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 9339                multi_workspace.workspace().clone()
 9340            })?;
 9341
 9342            (window, workspace)
 9343        };
 9344
 9345        notify_if_database_failed(window, cx);
 9346
 9347        // Restore items from the serialized workspace
 9348        window
 9349            .update(cx, |_, window, cx| {
 9350                workspace.update(cx, |_workspace, cx| {
 9351                    open_items(Some(serialized_workspace), vec![], window, cx)
 9352                })
 9353            })?
 9354            .await?;
 9355
 9356        window.update(cx, |_, window, cx| {
 9357            workspace.update(cx, |workspace, cx| {
 9358                workspace.serialize_workspace(window, cx);
 9359            });
 9360        })?;
 9361
 9362        Ok(window)
 9363    })
 9364}
 9365
 9366#[allow(clippy::type_complexity)]
 9367pub fn open_paths(
 9368    abs_paths: &[PathBuf],
 9369    app_state: Arc<AppState>,
 9370    open_options: OpenOptions,
 9371    cx: &mut App,
 9372) -> Task<anyhow::Result<OpenResult>> {
 9373    let abs_paths = abs_paths.to_vec();
 9374    #[cfg(target_os = "windows")]
 9375    let wsl_path = abs_paths
 9376        .iter()
 9377        .find_map(|p| util::paths::WslPath::from_path(p));
 9378
 9379    cx.spawn(async move |cx| {
 9380        let (mut existing, mut open_visible) = find_existing_workspace(
 9381            &abs_paths,
 9382            &open_options,
 9383            &SerializedWorkspaceLocation::Local,
 9384            cx,
 9385        )
 9386        .await;
 9387
 9388        // Fallback: if no workspace contains the paths and all paths are files,
 9389        // prefer an existing local workspace window (active window first).
 9390        if open_options.open_new_workspace.is_none() && existing.is_none() {
 9391            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 9392            let all_metadatas = futures::future::join_all(all_paths)
 9393                .await
 9394                .into_iter()
 9395                .filter_map(|result| result.ok().flatten())
 9396                .collect::<Vec<_>>();
 9397
 9398            if all_metadatas.iter().all(|file| !file.is_dir) {
 9399                cx.update(|cx| {
 9400                    let windows = workspace_windows_for_location(
 9401                        &SerializedWorkspaceLocation::Local,
 9402                        cx,
 9403                    );
 9404                    let window = cx
 9405                        .active_window()
 9406                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9407                        .filter(|window| windows.contains(window))
 9408                        .or_else(|| windows.into_iter().next());
 9409                    if let Some(window) = window {
 9410                        if let Ok(multi_workspace) = window.read(cx) {
 9411                            let active_workspace = multi_workspace.workspace().clone();
 9412                            existing = Some((window, active_workspace));
 9413                            open_visible = OpenVisible::None;
 9414                        }
 9415                    }
 9416                });
 9417            }
 9418        }
 9419
 9420        let open_in_dev_container = open_options.open_in_dev_container;
 9421
 9422        let result = if let Some((existing, target_workspace)) = existing {
 9423            let open_task = existing
 9424                .update(cx, |multi_workspace, window, cx| {
 9425                    window.activate_window();
 9426                    multi_workspace.activate(target_workspace.clone(), window, cx);
 9427                    target_workspace.update(cx, |workspace, cx| {
 9428                        if open_in_dev_container {
 9429                            workspace.set_open_in_dev_container(true);
 9430                        }
 9431                        workspace.open_paths(
 9432                            abs_paths,
 9433                            OpenOptions {
 9434                                visible: Some(open_visible),
 9435                                ..Default::default()
 9436                            },
 9437                            None,
 9438                            window,
 9439                            cx,
 9440                        )
 9441                    })
 9442                })?
 9443                .await;
 9444
 9445            _ = existing.update(cx, |multi_workspace, _, cx| {
 9446                let workspace = multi_workspace.workspace().clone();
 9447                workspace.update(cx, |workspace, cx| {
 9448                    for item in open_task.iter().flatten() {
 9449                        if let Err(e) = item {
 9450                            workspace.show_error(&e, cx);
 9451                        }
 9452                    }
 9453                });
 9454            });
 9455
 9456            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9457        } else {
 9458            let init = if open_in_dev_container {
 9459                Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>| {
 9460                    workspace.set_open_in_dev_container(true);
 9461                }) as Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>)
 9462            } else {
 9463                None
 9464            };
 9465            let result = cx
 9466                .update(move |cx| {
 9467                    Workspace::new_local(
 9468                        abs_paths,
 9469                        app_state.clone(),
 9470                        open_options.requesting_window,
 9471                        open_options.env,
 9472                        init,
 9473                        open_options.open_mode,
 9474                        cx,
 9475                    )
 9476                })
 9477                .await;
 9478
 9479            if let Ok(ref result) = result {
 9480                result.window
 9481                    .update(cx, |_, window, _cx| {
 9482                        window.activate_window();
 9483                    })
 9484                    .log_err();
 9485            }
 9486
 9487            result
 9488        };
 9489
 9490        #[cfg(target_os = "windows")]
 9491        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9492            && let Ok(ref result) = result
 9493        {
 9494            result.window
 9495                .update(cx, move |multi_workspace, _window, cx| {
 9496                    struct OpenInWsl;
 9497                    let workspace = multi_workspace.workspace().clone();
 9498                    workspace.update(cx, |workspace, cx| {
 9499                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9500                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9501                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9502                            cx.new(move |cx| {
 9503                                MessageNotification::new(msg, cx)
 9504                                    .primary_message("Open in WSL")
 9505                                    .primary_icon(IconName::FolderOpen)
 9506                                    .primary_on_click(move |window, cx| {
 9507                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9508                                                distro: remote::WslConnectionOptions {
 9509                                                        distro_name: distro.clone(),
 9510                                                    user: None,
 9511                                                },
 9512                                                paths: vec![path.clone().into()],
 9513                                            }), cx)
 9514                                    })
 9515                            })
 9516                        });
 9517                    });
 9518                })
 9519                .unwrap();
 9520        };
 9521        result
 9522    })
 9523}
 9524
 9525pub fn open_new(
 9526    open_options: OpenOptions,
 9527    app_state: Arc<AppState>,
 9528    cx: &mut App,
 9529    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9530) -> Task<anyhow::Result<()>> {
 9531    let addition = open_options.open_mode;
 9532    let task = Workspace::new_local(
 9533        Vec::new(),
 9534        app_state,
 9535        open_options.requesting_window,
 9536        open_options.env,
 9537        Some(Box::new(init)),
 9538        addition,
 9539        cx,
 9540    );
 9541    cx.spawn(async move |cx| {
 9542        let OpenResult { window, .. } = task.await?;
 9543        window
 9544            .update(cx, |_, window, _cx| {
 9545                window.activate_window();
 9546            })
 9547            .ok();
 9548        Ok(())
 9549    })
 9550}
 9551
 9552pub fn create_and_open_local_file(
 9553    path: &'static Path,
 9554    window: &mut Window,
 9555    cx: &mut Context<Workspace>,
 9556    default_content: impl 'static + Send + FnOnce() -> Rope,
 9557) -> Task<Result<Box<dyn ItemHandle>>> {
 9558    cx.spawn_in(window, async move |workspace, cx| {
 9559        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9560        if !fs.is_file(path).await {
 9561            fs.create_file(path, Default::default()).await?;
 9562            fs.save(path, &default_content(), Default::default())
 9563                .await?;
 9564        }
 9565
 9566        workspace
 9567            .update_in(cx, |workspace, window, cx| {
 9568                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9569                    let path = workspace
 9570                        .project
 9571                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9572                    cx.spawn_in(window, async move |workspace, cx| {
 9573                        let path = path.await?;
 9574
 9575                        let path = fs.canonicalize(&path).await.unwrap_or(path);
 9576
 9577                        let mut items = workspace
 9578                            .update_in(cx, |workspace, window, cx| {
 9579                                workspace.open_paths(
 9580                                    vec![path.to_path_buf()],
 9581                                    OpenOptions {
 9582                                        visible: Some(OpenVisible::None),
 9583                                        ..Default::default()
 9584                                    },
 9585                                    None,
 9586                                    window,
 9587                                    cx,
 9588                                )
 9589                            })?
 9590                            .await;
 9591                        let item = items.pop().flatten();
 9592                        item.with_context(|| format!("path {path:?} is not a file"))?
 9593                    })
 9594                })
 9595            })?
 9596            .await?
 9597            .await
 9598    })
 9599}
 9600
 9601pub fn open_remote_project_with_new_connection(
 9602    window: WindowHandle<MultiWorkspace>,
 9603    remote_connection: Arc<dyn RemoteConnection>,
 9604    cancel_rx: oneshot::Receiver<()>,
 9605    delegate: Arc<dyn RemoteClientDelegate>,
 9606    app_state: Arc<AppState>,
 9607    paths: Vec<PathBuf>,
 9608    cx: &mut App,
 9609) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9610    cx.spawn(async move |cx| {
 9611        let (workspace_id, serialized_workspace) =
 9612            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9613                .await?;
 9614
 9615        let session = match cx
 9616            .update(|cx| {
 9617                remote::RemoteClient::new(
 9618                    ConnectionIdentifier::Workspace(workspace_id.0),
 9619                    remote_connection,
 9620                    cancel_rx,
 9621                    delegate,
 9622                    cx,
 9623                )
 9624            })
 9625            .await?
 9626        {
 9627            Some(result) => result,
 9628            None => return Ok(Vec::new()),
 9629        };
 9630
 9631        let project = cx.update(|cx| {
 9632            project::Project::remote(
 9633                session,
 9634                app_state.client.clone(),
 9635                app_state.node_runtime.clone(),
 9636                app_state.user_store.clone(),
 9637                app_state.languages.clone(),
 9638                app_state.fs.clone(),
 9639                true,
 9640                cx,
 9641            )
 9642        });
 9643
 9644        open_remote_project_inner(
 9645            project,
 9646            paths,
 9647            workspace_id,
 9648            serialized_workspace,
 9649            app_state,
 9650            window,
 9651            cx,
 9652        )
 9653        .await
 9654    })
 9655}
 9656
 9657pub fn open_remote_project_with_existing_connection(
 9658    connection_options: RemoteConnectionOptions,
 9659    project: Entity<Project>,
 9660    paths: Vec<PathBuf>,
 9661    app_state: Arc<AppState>,
 9662    window: WindowHandle<MultiWorkspace>,
 9663    cx: &mut AsyncApp,
 9664) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9665    cx.spawn(async move |cx| {
 9666        let (workspace_id, serialized_workspace) =
 9667            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9668
 9669        open_remote_project_inner(
 9670            project,
 9671            paths,
 9672            workspace_id,
 9673            serialized_workspace,
 9674            app_state,
 9675            window,
 9676            cx,
 9677        )
 9678        .await
 9679    })
 9680}
 9681
 9682async fn open_remote_project_inner(
 9683    project: Entity<Project>,
 9684    paths: Vec<PathBuf>,
 9685    workspace_id: WorkspaceId,
 9686    serialized_workspace: Option<SerializedWorkspace>,
 9687    app_state: Arc<AppState>,
 9688    window: WindowHandle<MultiWorkspace>,
 9689    cx: &mut AsyncApp,
 9690) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9691    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9692    let toolchains = db.toolchains(workspace_id).await?;
 9693    for (toolchain, worktree_path, path) in toolchains {
 9694        project
 9695            .update(cx, |this, cx| {
 9696                let Some(worktree_id) =
 9697                    this.find_worktree(&worktree_path, cx)
 9698                        .and_then(|(worktree, rel_path)| {
 9699                            if rel_path.is_empty() {
 9700                                Some(worktree.read(cx).id())
 9701                            } else {
 9702                                None
 9703                            }
 9704                        })
 9705                else {
 9706                    return Task::ready(None);
 9707                };
 9708
 9709                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9710            })
 9711            .await;
 9712    }
 9713    let mut project_paths_to_open = vec![];
 9714    let mut project_path_errors = vec![];
 9715
 9716    for path in paths {
 9717        let result = cx
 9718            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9719            .await;
 9720        match result {
 9721            Ok((_, project_path)) => {
 9722                project_paths_to_open.push((path.clone(), Some(project_path)));
 9723            }
 9724            Err(error) => {
 9725                project_path_errors.push(error);
 9726            }
 9727        };
 9728    }
 9729
 9730    if project_paths_to_open.is_empty() {
 9731        return Err(project_path_errors.pop().context("no paths given")?);
 9732    }
 9733
 9734    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9735        telemetry::event!("SSH Project Opened");
 9736
 9737        let new_workspace = cx.new(|cx| {
 9738            let mut workspace =
 9739                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9740            workspace.update_history(cx);
 9741
 9742            if let Some(ref serialized) = serialized_workspace {
 9743                workspace.centered_layout = serialized.centered_layout;
 9744            }
 9745
 9746            workspace
 9747        });
 9748
 9749        multi_workspace.activate(new_workspace.clone(), window, cx);
 9750        new_workspace
 9751    })?;
 9752
 9753    let items = window
 9754        .update(cx, |_, window, cx| {
 9755            window.activate_window();
 9756            workspace.update(cx, |_workspace, cx| {
 9757                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9758            })
 9759        })?
 9760        .await?;
 9761
 9762    workspace.update(cx, |workspace, cx| {
 9763        for error in project_path_errors {
 9764            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9765                if let Some(path) = error.error_tag("path") {
 9766                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9767                }
 9768            } else {
 9769                workspace.show_error(&error, cx)
 9770            }
 9771        }
 9772    });
 9773
 9774    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9775}
 9776
 9777fn deserialize_remote_project(
 9778    connection_options: RemoteConnectionOptions,
 9779    paths: Vec<PathBuf>,
 9780    cx: &AsyncApp,
 9781) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9782    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9783    cx.background_spawn(async move {
 9784        let remote_connection_id = db
 9785            .get_or_create_remote_connection(connection_options)
 9786            .await?;
 9787
 9788        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
 9789
 9790        let workspace_id = if let Some(workspace_id) =
 9791            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9792        {
 9793            workspace_id
 9794        } else {
 9795            db.next_id().await?
 9796        };
 9797
 9798        Ok((workspace_id, serialized_workspace))
 9799    })
 9800}
 9801
 9802pub fn join_in_room_project(
 9803    project_id: u64,
 9804    follow_user_id: u64,
 9805    app_state: Arc<AppState>,
 9806    cx: &mut App,
 9807) -> Task<Result<()>> {
 9808    let windows = cx.windows();
 9809    cx.spawn(async move |cx| {
 9810        let existing_window_and_workspace: Option<(
 9811            WindowHandle<MultiWorkspace>,
 9812            Entity<Workspace>,
 9813        )> = windows.into_iter().find_map(|window_handle| {
 9814            window_handle
 9815                .downcast::<MultiWorkspace>()
 9816                .and_then(|window_handle| {
 9817                    window_handle
 9818                        .update(cx, |multi_workspace, _window, cx| {
 9819                            for workspace in multi_workspace.workspaces() {
 9820                                if workspace.read(cx).project().read(cx).remote_id()
 9821                                    == Some(project_id)
 9822                                {
 9823                                    return Some((window_handle, workspace.clone()));
 9824                                }
 9825                            }
 9826                            None
 9827                        })
 9828                        .unwrap_or(None)
 9829                })
 9830        });
 9831
 9832        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9833            existing_window_and_workspace
 9834        {
 9835            existing_window
 9836                .update(cx, |multi_workspace, window, cx| {
 9837                    multi_workspace.activate(target_workspace, window, cx);
 9838                })
 9839                .ok();
 9840            existing_window
 9841        } else {
 9842            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9843            let project = cx
 9844                .update(|cx| {
 9845                    active_call.0.join_project(
 9846                        project_id,
 9847                        app_state.languages.clone(),
 9848                        app_state.fs.clone(),
 9849                        cx,
 9850                    )
 9851                })
 9852                .await?;
 9853
 9854            let window_bounds_override = window_bounds_env_override();
 9855            cx.update(|cx| {
 9856                let mut options = (app_state.build_window_options)(None, cx);
 9857                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9858                cx.open_window(options, |window, cx| {
 9859                    let workspace = cx.new(|cx| {
 9860                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9861                    });
 9862                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9863                })
 9864            })?
 9865        };
 9866
 9867        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9868            cx.activate(true);
 9869            window.activate_window();
 9870
 9871            // We set the active workspace above, so this is the correct workspace.
 9872            let workspace = multi_workspace.workspace().clone();
 9873            workspace.update(cx, |workspace, cx| {
 9874                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9875                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9876                    .or_else(|| {
 9877                        // If we couldn't follow the given user, follow the host instead.
 9878                        let collaborator = workspace
 9879                            .project()
 9880                            .read(cx)
 9881                            .collaborators()
 9882                            .values()
 9883                            .find(|collaborator| collaborator.is_host)?;
 9884                        Some(collaborator.peer_id)
 9885                    });
 9886
 9887                if let Some(follow_peer_id) = follow_peer_id {
 9888                    workspace.follow(follow_peer_id, window, cx);
 9889                }
 9890            });
 9891        })?;
 9892
 9893        anyhow::Ok(())
 9894    })
 9895}
 9896
 9897pub fn reload(cx: &mut App) {
 9898    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9899    let mut workspace_windows = cx
 9900        .windows()
 9901        .into_iter()
 9902        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9903        .collect::<Vec<_>>();
 9904
 9905    // If multiple windows have unsaved changes, and need a save prompt,
 9906    // prompt in the active window before switching to a different window.
 9907    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9908
 9909    let mut prompt = None;
 9910    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9911        prompt = window
 9912            .update(cx, |_, window, cx| {
 9913                window.prompt(
 9914                    PromptLevel::Info,
 9915                    "Are you sure you want to restart?",
 9916                    None,
 9917                    &["Restart", "Cancel"],
 9918                    cx,
 9919                )
 9920            })
 9921            .ok();
 9922    }
 9923
 9924    cx.spawn(async move |cx| {
 9925        if let Some(prompt) = prompt {
 9926            let answer = prompt.await?;
 9927            if answer != 0 {
 9928                return anyhow::Ok(());
 9929            }
 9930        }
 9931
 9932        // If the user cancels any save prompt, then keep the app open.
 9933        for window in workspace_windows {
 9934            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9935                let workspace = multi_workspace.workspace().clone();
 9936                workspace.update(cx, |workspace, cx| {
 9937                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9938                })
 9939            }) && !should_close.await?
 9940            {
 9941                return anyhow::Ok(());
 9942            }
 9943        }
 9944        cx.update(|cx| cx.restart());
 9945        anyhow::Ok(())
 9946    })
 9947    .detach_and_log_err(cx);
 9948}
 9949
 9950fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9951    let mut parts = value.split(',');
 9952    let x: usize = parts.next()?.parse().ok()?;
 9953    let y: usize = parts.next()?.parse().ok()?;
 9954    Some(point(px(x as f32), px(y as f32)))
 9955}
 9956
 9957fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9958    let mut parts = value.split(',');
 9959    let width: usize = parts.next()?.parse().ok()?;
 9960    let height: usize = parts.next()?.parse().ok()?;
 9961    Some(size(px(width as f32), px(height as f32)))
 9962}
 9963
 9964/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9965/// appropriate.
 9966///
 9967/// The `border_radius_tiling` parameter allows overriding which corners get
 9968/// rounded, independently of the actual window tiling state. This is used
 9969/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9970/// we want square corners on the left (so the sidebar appears flush with the
 9971/// window edge) but we still need the shadow padding for proper visual
 9972/// appearance. Unlike actual window tiling, this only affects border radius -
 9973/// not padding or shadows.
 9974pub fn client_side_decorations(
 9975    element: impl IntoElement,
 9976    window: &mut Window,
 9977    cx: &mut App,
 9978    border_radius_tiling: Tiling,
 9979) -> Stateful<Div> {
 9980    const BORDER_SIZE: Pixels = px(1.0);
 9981    let decorations = window.window_decorations();
 9982    let tiling = match decorations {
 9983        Decorations::Server => Tiling::default(),
 9984        Decorations::Client { tiling } => tiling,
 9985    };
 9986
 9987    match decorations {
 9988        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9989        Decorations::Server => window.set_client_inset(px(0.0)),
 9990    }
 9991
 9992    struct GlobalResizeEdge(ResizeEdge);
 9993    impl Global for GlobalResizeEdge {}
 9994
 9995    div()
 9996        .id("window-backdrop")
 9997        .bg(transparent_black())
 9998        .map(|div| match decorations {
 9999            Decorations::Server => div,
10000            Decorations::Client { .. } => div
10001                .when(
10002                    !(tiling.top
10003                        || tiling.right
10004                        || border_radius_tiling.top
10005                        || border_radius_tiling.right),
10006                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10007                )
10008                .when(
10009                    !(tiling.top
10010                        || tiling.left
10011                        || border_radius_tiling.top
10012                        || border_radius_tiling.left),
10013                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10014                )
10015                .when(
10016                    !(tiling.bottom
10017                        || tiling.right
10018                        || border_radius_tiling.bottom
10019                        || border_radius_tiling.right),
10020                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10021                )
10022                .when(
10023                    !(tiling.bottom
10024                        || tiling.left
10025                        || border_radius_tiling.bottom
10026                        || border_radius_tiling.left),
10027                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10028                )
10029                .when(!tiling.top, |div| {
10030                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
10031                })
10032                .when(!tiling.bottom, |div| {
10033                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
10034                })
10035                .when(!tiling.left, |div| {
10036                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10037                })
10038                .when(!tiling.right, |div| {
10039                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10040                })
10041                .on_mouse_move(move |e, window, cx| {
10042                    let size = window.window_bounds().get_bounds().size;
10043                    let pos = e.position;
10044
10045                    let new_edge =
10046                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10047
10048                    let edge = cx.try_global::<GlobalResizeEdge>();
10049                    if new_edge != edge.map(|edge| edge.0) {
10050                        window
10051                            .window_handle()
10052                            .update(cx, |workspace, _, cx| {
10053                                cx.notify(workspace.entity_id());
10054                            })
10055                            .ok();
10056                    }
10057                })
10058                .on_mouse_down(MouseButton::Left, move |e, window, _| {
10059                    let size = window.window_bounds().get_bounds().size;
10060                    let pos = e.position;
10061
10062                    let edge = match resize_edge(
10063                        pos,
10064                        theme::CLIENT_SIDE_DECORATION_SHADOW,
10065                        size,
10066                        tiling,
10067                    ) {
10068                        Some(value) => value,
10069                        None => return,
10070                    };
10071
10072                    window.start_window_resize(edge);
10073                }),
10074        })
10075        .size_full()
10076        .child(
10077            div()
10078                .cursor(CursorStyle::Arrow)
10079                .map(|div| match decorations {
10080                    Decorations::Server => div,
10081                    Decorations::Client { .. } => div
10082                        .border_color(cx.theme().colors().border)
10083                        .when(
10084                            !(tiling.top
10085                                || tiling.right
10086                                || border_radius_tiling.top
10087                                || border_radius_tiling.right),
10088                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10089                        )
10090                        .when(
10091                            !(tiling.top
10092                                || tiling.left
10093                                || border_radius_tiling.top
10094                                || border_radius_tiling.left),
10095                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10096                        )
10097                        .when(
10098                            !(tiling.bottom
10099                                || tiling.right
10100                                || border_radius_tiling.bottom
10101                                || border_radius_tiling.right),
10102                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10103                        )
10104                        .when(
10105                            !(tiling.bottom
10106                                || tiling.left
10107                                || border_radius_tiling.bottom
10108                                || border_radius_tiling.left),
10109                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10110                        )
10111                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10112                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10113                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10114                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10115                        .when(!tiling.is_tiled(), |div| {
10116                            div.shadow(vec![gpui::BoxShadow {
10117                                color: Hsla {
10118                                    h: 0.,
10119                                    s: 0.,
10120                                    l: 0.,
10121                                    a: 0.4,
10122                                },
10123                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10124                                spread_radius: px(0.),
10125                                offset: point(px(0.0), px(0.0)),
10126                            }])
10127                        }),
10128                })
10129                .on_mouse_move(|_e, _, cx| {
10130                    cx.stop_propagation();
10131                })
10132                .size_full()
10133                .child(element),
10134        )
10135        .map(|div| match decorations {
10136            Decorations::Server => div,
10137            Decorations::Client { tiling, .. } => div.child(
10138                canvas(
10139                    |_bounds, window, _| {
10140                        window.insert_hitbox(
10141                            Bounds::new(
10142                                point(px(0.0), px(0.0)),
10143                                window.window_bounds().get_bounds().size,
10144                            ),
10145                            HitboxBehavior::Normal,
10146                        )
10147                    },
10148                    move |_bounds, hitbox, window, cx| {
10149                        let mouse = window.mouse_position();
10150                        let size = window.window_bounds().get_bounds().size;
10151                        let Some(edge) =
10152                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10153                        else {
10154                            return;
10155                        };
10156                        cx.set_global(GlobalResizeEdge(edge));
10157                        window.set_cursor_style(
10158                            match edge {
10159                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10160                                ResizeEdge::Left | ResizeEdge::Right => {
10161                                    CursorStyle::ResizeLeftRight
10162                                }
10163                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10164                                    CursorStyle::ResizeUpLeftDownRight
10165                                }
10166                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10167                                    CursorStyle::ResizeUpRightDownLeft
10168                                }
10169                            },
10170                            &hitbox,
10171                        );
10172                    },
10173                )
10174                .size_full()
10175                .absolute(),
10176            ),
10177        })
10178}
10179
10180fn resize_edge(
10181    pos: Point<Pixels>,
10182    shadow_size: Pixels,
10183    window_size: Size<Pixels>,
10184    tiling: Tiling,
10185) -> Option<ResizeEdge> {
10186    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10187    if bounds.contains(&pos) {
10188        return None;
10189    }
10190
10191    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10192    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10193    if !tiling.top && top_left_bounds.contains(&pos) {
10194        return Some(ResizeEdge::TopLeft);
10195    }
10196
10197    let top_right_bounds = Bounds::new(
10198        Point::new(window_size.width - corner_size.width, px(0.)),
10199        corner_size,
10200    );
10201    if !tiling.top && top_right_bounds.contains(&pos) {
10202        return Some(ResizeEdge::TopRight);
10203    }
10204
10205    let bottom_left_bounds = Bounds::new(
10206        Point::new(px(0.), window_size.height - corner_size.height),
10207        corner_size,
10208    );
10209    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10210        return Some(ResizeEdge::BottomLeft);
10211    }
10212
10213    let bottom_right_bounds = Bounds::new(
10214        Point::new(
10215            window_size.width - corner_size.width,
10216            window_size.height - corner_size.height,
10217        ),
10218        corner_size,
10219    );
10220    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10221        return Some(ResizeEdge::BottomRight);
10222    }
10223
10224    if !tiling.top && pos.y < shadow_size {
10225        Some(ResizeEdge::Top)
10226    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10227        Some(ResizeEdge::Bottom)
10228    } else if !tiling.left && pos.x < shadow_size {
10229        Some(ResizeEdge::Left)
10230    } else if !tiling.right && pos.x > window_size.width - shadow_size {
10231        Some(ResizeEdge::Right)
10232    } else {
10233        None
10234    }
10235}
10236
10237fn join_pane_into_active(
10238    active_pane: &Entity<Pane>,
10239    pane: &Entity<Pane>,
10240    window: &mut Window,
10241    cx: &mut App,
10242) {
10243    if pane == active_pane {
10244    } else if pane.read(cx).items_len() == 0 {
10245        pane.update(cx, |_, cx| {
10246            cx.emit(pane::Event::Remove {
10247                focus_on_pane: None,
10248            });
10249        })
10250    } else {
10251        move_all_items(pane, active_pane, window, cx);
10252    }
10253}
10254
10255fn move_all_items(
10256    from_pane: &Entity<Pane>,
10257    to_pane: &Entity<Pane>,
10258    window: &mut Window,
10259    cx: &mut App,
10260) {
10261    let destination_is_different = from_pane != to_pane;
10262    let mut moved_items = 0;
10263    for (item_ix, item_handle) in from_pane
10264        .read(cx)
10265        .items()
10266        .enumerate()
10267        .map(|(ix, item)| (ix, item.clone()))
10268        .collect::<Vec<_>>()
10269    {
10270        let ix = item_ix - moved_items;
10271        if destination_is_different {
10272            // Close item from previous pane
10273            from_pane.update(cx, |source, cx| {
10274                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10275            });
10276            moved_items += 1;
10277        }
10278
10279        // This automatically removes duplicate items in the pane
10280        to_pane.update(cx, |destination, cx| {
10281            destination.add_item(item_handle, true, true, None, window, cx);
10282            window.focus(&destination.focus_handle(cx), cx)
10283        });
10284    }
10285}
10286
10287pub fn move_item(
10288    source: &Entity<Pane>,
10289    destination: &Entity<Pane>,
10290    item_id_to_move: EntityId,
10291    destination_index: usize,
10292    activate: bool,
10293    window: &mut Window,
10294    cx: &mut App,
10295) {
10296    let Some((item_ix, item_handle)) = source
10297        .read(cx)
10298        .items()
10299        .enumerate()
10300        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10301        .map(|(ix, item)| (ix, item.clone()))
10302    else {
10303        // Tab was closed during drag
10304        return;
10305    };
10306
10307    if source != destination {
10308        // Close item from previous pane
10309        source.update(cx, |source, cx| {
10310            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10311        });
10312    }
10313
10314    // This automatically removes duplicate items in the pane
10315    destination.update(cx, |destination, cx| {
10316        destination.add_item_inner(
10317            item_handle,
10318            activate,
10319            activate,
10320            activate,
10321            Some(destination_index),
10322            window,
10323            cx,
10324        );
10325        if activate {
10326            window.focus(&destination.focus_handle(cx), cx)
10327        }
10328    });
10329}
10330
10331pub fn move_active_item(
10332    source: &Entity<Pane>,
10333    destination: &Entity<Pane>,
10334    focus_destination: bool,
10335    close_if_empty: bool,
10336    window: &mut Window,
10337    cx: &mut App,
10338) {
10339    if source == destination {
10340        return;
10341    }
10342    let Some(active_item) = source.read(cx).active_item() else {
10343        return;
10344    };
10345    source.update(cx, |source_pane, cx| {
10346        let item_id = active_item.item_id();
10347        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10348        destination.update(cx, |target_pane, cx| {
10349            target_pane.add_item(
10350                active_item,
10351                focus_destination,
10352                focus_destination,
10353                Some(target_pane.items_len()),
10354                window,
10355                cx,
10356            );
10357        });
10358    });
10359}
10360
10361pub fn clone_active_item(
10362    workspace_id: Option<WorkspaceId>,
10363    source: &Entity<Pane>,
10364    destination: &Entity<Pane>,
10365    focus_destination: bool,
10366    window: &mut Window,
10367    cx: &mut App,
10368) {
10369    if source == destination {
10370        return;
10371    }
10372    let Some(active_item) = source.read(cx).active_item() else {
10373        return;
10374    };
10375    if !active_item.can_split(cx) {
10376        return;
10377    }
10378    let destination = destination.downgrade();
10379    let task = active_item.clone_on_split(workspace_id, window, cx);
10380    window
10381        .spawn(cx, async move |cx| {
10382            let Some(clone) = task.await else {
10383                return;
10384            };
10385            destination
10386                .update_in(cx, |target_pane, window, cx| {
10387                    target_pane.add_item(
10388                        clone,
10389                        focus_destination,
10390                        focus_destination,
10391                        Some(target_pane.items_len()),
10392                        window,
10393                        cx,
10394                    );
10395                })
10396                .log_err();
10397        })
10398        .detach();
10399}
10400
10401#[derive(Debug)]
10402pub struct WorkspacePosition {
10403    pub window_bounds: Option<WindowBounds>,
10404    pub display: Option<Uuid>,
10405    pub centered_layout: bool,
10406}
10407
10408pub fn remote_workspace_position_from_db(
10409    connection_options: RemoteConnectionOptions,
10410    paths_to_open: &[PathBuf],
10411    cx: &App,
10412) -> Task<Result<WorkspacePosition>> {
10413    let paths = paths_to_open.to_vec();
10414    let db = WorkspaceDb::global(cx);
10415    let kvp = db::kvp::KeyValueStore::global(cx);
10416
10417    cx.background_spawn(async move {
10418        let remote_connection_id = db
10419            .get_or_create_remote_connection(connection_options)
10420            .await
10421            .context("fetching serialized ssh project")?;
10422        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10423
10424        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10425            (Some(WindowBounds::Windowed(bounds)), None)
10426        } else {
10427            let restorable_bounds = serialized_workspace
10428                .as_ref()
10429                .and_then(|workspace| {
10430                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10431                })
10432                .or_else(|| persistence::read_default_window_bounds(&kvp));
10433
10434            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10435                (Some(serialized_bounds), Some(serialized_display))
10436            } else {
10437                (None, None)
10438            }
10439        };
10440
10441        let centered_layout = serialized_workspace
10442            .as_ref()
10443            .map(|w| w.centered_layout)
10444            .unwrap_or(false);
10445
10446        Ok(WorkspacePosition {
10447            window_bounds,
10448            display,
10449            centered_layout,
10450        })
10451    })
10452}
10453
10454pub fn with_active_or_new_workspace(
10455    cx: &mut App,
10456    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10457) {
10458    match cx
10459        .active_window()
10460        .and_then(|w| w.downcast::<MultiWorkspace>())
10461    {
10462        Some(multi_workspace) => {
10463            cx.defer(move |cx| {
10464                multi_workspace
10465                    .update(cx, |multi_workspace, window, cx| {
10466                        let workspace = multi_workspace.workspace().clone();
10467                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10468                    })
10469                    .log_err();
10470            });
10471        }
10472        None => {
10473            let app_state = AppState::global(cx);
10474            open_new(
10475                OpenOptions::default(),
10476                app_state,
10477                cx,
10478                move |workspace, window, cx| f(workspace, window, cx),
10479            )
10480            .detach_and_log_err(cx);
10481        }
10482    }
10483}
10484
10485/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10486/// key. This migration path only runs once per panel per workspace.
10487fn load_legacy_panel_size(
10488    panel_key: &str,
10489    dock_position: DockPosition,
10490    workspace: &Workspace,
10491    cx: &mut App,
10492) -> Option<Pixels> {
10493    #[derive(Deserialize)]
10494    struct LegacyPanelState {
10495        #[serde(default)]
10496        width: Option<Pixels>,
10497        #[serde(default)]
10498        height: Option<Pixels>,
10499    }
10500
10501    let workspace_id = workspace
10502        .database_id()
10503        .map(|id| i64::from(id).to_string())
10504        .or_else(|| workspace.session_id())?;
10505
10506    let legacy_key = match panel_key {
10507        "ProjectPanel" => {
10508            format!("{}-{:?}", "ProjectPanel", workspace_id)
10509        }
10510        "OutlinePanel" => {
10511            format!("{}-{:?}", "OutlinePanel", workspace_id)
10512        }
10513        "GitPanel" => {
10514            format!("{}-{:?}", "GitPanel", workspace_id)
10515        }
10516        "TerminalPanel" => {
10517            format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10518        }
10519        _ => return None,
10520    };
10521
10522    let kvp = db::kvp::KeyValueStore::global(cx);
10523    let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10524    let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10525    let size = match dock_position {
10526        DockPosition::Bottom => state.height,
10527        DockPosition::Left | DockPosition::Right => state.width,
10528    }?;
10529
10530    cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10531        .detach_and_log_err(cx);
10532
10533    Some(size)
10534}
10535
10536#[cfg(test)]
10537mod tests {
10538    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10539
10540    use super::*;
10541    use crate::{
10542        dock::{PanelEvent, test::TestPanel},
10543        item::{
10544            ItemBufferKind, ItemEvent,
10545            test::{TestItem, TestProjectItem},
10546        },
10547    };
10548    use fs::FakeFs;
10549    use gpui::{
10550        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10551        UpdateGlobal, VisualTestContext, px,
10552    };
10553    use project::{Project, ProjectEntryId};
10554    use serde_json::json;
10555    use settings::SettingsStore;
10556    use util::path;
10557    use util::rel_path::rel_path;
10558
10559    #[gpui::test]
10560    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10561        init_test(cx);
10562
10563        let fs = FakeFs::new(cx.executor());
10564        let project = Project::test(fs, [], cx).await;
10565        let (workspace, cx) =
10566            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10567
10568        // Adding an item with no ambiguity renders the tab without detail.
10569        let item1 = cx.new(|cx| {
10570            let mut item = TestItem::new(cx);
10571            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10572            item
10573        });
10574        workspace.update_in(cx, |workspace, window, cx| {
10575            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10576        });
10577        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10578
10579        // Adding an item that creates ambiguity increases the level of detail on
10580        // both tabs.
10581        let item2 = cx.new_window_entity(|_window, cx| {
10582            let mut item = TestItem::new(cx);
10583            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10584            item
10585        });
10586        workspace.update_in(cx, |workspace, window, cx| {
10587            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10588        });
10589        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10590        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10591
10592        // Adding an item that creates ambiguity increases the level of detail only
10593        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10594        // we stop at the highest detail available.
10595        let item3 = cx.new(|cx| {
10596            let mut item = TestItem::new(cx);
10597            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10598            item
10599        });
10600        workspace.update_in(cx, |workspace, window, cx| {
10601            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10602        });
10603        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10604        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10605        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10606    }
10607
10608    #[gpui::test]
10609    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10610        init_test(cx);
10611
10612        let fs = FakeFs::new(cx.executor());
10613        fs.insert_tree(
10614            "/root1",
10615            json!({
10616                "one.txt": "",
10617                "two.txt": "",
10618            }),
10619        )
10620        .await;
10621        fs.insert_tree(
10622            "/root2",
10623            json!({
10624                "three.txt": "",
10625            }),
10626        )
10627        .await;
10628
10629        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10630        let (workspace, cx) =
10631            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10632        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10633        let worktree_id = project.update(cx, |project, cx| {
10634            project.worktrees(cx).next().unwrap().read(cx).id()
10635        });
10636
10637        let item1 = cx.new(|cx| {
10638            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10639        });
10640        let item2 = cx.new(|cx| {
10641            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10642        });
10643
10644        // Add an item to an empty pane
10645        workspace.update_in(cx, |workspace, window, cx| {
10646            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10647        });
10648        project.update(cx, |project, cx| {
10649            assert_eq!(
10650                project.active_entry(),
10651                project
10652                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10653                    .map(|e| e.id)
10654            );
10655        });
10656        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10657
10658        // Add a second item to a non-empty pane
10659        workspace.update_in(cx, |workspace, window, cx| {
10660            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10661        });
10662        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10663        project.update(cx, |project, cx| {
10664            assert_eq!(
10665                project.active_entry(),
10666                project
10667                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10668                    .map(|e| e.id)
10669            );
10670        });
10671
10672        // Close the active item
10673        pane.update_in(cx, |pane, window, cx| {
10674            pane.close_active_item(&Default::default(), window, cx)
10675        })
10676        .await
10677        .unwrap();
10678        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10679        project.update(cx, |project, cx| {
10680            assert_eq!(
10681                project.active_entry(),
10682                project
10683                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10684                    .map(|e| e.id)
10685            );
10686        });
10687
10688        // Add a project folder
10689        project
10690            .update(cx, |project, cx| {
10691                project.find_or_create_worktree("root2", true, cx)
10692            })
10693            .await
10694            .unwrap();
10695        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10696
10697        // Remove a project folder
10698        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10699        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10700    }
10701
10702    #[gpui::test]
10703    async fn test_close_window(cx: &mut TestAppContext) {
10704        init_test(cx);
10705
10706        let fs = FakeFs::new(cx.executor());
10707        fs.insert_tree("/root", json!({ "one": "" })).await;
10708
10709        let project = Project::test(fs, ["root".as_ref()], cx).await;
10710        let (workspace, cx) =
10711            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10712
10713        // When there are no dirty items, there's nothing to do.
10714        let item1 = cx.new(TestItem::new);
10715        workspace.update_in(cx, |w, window, cx| {
10716            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10717        });
10718        let task = workspace.update_in(cx, |w, window, cx| {
10719            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10720        });
10721        assert!(task.await.unwrap());
10722
10723        // When there are dirty untitled items, prompt to save each one. If the user
10724        // cancels any prompt, then abort.
10725        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10726        let item3 = cx.new(|cx| {
10727            TestItem::new(cx)
10728                .with_dirty(true)
10729                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10730        });
10731        workspace.update_in(cx, |w, window, cx| {
10732            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10733            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10734        });
10735        let task = workspace.update_in(cx, |w, window, cx| {
10736            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10737        });
10738        cx.executor().run_until_parked();
10739        cx.simulate_prompt_answer("Cancel"); // cancel save all
10740        cx.executor().run_until_parked();
10741        assert!(!cx.has_pending_prompt());
10742        assert!(!task.await.unwrap());
10743    }
10744
10745    #[gpui::test]
10746    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10747        init_test(cx);
10748
10749        let fs = FakeFs::new(cx.executor());
10750        fs.insert_tree("/root", json!({ "one": "" })).await;
10751
10752        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10753        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10754        let multi_workspace_handle =
10755            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10756        cx.run_until_parked();
10757
10758        let workspace_a = multi_workspace_handle
10759            .read_with(cx, |mw, _| mw.workspace().clone())
10760            .unwrap();
10761
10762        let workspace_b = multi_workspace_handle
10763            .update(cx, |mw, window, cx| {
10764                mw.test_add_workspace(project_b, window, cx)
10765            })
10766            .unwrap();
10767
10768        // Activate workspace A
10769        multi_workspace_handle
10770            .update(cx, |mw, window, cx| {
10771                let workspace = mw.workspaces()[0].clone();
10772                mw.activate(workspace, window, cx);
10773            })
10774            .unwrap();
10775
10776        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10777
10778        // Workspace A has a clean item
10779        let item_a = cx.new(TestItem::new);
10780        workspace_a.update_in(cx, |w, window, cx| {
10781            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10782        });
10783
10784        // Workspace B has a dirty item
10785        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10786        workspace_b.update_in(cx, |w, window, cx| {
10787            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10788        });
10789
10790        // Verify workspace A is active
10791        multi_workspace_handle
10792            .read_with(cx, |mw, _| {
10793                assert_eq!(mw.active_workspace_index(), 0);
10794            })
10795            .unwrap();
10796
10797        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10798        multi_workspace_handle
10799            .update(cx, |mw, window, cx| {
10800                mw.close_window(&CloseWindow, window, cx);
10801            })
10802            .unwrap();
10803        cx.run_until_parked();
10804
10805        // Workspace B should now be active since it has dirty items that need attention
10806        multi_workspace_handle
10807            .read_with(cx, |mw, _| {
10808                assert_eq!(
10809                    mw.active_workspace_index(),
10810                    1,
10811                    "workspace B should be activated when it prompts"
10812                );
10813            })
10814            .unwrap();
10815
10816        // User cancels the save prompt from workspace B
10817        cx.simulate_prompt_answer("Cancel");
10818        cx.run_until_parked();
10819
10820        // Window should still exist because workspace B's close was cancelled
10821        assert!(
10822            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10823            "window should still exist after cancelling one workspace's close"
10824        );
10825    }
10826
10827    #[gpui::test]
10828    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10829        init_test(cx);
10830
10831        // Register TestItem as a serializable item
10832        cx.update(|cx| {
10833            register_serializable_item::<TestItem>(cx);
10834        });
10835
10836        let fs = FakeFs::new(cx.executor());
10837        fs.insert_tree("/root", json!({ "one": "" })).await;
10838
10839        let project = Project::test(fs, ["root".as_ref()], cx).await;
10840        let (workspace, cx) =
10841            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10842
10843        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10844        let item1 = cx.new(|cx| {
10845            TestItem::new(cx)
10846                .with_dirty(true)
10847                .with_serialize(|| Some(Task::ready(Ok(()))))
10848        });
10849        let item2 = cx.new(|cx| {
10850            TestItem::new(cx)
10851                .with_dirty(true)
10852                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10853                .with_serialize(|| Some(Task::ready(Ok(()))))
10854        });
10855        workspace.update_in(cx, |w, window, cx| {
10856            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10857            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10858        });
10859        let task = workspace.update_in(cx, |w, window, cx| {
10860            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10861        });
10862        assert!(task.await.unwrap());
10863    }
10864
10865    #[gpui::test]
10866    async fn test_close_pane_items(cx: &mut TestAppContext) {
10867        init_test(cx);
10868
10869        let fs = FakeFs::new(cx.executor());
10870
10871        let project = Project::test(fs, None, cx).await;
10872        let (workspace, cx) =
10873            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10874
10875        let item1 = cx.new(|cx| {
10876            TestItem::new(cx)
10877                .with_dirty(true)
10878                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10879        });
10880        let item2 = cx.new(|cx| {
10881            TestItem::new(cx)
10882                .with_dirty(true)
10883                .with_conflict(true)
10884                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10885        });
10886        let item3 = cx.new(|cx| {
10887            TestItem::new(cx)
10888                .with_dirty(true)
10889                .with_conflict(true)
10890                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10891        });
10892        let item4 = cx.new(|cx| {
10893            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10894                let project_item = TestProjectItem::new_untitled(cx);
10895                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10896                project_item
10897            }])
10898        });
10899        let pane = workspace.update_in(cx, |workspace, window, cx| {
10900            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10901            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10902            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10903            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10904            workspace.active_pane().clone()
10905        });
10906
10907        let close_items = pane.update_in(cx, |pane, window, cx| {
10908            pane.activate_item(1, true, true, window, cx);
10909            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10910            let item1_id = item1.item_id();
10911            let item3_id = item3.item_id();
10912            let item4_id = item4.item_id();
10913            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10914                [item1_id, item3_id, item4_id].contains(&id)
10915            })
10916        });
10917        cx.executor().run_until_parked();
10918
10919        assert!(cx.has_pending_prompt());
10920        cx.simulate_prompt_answer("Save all");
10921
10922        cx.executor().run_until_parked();
10923
10924        // Item 1 is saved. There's a prompt to save item 3.
10925        pane.update(cx, |pane, cx| {
10926            assert_eq!(item1.read(cx).save_count, 1);
10927            assert_eq!(item1.read(cx).save_as_count, 0);
10928            assert_eq!(item1.read(cx).reload_count, 0);
10929            assert_eq!(pane.items_len(), 3);
10930            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10931        });
10932        assert!(cx.has_pending_prompt());
10933
10934        // Cancel saving item 3.
10935        cx.simulate_prompt_answer("Discard");
10936        cx.executor().run_until_parked();
10937
10938        // Item 3 is reloaded. There's a prompt to save item 4.
10939        pane.update(cx, |pane, cx| {
10940            assert_eq!(item3.read(cx).save_count, 0);
10941            assert_eq!(item3.read(cx).save_as_count, 0);
10942            assert_eq!(item3.read(cx).reload_count, 1);
10943            assert_eq!(pane.items_len(), 2);
10944            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10945        });
10946
10947        // There's a prompt for a path for item 4.
10948        cx.simulate_new_path_selection(|_| Some(Default::default()));
10949        close_items.await.unwrap();
10950
10951        // The requested items are closed.
10952        pane.update(cx, |pane, cx| {
10953            assert_eq!(item4.read(cx).save_count, 0);
10954            assert_eq!(item4.read(cx).save_as_count, 1);
10955            assert_eq!(item4.read(cx).reload_count, 0);
10956            assert_eq!(pane.items_len(), 1);
10957            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10958        });
10959    }
10960
10961    #[gpui::test]
10962    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10963        init_test(cx);
10964
10965        let fs = FakeFs::new(cx.executor());
10966        let project = Project::test(fs, [], cx).await;
10967        let (workspace, cx) =
10968            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10969
10970        // Create several workspace items with single project entries, and two
10971        // workspace items with multiple project entries.
10972        let single_entry_items = (0..=4)
10973            .map(|project_entry_id| {
10974                cx.new(|cx| {
10975                    TestItem::new(cx)
10976                        .with_dirty(true)
10977                        .with_project_items(&[dirty_project_item(
10978                            project_entry_id,
10979                            &format!("{project_entry_id}.txt"),
10980                            cx,
10981                        )])
10982                })
10983            })
10984            .collect::<Vec<_>>();
10985        let item_2_3 = cx.new(|cx| {
10986            TestItem::new(cx)
10987                .with_dirty(true)
10988                .with_buffer_kind(ItemBufferKind::Multibuffer)
10989                .with_project_items(&[
10990                    single_entry_items[2].read(cx).project_items[0].clone(),
10991                    single_entry_items[3].read(cx).project_items[0].clone(),
10992                ])
10993        });
10994        let item_3_4 = cx.new(|cx| {
10995            TestItem::new(cx)
10996                .with_dirty(true)
10997                .with_buffer_kind(ItemBufferKind::Multibuffer)
10998                .with_project_items(&[
10999                    single_entry_items[3].read(cx).project_items[0].clone(),
11000                    single_entry_items[4].read(cx).project_items[0].clone(),
11001                ])
11002        });
11003
11004        // Create two panes that contain the following project entries:
11005        //   left pane:
11006        //     multi-entry items:   (2, 3)
11007        //     single-entry items:  0, 2, 3, 4
11008        //   right pane:
11009        //     single-entry items:  4, 1
11010        //     multi-entry items:   (3, 4)
11011        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
11012            let left_pane = workspace.active_pane().clone();
11013            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
11014            workspace.add_item_to_active_pane(
11015                single_entry_items[0].boxed_clone(),
11016                None,
11017                true,
11018                window,
11019                cx,
11020            );
11021            workspace.add_item_to_active_pane(
11022                single_entry_items[2].boxed_clone(),
11023                None,
11024                true,
11025                window,
11026                cx,
11027            );
11028            workspace.add_item_to_active_pane(
11029                single_entry_items[3].boxed_clone(),
11030                None,
11031                true,
11032                window,
11033                cx,
11034            );
11035            workspace.add_item_to_active_pane(
11036                single_entry_items[4].boxed_clone(),
11037                None,
11038                true,
11039                window,
11040                cx,
11041            );
11042
11043            let right_pane =
11044                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11045
11046            let boxed_clone = single_entry_items[1].boxed_clone();
11047            let right_pane = window.spawn(cx, async move |cx| {
11048                right_pane.await.inspect(|right_pane| {
11049                    right_pane
11050                        .update_in(cx, |pane, window, cx| {
11051                            pane.add_item(boxed_clone, true, true, None, window, cx);
11052                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11053                        })
11054                        .unwrap();
11055                })
11056            });
11057
11058            (left_pane, right_pane)
11059        });
11060        let right_pane = right_pane.await.unwrap();
11061        cx.focus(&right_pane);
11062
11063        let close = right_pane.update_in(cx, |pane, window, cx| {
11064            pane.close_all_items(&CloseAllItems::default(), window, cx)
11065                .unwrap()
11066        });
11067        cx.executor().run_until_parked();
11068
11069        let msg = cx.pending_prompt().unwrap().0;
11070        assert!(msg.contains("1.txt"));
11071        assert!(!msg.contains("2.txt"));
11072        assert!(!msg.contains("3.txt"));
11073        assert!(!msg.contains("4.txt"));
11074
11075        // With best-effort close, cancelling item 1 keeps it open but items 4
11076        // and (3,4) still close since their entries exist in left pane.
11077        cx.simulate_prompt_answer("Cancel");
11078        close.await;
11079
11080        right_pane.read_with(cx, |pane, _| {
11081            assert_eq!(pane.items_len(), 1);
11082        });
11083
11084        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11085        left_pane
11086            .update_in(cx, |left_pane, window, cx| {
11087                left_pane.close_item_by_id(
11088                    single_entry_items[3].entity_id(),
11089                    SaveIntent::Skip,
11090                    window,
11091                    cx,
11092                )
11093            })
11094            .await
11095            .unwrap();
11096
11097        let close = left_pane.update_in(cx, |pane, window, cx| {
11098            pane.close_all_items(&CloseAllItems::default(), window, cx)
11099                .unwrap()
11100        });
11101        cx.executor().run_until_parked();
11102
11103        let details = cx.pending_prompt().unwrap().1;
11104        assert!(details.contains("0.txt"));
11105        assert!(details.contains("3.txt"));
11106        assert!(details.contains("4.txt"));
11107        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11108        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11109        // assert!(!details.contains("2.txt"));
11110
11111        cx.simulate_prompt_answer("Save all");
11112        cx.executor().run_until_parked();
11113        close.await;
11114
11115        left_pane.read_with(cx, |pane, _| {
11116            assert_eq!(pane.items_len(), 0);
11117        });
11118    }
11119
11120    #[gpui::test]
11121    async fn test_autosave(cx: &mut gpui::TestAppContext) {
11122        init_test(cx);
11123
11124        let fs = FakeFs::new(cx.executor());
11125        let project = Project::test(fs, [], cx).await;
11126        let (workspace, cx) =
11127            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11128        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11129
11130        let item = cx.new(|cx| {
11131            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11132        });
11133        let item_id = item.entity_id();
11134        workspace.update_in(cx, |workspace, window, cx| {
11135            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11136        });
11137
11138        // Autosave on window change.
11139        item.update(cx, |item, cx| {
11140            SettingsStore::update_global(cx, |settings, cx| {
11141                settings.update_user_settings(cx, |settings| {
11142                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11143                })
11144            });
11145            item.is_dirty = true;
11146        });
11147
11148        // Deactivating the window saves the file.
11149        cx.deactivate_window();
11150        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11151
11152        // Re-activating the window doesn't save the file.
11153        cx.update(|window, _| window.activate_window());
11154        cx.executor().run_until_parked();
11155        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11156
11157        // Autosave on focus change.
11158        item.update_in(cx, |item, window, cx| {
11159            cx.focus_self(window);
11160            SettingsStore::update_global(cx, |settings, cx| {
11161                settings.update_user_settings(cx, |settings| {
11162                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11163                })
11164            });
11165            item.is_dirty = true;
11166        });
11167        // Blurring the item saves the file.
11168        item.update_in(cx, |_, window, _| window.blur());
11169        cx.executor().run_until_parked();
11170        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11171
11172        // Deactivating the window still saves the file.
11173        item.update_in(cx, |item, window, cx| {
11174            cx.focus_self(window);
11175            item.is_dirty = true;
11176        });
11177        cx.deactivate_window();
11178        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11179
11180        // Autosave after delay.
11181        item.update(cx, |item, cx| {
11182            SettingsStore::update_global(cx, |settings, cx| {
11183                settings.update_user_settings(cx, |settings| {
11184                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11185                        milliseconds: 500.into(),
11186                    });
11187                })
11188            });
11189            item.is_dirty = true;
11190            cx.emit(ItemEvent::Edit);
11191        });
11192
11193        // Delay hasn't fully expired, so the file is still dirty and unsaved.
11194        cx.executor().advance_clock(Duration::from_millis(250));
11195        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11196
11197        // After delay expires, the file is saved.
11198        cx.executor().advance_clock(Duration::from_millis(250));
11199        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11200
11201        // Autosave after delay, should save earlier than delay if tab is closed
11202        item.update(cx, |item, cx| {
11203            item.is_dirty = true;
11204            cx.emit(ItemEvent::Edit);
11205        });
11206        cx.executor().advance_clock(Duration::from_millis(250));
11207        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11208
11209        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11210        pane.update_in(cx, |pane, window, cx| {
11211            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11212        })
11213        .await
11214        .unwrap();
11215        assert!(!cx.has_pending_prompt());
11216        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11217
11218        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11219        workspace.update_in(cx, |workspace, window, cx| {
11220            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11221        });
11222        item.update_in(cx, |item, _window, cx| {
11223            item.is_dirty = true;
11224            for project_item in &mut item.project_items {
11225                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11226            }
11227        });
11228        cx.run_until_parked();
11229        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11230
11231        // Autosave on focus change, ensuring closing the tab counts as such.
11232        item.update(cx, |item, cx| {
11233            SettingsStore::update_global(cx, |settings, cx| {
11234                settings.update_user_settings(cx, |settings| {
11235                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11236                })
11237            });
11238            item.is_dirty = true;
11239            for project_item in &mut item.project_items {
11240                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11241            }
11242        });
11243
11244        pane.update_in(cx, |pane, window, cx| {
11245            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11246        })
11247        .await
11248        .unwrap();
11249        assert!(!cx.has_pending_prompt());
11250        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11251
11252        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11253        workspace.update_in(cx, |workspace, window, cx| {
11254            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11255        });
11256        item.update_in(cx, |item, window, cx| {
11257            item.project_items[0].update(cx, |item, _| {
11258                item.entry_id = None;
11259            });
11260            item.is_dirty = true;
11261            window.blur();
11262        });
11263        cx.run_until_parked();
11264        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11265
11266        // Ensure autosave is prevented for deleted files also when closing the buffer.
11267        let _close_items = pane.update_in(cx, |pane, window, cx| {
11268            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11269        });
11270        cx.run_until_parked();
11271        assert!(cx.has_pending_prompt());
11272        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11273    }
11274
11275    #[gpui::test]
11276    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11277        init_test(cx);
11278
11279        let fs = FakeFs::new(cx.executor());
11280        let project = Project::test(fs, [], cx).await;
11281        let (workspace, cx) =
11282            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11283
11284        // Create a multibuffer-like item with two child focus handles,
11285        // simulating individual buffer editors within a multibuffer.
11286        let item = cx.new(|cx| {
11287            TestItem::new(cx)
11288                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11289                .with_child_focus_handles(2, cx)
11290        });
11291        workspace.update_in(cx, |workspace, window, cx| {
11292            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11293        });
11294
11295        // Set autosave to OnFocusChange and focus the first child handle,
11296        // simulating the user's cursor being inside one of the multibuffer's excerpts.
11297        item.update_in(cx, |item, window, cx| {
11298            SettingsStore::update_global(cx, |settings, cx| {
11299                settings.update_user_settings(cx, |settings| {
11300                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11301                })
11302            });
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, 0));
11308
11309        // Moving focus from one child to another within the same item should
11310        // NOT trigger autosave — focus is still within the item's focus hierarchy.
11311        item.update_in(cx, |item, window, cx| {
11312            window.focus(&item.child_focus_handles[1], cx);
11313        });
11314        cx.executor().run_until_parked();
11315        item.read_with(cx, |item, _| {
11316            assert_eq!(
11317                item.save_count, 0,
11318                "Switching focus between children within the same item should not autosave"
11319            );
11320        });
11321
11322        // Blurring the item saves the file. This is the core regression scenario:
11323        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11324        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11325        // the leaf is always a child focus handle, so `on_blur` never detected
11326        // focus leaving the item.
11327        item.update_in(cx, |_, window, _| window.blur());
11328        cx.executor().run_until_parked();
11329        item.read_with(cx, |item, _| {
11330            assert_eq!(
11331                item.save_count, 1,
11332                "Blurring should trigger autosave when focus was on a child of the item"
11333            );
11334        });
11335
11336        // Deactivating the window should also trigger autosave when a child of
11337        // the multibuffer item currently owns focus.
11338        item.update_in(cx, |item, window, cx| {
11339            item.is_dirty = true;
11340            window.focus(&item.child_focus_handles[0], cx);
11341        });
11342        cx.executor().run_until_parked();
11343        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11344
11345        cx.deactivate_window();
11346        item.read_with(cx, |item, _| {
11347            assert_eq!(
11348                item.save_count, 2,
11349                "Deactivating window should trigger autosave when focus was on a child"
11350            );
11351        });
11352    }
11353
11354    #[gpui::test]
11355    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11356        init_test(cx);
11357
11358        let fs = FakeFs::new(cx.executor());
11359
11360        let project = Project::test(fs, [], cx).await;
11361        let (workspace, cx) =
11362            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11363
11364        let item = cx.new(|cx| {
11365            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11366        });
11367        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11368        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11369        let toolbar_notify_count = Rc::new(RefCell::new(0));
11370
11371        workspace.update_in(cx, |workspace, window, cx| {
11372            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11373            let toolbar_notification_count = toolbar_notify_count.clone();
11374            cx.observe_in(&toolbar, window, move |_, _, _, _| {
11375                *toolbar_notification_count.borrow_mut() += 1
11376            })
11377            .detach();
11378        });
11379
11380        pane.read_with(cx, |pane, _| {
11381            assert!(!pane.can_navigate_backward());
11382            assert!(!pane.can_navigate_forward());
11383        });
11384
11385        item.update_in(cx, |item, _, cx| {
11386            item.set_state("one".to_string(), cx);
11387        });
11388
11389        // Toolbar must be notified to re-render the navigation buttons
11390        assert_eq!(*toolbar_notify_count.borrow(), 1);
11391
11392        pane.read_with(cx, |pane, _| {
11393            assert!(pane.can_navigate_backward());
11394            assert!(!pane.can_navigate_forward());
11395        });
11396
11397        workspace
11398            .update_in(cx, |workspace, window, cx| {
11399                workspace.go_back(pane.downgrade(), window, cx)
11400            })
11401            .await
11402            .unwrap();
11403
11404        assert_eq!(*toolbar_notify_count.borrow(), 2);
11405        pane.read_with(cx, |pane, _| {
11406            assert!(!pane.can_navigate_backward());
11407            assert!(pane.can_navigate_forward());
11408        });
11409    }
11410
11411    /// Tests that the navigation history deduplicates entries for the same item.
11412    ///
11413    /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11414    /// the navigation history deduplicates by keeping only the most recent visit to each item,
11415    /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11416    /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11417    /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11418    ///
11419    /// This behavior prevents the navigation history from growing unnecessarily large and provides
11420    /// a better user experience by eliminating redundant navigation steps when jumping between files.
11421    #[gpui::test]
11422    async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11423        init_test(cx);
11424
11425        let fs = FakeFs::new(cx.executor());
11426        let project = Project::test(fs, [], cx).await;
11427        let (workspace, cx) =
11428            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11429
11430        let item_a = cx.new(|cx| {
11431            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11432        });
11433        let item_b = cx.new(|cx| {
11434            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11435        });
11436        let item_c = cx.new(|cx| {
11437            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11438        });
11439
11440        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11441
11442        workspace.update_in(cx, |workspace, window, cx| {
11443            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11444            workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11445            workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11446        });
11447
11448        workspace.update_in(cx, |workspace, window, cx| {
11449            workspace.activate_item(&item_a, false, false, window, cx);
11450        });
11451        cx.run_until_parked();
11452
11453        workspace.update_in(cx, |workspace, window, cx| {
11454            workspace.activate_item(&item_b, false, false, window, cx);
11455        });
11456        cx.run_until_parked();
11457
11458        workspace.update_in(cx, |workspace, window, cx| {
11459            workspace.activate_item(&item_a, false, false, window, cx);
11460        });
11461        cx.run_until_parked();
11462
11463        workspace.update_in(cx, |workspace, window, cx| {
11464            workspace.activate_item(&item_b, false, false, window, cx);
11465        });
11466        cx.run_until_parked();
11467
11468        workspace.update_in(cx, |workspace, window, cx| {
11469            workspace.activate_item(&item_a, false, false, window, cx);
11470        });
11471        cx.run_until_parked();
11472
11473        workspace.update_in(cx, |workspace, window, cx| {
11474            workspace.activate_item(&item_b, false, false, window, cx);
11475        });
11476        cx.run_until_parked();
11477
11478        workspace.update_in(cx, |workspace, window, cx| {
11479            workspace.activate_item(&item_c, false, false, window, cx);
11480        });
11481        cx.run_until_parked();
11482
11483        let backward_count = pane.read_with(cx, |pane, cx| {
11484            let mut count = 0;
11485            pane.nav_history().for_each_entry(cx, &mut |_, _| {
11486                count += 1;
11487            });
11488            count
11489        });
11490        assert!(
11491            backward_count <= 4,
11492            "Should have at most 4 entries, got {}",
11493            backward_count
11494        );
11495
11496        workspace
11497            .update_in(cx, |workspace, window, cx| {
11498                workspace.go_back(pane.downgrade(), window, cx)
11499            })
11500            .await
11501            .unwrap();
11502
11503        let active_item = workspace.read_with(cx, |workspace, cx| {
11504            workspace.active_item(cx).unwrap().item_id()
11505        });
11506        assert_eq!(
11507            active_item,
11508            item_b.entity_id(),
11509            "After first go_back, should be at item B"
11510        );
11511
11512        workspace
11513            .update_in(cx, |workspace, window, cx| {
11514                workspace.go_back(pane.downgrade(), window, cx)
11515            })
11516            .await
11517            .unwrap();
11518
11519        let active_item = workspace.read_with(cx, |workspace, cx| {
11520            workspace.active_item(cx).unwrap().item_id()
11521        });
11522        assert_eq!(
11523            active_item,
11524            item_a.entity_id(),
11525            "After second go_back, should be at item A"
11526        );
11527
11528        pane.read_with(cx, |pane, _| {
11529            assert!(pane.can_navigate_forward(), "Should be able to go forward");
11530        });
11531    }
11532
11533    #[gpui::test]
11534    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11535        init_test(cx);
11536        let fs = FakeFs::new(cx.executor());
11537        let project = Project::test(fs, [], cx).await;
11538        let (multi_workspace, cx) =
11539            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11540        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11541
11542        workspace.update_in(cx, |workspace, window, cx| {
11543            let first_item = cx.new(|cx| {
11544                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11545            });
11546            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11547            workspace.split_pane(
11548                workspace.active_pane().clone(),
11549                SplitDirection::Right,
11550                window,
11551                cx,
11552            );
11553            workspace.split_pane(
11554                workspace.active_pane().clone(),
11555                SplitDirection::Right,
11556                window,
11557                cx,
11558            );
11559        });
11560
11561        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11562            let panes = workspace.center.panes();
11563            assert!(panes.len() >= 2);
11564            (
11565                panes.first().expect("at least one pane").entity_id(),
11566                panes.last().expect("at least one pane").entity_id(),
11567            )
11568        });
11569
11570        workspace.update_in(cx, |workspace, window, cx| {
11571            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11572        });
11573        workspace.update(cx, |workspace, _| {
11574            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11575            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11576        });
11577
11578        cx.dispatch_action(ActivateLastPane);
11579
11580        workspace.update(cx, |workspace, _| {
11581            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11582        });
11583    }
11584
11585    #[gpui::test]
11586    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11587        init_test(cx);
11588        let fs = FakeFs::new(cx.executor());
11589
11590        let project = Project::test(fs, [], cx).await;
11591        let (workspace, cx) =
11592            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11593
11594        let panel = workspace.update_in(cx, |workspace, window, cx| {
11595            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11596            workspace.add_panel(panel.clone(), window, cx);
11597
11598            workspace
11599                .right_dock()
11600                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11601
11602            panel
11603        });
11604
11605        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11606        pane.update_in(cx, |pane, window, cx| {
11607            let item = cx.new(TestItem::new);
11608            pane.add_item(Box::new(item), true, true, None, window, cx);
11609        });
11610
11611        // Transfer focus from center to panel
11612        workspace.update_in(cx, |workspace, window, cx| {
11613            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11614        });
11615
11616        workspace.update_in(cx, |workspace, window, cx| {
11617            assert!(workspace.right_dock().read(cx).is_open());
11618            assert!(!panel.is_zoomed(window, cx));
11619            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11620        });
11621
11622        // Transfer focus from panel to center
11623        workspace.update_in(cx, |workspace, window, cx| {
11624            workspace.toggle_panel_focus::<TestPanel>(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            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11632        });
11633
11634        // Close the dock
11635        workspace.update_in(cx, |workspace, window, cx| {
11636            workspace.toggle_dock(DockPosition::Right, window, cx);
11637        });
11638
11639        workspace.update_in(cx, |workspace, window, cx| {
11640            assert!(!workspace.right_dock().read(cx).is_open());
11641            assert!(!panel.is_zoomed(window, cx));
11642            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11643            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11644        });
11645
11646        // Open the dock
11647        workspace.update_in(cx, |workspace, window, cx| {
11648            workspace.toggle_dock(DockPosition::Right, window, cx);
11649        });
11650
11651        workspace.update_in(cx, |workspace, window, cx| {
11652            assert!(workspace.right_dock().read(cx).is_open());
11653            assert!(!panel.is_zoomed(window, cx));
11654            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11655        });
11656
11657        // Focus and zoom panel
11658        panel.update_in(cx, |panel, window, cx| {
11659            cx.focus_self(window);
11660            panel.set_zoomed(true, window, cx)
11661        });
11662
11663        workspace.update_in(cx, |workspace, window, cx| {
11664            assert!(workspace.right_dock().read(cx).is_open());
11665            assert!(panel.is_zoomed(window, cx));
11666            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11667        });
11668
11669        // Transfer focus to the center closes the dock
11670        workspace.update_in(cx, |workspace, window, cx| {
11671            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11672        });
11673
11674        workspace.update_in(cx, |workspace, window, cx| {
11675            assert!(!workspace.right_dock().read(cx).is_open());
11676            assert!(panel.is_zoomed(window, cx));
11677            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11678        });
11679
11680        // Transferring focus back to the panel keeps it zoomed
11681        workspace.update_in(cx, |workspace, window, cx| {
11682            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11683        });
11684
11685        workspace.update_in(cx, |workspace, window, cx| {
11686            assert!(workspace.right_dock().read(cx).is_open());
11687            assert!(panel.is_zoomed(window, cx));
11688            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11689        });
11690
11691        // Close the dock while it is zoomed
11692        workspace.update_in(cx, |workspace, window, cx| {
11693            workspace.toggle_dock(DockPosition::Right, window, cx)
11694        });
11695
11696        workspace.update_in(cx, |workspace, window, cx| {
11697            assert!(!workspace.right_dock().read(cx).is_open());
11698            assert!(panel.is_zoomed(window, cx));
11699            assert!(workspace.zoomed.is_none());
11700            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11701        });
11702
11703        // Opening the dock, when it's zoomed, retains focus
11704        workspace.update_in(cx, |workspace, window, cx| {
11705            workspace.toggle_dock(DockPosition::Right, window, cx)
11706        });
11707
11708        workspace.update_in(cx, |workspace, window, cx| {
11709            assert!(workspace.right_dock().read(cx).is_open());
11710            assert!(panel.is_zoomed(window, cx));
11711            assert!(workspace.zoomed.is_some());
11712            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11713        });
11714
11715        // Unzoom and close the panel, zoom the active pane.
11716        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11717        workspace.update_in(cx, |workspace, window, cx| {
11718            workspace.toggle_dock(DockPosition::Right, window, cx)
11719        });
11720        pane.update_in(cx, |pane, window, cx| {
11721            pane.toggle_zoom(&Default::default(), window, cx)
11722        });
11723
11724        // Opening a dock unzooms the pane.
11725        workspace.update_in(cx, |workspace, window, cx| {
11726            workspace.toggle_dock(DockPosition::Right, window, cx)
11727        });
11728        workspace.update_in(cx, |workspace, window, cx| {
11729            let pane = pane.read(cx);
11730            assert!(!pane.is_zoomed());
11731            assert!(!pane.focus_handle(cx).is_focused(window));
11732            assert!(workspace.right_dock().read(cx).is_open());
11733            assert!(workspace.zoomed.is_none());
11734        });
11735    }
11736
11737    #[gpui::test]
11738    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11739        init_test(cx);
11740        let fs = FakeFs::new(cx.executor());
11741
11742        let project = Project::test(fs, [], cx).await;
11743        let (workspace, cx) =
11744            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11745
11746        let panel = workspace.update_in(cx, |workspace, window, cx| {
11747            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11748            workspace.add_panel(panel.clone(), window, cx);
11749            panel
11750        });
11751
11752        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11753        pane.update_in(cx, |pane, window, cx| {
11754            let item = cx.new(TestItem::new);
11755            pane.add_item(Box::new(item), true, true, None, window, cx);
11756        });
11757
11758        // Enable close_panel_on_toggle
11759        cx.update_global(|store: &mut SettingsStore, cx| {
11760            store.update_user_settings(cx, |settings| {
11761                settings.workspace.close_panel_on_toggle = Some(true);
11762            });
11763        });
11764
11765        // Panel starts closed. Toggling should open and focus it.
11766        workspace.update_in(cx, |workspace, window, cx| {
11767            assert!(!workspace.right_dock().read(cx).is_open());
11768            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11769        });
11770
11771        workspace.update_in(cx, |workspace, window, cx| {
11772            assert!(
11773                workspace.right_dock().read(cx).is_open(),
11774                "Dock should be open after toggling from center"
11775            );
11776            assert!(
11777                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11778                "Panel should be focused after toggling from center"
11779            );
11780        });
11781
11782        // Panel is open and focused. Toggling should close the panel and
11783        // return focus to the center.
11784        workspace.update_in(cx, |workspace, window, cx| {
11785            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11786        });
11787
11788        workspace.update_in(cx, |workspace, window, cx| {
11789            assert!(
11790                !workspace.right_dock().read(cx).is_open(),
11791                "Dock should be closed after toggling from focused panel"
11792            );
11793            assert!(
11794                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11795                "Panel should not be focused after toggling from focused panel"
11796            );
11797        });
11798
11799        // Open the dock and focus something else so the panel is open but not
11800        // focused. Toggling should focus the panel (not close it).
11801        workspace.update_in(cx, |workspace, window, cx| {
11802            workspace
11803                .right_dock()
11804                .update(cx, |dock, cx| dock.set_open(true, window, cx));
11805            window.focus(&pane.read(cx).focus_handle(cx), cx);
11806        });
11807
11808        workspace.update_in(cx, |workspace, window, cx| {
11809            assert!(workspace.right_dock().read(cx).is_open());
11810            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11811            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11812        });
11813
11814        workspace.update_in(cx, |workspace, window, cx| {
11815            assert!(
11816                workspace.right_dock().read(cx).is_open(),
11817                "Dock should remain open when toggling focuses an open-but-unfocused panel"
11818            );
11819            assert!(
11820                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11821                "Panel should be focused after toggling an open-but-unfocused panel"
11822            );
11823        });
11824
11825        // Now disable the setting and verify the original behavior: toggling
11826        // from a focused panel moves focus to center but leaves the dock open.
11827        cx.update_global(|store: &mut SettingsStore, cx| {
11828            store.update_user_settings(cx, |settings| {
11829                settings.workspace.close_panel_on_toggle = Some(false);
11830            });
11831        });
11832
11833        workspace.update_in(cx, |workspace, window, cx| {
11834            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11835        });
11836
11837        workspace.update_in(cx, |workspace, window, cx| {
11838            assert!(
11839                workspace.right_dock().read(cx).is_open(),
11840                "Dock should remain open when setting is disabled"
11841            );
11842            assert!(
11843                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11844                "Panel should not be focused after toggling with setting disabled"
11845            );
11846        });
11847    }
11848
11849    #[gpui::test]
11850    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11851        init_test(cx);
11852        let fs = FakeFs::new(cx.executor());
11853
11854        let project = Project::test(fs, [], cx).await;
11855        let (workspace, cx) =
11856            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11857
11858        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11859            workspace.active_pane().clone()
11860        });
11861
11862        // Add an item to the pane so it can be zoomed
11863        workspace.update_in(cx, |workspace, window, cx| {
11864            let item = cx.new(TestItem::new);
11865            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11866        });
11867
11868        // Initially not zoomed
11869        workspace.update_in(cx, |workspace, _window, cx| {
11870            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11871            assert!(
11872                workspace.zoomed.is_none(),
11873                "Workspace should track no zoomed pane"
11874            );
11875            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11876        });
11877
11878        // Zoom In
11879        pane.update_in(cx, |pane, window, cx| {
11880            pane.zoom_in(&crate::ZoomIn, window, cx);
11881        });
11882
11883        workspace.update_in(cx, |workspace, window, cx| {
11884            assert!(
11885                pane.read(cx).is_zoomed(),
11886                "Pane should be zoomed after ZoomIn"
11887            );
11888            assert!(
11889                workspace.zoomed.is_some(),
11890                "Workspace should track the zoomed pane"
11891            );
11892            assert!(
11893                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11894                "ZoomIn should focus the pane"
11895            );
11896        });
11897
11898        // Zoom In again is a no-op
11899        pane.update_in(cx, |pane, window, cx| {
11900            pane.zoom_in(&crate::ZoomIn, window, cx);
11901        });
11902
11903        workspace.update_in(cx, |workspace, window, cx| {
11904            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11905            assert!(
11906                workspace.zoomed.is_some(),
11907                "Workspace still tracks zoomed pane"
11908            );
11909            assert!(
11910                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11911                "Pane remains focused after repeated ZoomIn"
11912            );
11913        });
11914
11915        // Zoom Out
11916        pane.update_in(cx, |pane, window, cx| {
11917            pane.zoom_out(&crate::ZoomOut, window, cx);
11918        });
11919
11920        workspace.update_in(cx, |workspace, _window, cx| {
11921            assert!(
11922                !pane.read(cx).is_zoomed(),
11923                "Pane should unzoom after ZoomOut"
11924            );
11925            assert!(
11926                workspace.zoomed.is_none(),
11927                "Workspace clears zoom tracking after ZoomOut"
11928            );
11929        });
11930
11931        // Zoom Out again is a no-op
11932        pane.update_in(cx, |pane, window, cx| {
11933            pane.zoom_out(&crate::ZoomOut, window, cx);
11934        });
11935
11936        workspace.update_in(cx, |workspace, _window, cx| {
11937            assert!(
11938                !pane.read(cx).is_zoomed(),
11939                "Second ZoomOut keeps pane unzoomed"
11940            );
11941            assert!(
11942                workspace.zoomed.is_none(),
11943                "Workspace remains without zoomed pane"
11944            );
11945        });
11946    }
11947
11948    #[gpui::test]
11949    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11950        init_test(cx);
11951        let fs = FakeFs::new(cx.executor());
11952
11953        let project = Project::test(fs, [], cx).await;
11954        let (workspace, cx) =
11955            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11956        workspace.update_in(cx, |workspace, window, cx| {
11957            // Open two docks
11958            let left_dock = workspace.dock_at_position(DockPosition::Left);
11959            let right_dock = workspace.dock_at_position(DockPosition::Right);
11960
11961            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11962            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11963
11964            assert!(left_dock.read(cx).is_open());
11965            assert!(right_dock.read(cx).is_open());
11966        });
11967
11968        workspace.update_in(cx, |workspace, window, cx| {
11969            // Toggle all docks - should close both
11970            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11971
11972            let left_dock = workspace.dock_at_position(DockPosition::Left);
11973            let right_dock = workspace.dock_at_position(DockPosition::Right);
11974            assert!(!left_dock.read(cx).is_open());
11975            assert!(!right_dock.read(cx).is_open());
11976        });
11977
11978        workspace.update_in(cx, |workspace, window, cx| {
11979            // Toggle again - should reopen both
11980            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11981
11982            let left_dock = workspace.dock_at_position(DockPosition::Left);
11983            let right_dock = workspace.dock_at_position(DockPosition::Right);
11984            assert!(left_dock.read(cx).is_open());
11985            assert!(right_dock.read(cx).is_open());
11986        });
11987    }
11988
11989    #[gpui::test]
11990    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11991        init_test(cx);
11992        let fs = FakeFs::new(cx.executor());
11993
11994        let project = Project::test(fs, [], cx).await;
11995        let (workspace, cx) =
11996            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11997        workspace.update_in(cx, |workspace, window, cx| {
11998            // Open two docks
11999            let left_dock = workspace.dock_at_position(DockPosition::Left);
12000            let right_dock = workspace.dock_at_position(DockPosition::Right);
12001
12002            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12003            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12004
12005            assert!(left_dock.read(cx).is_open());
12006            assert!(right_dock.read(cx).is_open());
12007        });
12008
12009        workspace.update_in(cx, |workspace, window, cx| {
12010            // Close them manually
12011            workspace.toggle_dock(DockPosition::Left, window, cx);
12012            workspace.toggle_dock(DockPosition::Right, window, cx);
12013
12014            let left_dock = workspace.dock_at_position(DockPosition::Left);
12015            let right_dock = workspace.dock_at_position(DockPosition::Right);
12016            assert!(!left_dock.read(cx).is_open());
12017            assert!(!right_dock.read(cx).is_open());
12018        });
12019
12020        workspace.update_in(cx, |workspace, window, cx| {
12021            // Toggle all docks - only last closed (right dock) should reopen
12022            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12023
12024            let left_dock = workspace.dock_at_position(DockPosition::Left);
12025            let right_dock = workspace.dock_at_position(DockPosition::Right);
12026            assert!(!left_dock.read(cx).is_open());
12027            assert!(right_dock.read(cx).is_open());
12028        });
12029    }
12030
12031    #[gpui::test]
12032    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
12033        init_test(cx);
12034        let fs = FakeFs::new(cx.executor());
12035        let project = Project::test(fs, [], cx).await;
12036        let (multi_workspace, cx) =
12037            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12038        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12039
12040        // Open two docks (left and right) with one panel each
12041        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12042            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12043            workspace.add_panel(left_panel.clone(), window, cx);
12044
12045            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12046            workspace.add_panel(right_panel.clone(), window, cx);
12047
12048            workspace.toggle_dock(DockPosition::Left, window, cx);
12049            workspace.toggle_dock(DockPosition::Right, window, cx);
12050
12051            // Verify initial state
12052            assert!(
12053                workspace.left_dock().read(cx).is_open(),
12054                "Left dock should be open"
12055            );
12056            assert_eq!(
12057                workspace
12058                    .left_dock()
12059                    .read(cx)
12060                    .visible_panel()
12061                    .unwrap()
12062                    .panel_id(),
12063                left_panel.panel_id(),
12064                "Left panel should be visible in left dock"
12065            );
12066            assert!(
12067                workspace.right_dock().read(cx).is_open(),
12068                "Right dock should be open"
12069            );
12070            assert_eq!(
12071                workspace
12072                    .right_dock()
12073                    .read(cx)
12074                    .visible_panel()
12075                    .unwrap()
12076                    .panel_id(),
12077                right_panel.panel_id(),
12078                "Right panel should be visible in right dock"
12079            );
12080            assert!(
12081                !workspace.bottom_dock().read(cx).is_open(),
12082                "Bottom dock should be closed"
12083            );
12084
12085            (left_panel, right_panel)
12086        });
12087
12088        // Focus the left panel and move it to the next position (bottom dock)
12089        workspace.update_in(cx, |workspace, window, cx| {
12090            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12091            assert!(
12092                left_panel.read(cx).focus_handle(cx).is_focused(window),
12093                "Left panel should be focused"
12094            );
12095        });
12096
12097        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12098
12099        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12100        workspace.update(cx, |workspace, cx| {
12101            assert!(
12102                !workspace.left_dock().read(cx).is_open(),
12103                "Left dock should be closed"
12104            );
12105            assert!(
12106                workspace.bottom_dock().read(cx).is_open(),
12107                "Bottom dock should now be open"
12108            );
12109            assert_eq!(
12110                left_panel.read(cx).position,
12111                DockPosition::Bottom,
12112                "Left panel should now be in the bottom dock"
12113            );
12114            assert_eq!(
12115                workspace
12116                    .bottom_dock()
12117                    .read(cx)
12118                    .visible_panel()
12119                    .unwrap()
12120                    .panel_id(),
12121                left_panel.panel_id(),
12122                "Left panel should be the visible panel in the bottom dock"
12123            );
12124        });
12125
12126        // Toggle all docks off
12127        workspace.update_in(cx, |workspace, window, cx| {
12128            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12129            assert!(
12130                !workspace.left_dock().read(cx).is_open(),
12131                "Left dock should be closed"
12132            );
12133            assert!(
12134                !workspace.right_dock().read(cx).is_open(),
12135                "Right dock should be closed"
12136            );
12137            assert!(
12138                !workspace.bottom_dock().read(cx).is_open(),
12139                "Bottom dock should be closed"
12140            );
12141        });
12142
12143        // Toggle all docks back on and verify positions are restored
12144        workspace.update_in(cx, |workspace, window, cx| {
12145            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12146            assert!(
12147                !workspace.left_dock().read(cx).is_open(),
12148                "Left dock should remain closed"
12149            );
12150            assert!(
12151                workspace.right_dock().read(cx).is_open(),
12152                "Right dock should remain open"
12153            );
12154            assert!(
12155                workspace.bottom_dock().read(cx).is_open(),
12156                "Bottom dock should remain open"
12157            );
12158            assert_eq!(
12159                left_panel.read(cx).position,
12160                DockPosition::Bottom,
12161                "Left panel should remain in the bottom dock"
12162            );
12163            assert_eq!(
12164                right_panel.read(cx).position,
12165                DockPosition::Right,
12166                "Right panel should remain in the right dock"
12167            );
12168            assert_eq!(
12169                workspace
12170                    .bottom_dock()
12171                    .read(cx)
12172                    .visible_panel()
12173                    .unwrap()
12174                    .panel_id(),
12175                left_panel.panel_id(),
12176                "Left panel should be the visible panel in the right dock"
12177            );
12178        });
12179    }
12180
12181    #[gpui::test]
12182    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12183        init_test(cx);
12184
12185        let fs = FakeFs::new(cx.executor());
12186
12187        let project = Project::test(fs, None, cx).await;
12188        let (workspace, cx) =
12189            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12190
12191        // Let's arrange the panes like this:
12192        //
12193        // +-----------------------+
12194        // |         top           |
12195        // +------+--------+-------+
12196        // | left | center | right |
12197        // +------+--------+-------+
12198        // |        bottom         |
12199        // +-----------------------+
12200
12201        let top_item = cx.new(|cx| {
12202            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12203        });
12204        let bottom_item = cx.new(|cx| {
12205            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12206        });
12207        let left_item = cx.new(|cx| {
12208            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12209        });
12210        let right_item = cx.new(|cx| {
12211            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12212        });
12213        let center_item = cx.new(|cx| {
12214            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12215        });
12216
12217        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12218            let top_pane_id = workspace.active_pane().entity_id();
12219            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12220            workspace.split_pane(
12221                workspace.active_pane().clone(),
12222                SplitDirection::Down,
12223                window,
12224                cx,
12225            );
12226            top_pane_id
12227        });
12228        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12229            let bottom_pane_id = workspace.active_pane().entity_id();
12230            workspace.add_item_to_active_pane(
12231                Box::new(bottom_item.clone()),
12232                None,
12233                false,
12234                window,
12235                cx,
12236            );
12237            workspace.split_pane(
12238                workspace.active_pane().clone(),
12239                SplitDirection::Up,
12240                window,
12241                cx,
12242            );
12243            bottom_pane_id
12244        });
12245        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12246            let left_pane_id = workspace.active_pane().entity_id();
12247            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12248            workspace.split_pane(
12249                workspace.active_pane().clone(),
12250                SplitDirection::Right,
12251                window,
12252                cx,
12253            );
12254            left_pane_id
12255        });
12256        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12257            let right_pane_id = workspace.active_pane().entity_id();
12258            workspace.add_item_to_active_pane(
12259                Box::new(right_item.clone()),
12260                None,
12261                false,
12262                window,
12263                cx,
12264            );
12265            workspace.split_pane(
12266                workspace.active_pane().clone(),
12267                SplitDirection::Left,
12268                window,
12269                cx,
12270            );
12271            right_pane_id
12272        });
12273        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12274            let center_pane_id = workspace.active_pane().entity_id();
12275            workspace.add_item_to_active_pane(
12276                Box::new(center_item.clone()),
12277                None,
12278                false,
12279                window,
12280                cx,
12281            );
12282            center_pane_id
12283        });
12284        cx.executor().run_until_parked();
12285
12286        workspace.update_in(cx, |workspace, window, cx| {
12287            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12288
12289            // Join into next from center pane into right
12290            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12291        });
12292
12293        workspace.update_in(cx, |workspace, window, cx| {
12294            let active_pane = workspace.active_pane();
12295            assert_eq!(right_pane_id, active_pane.entity_id());
12296            assert_eq!(2, active_pane.read(cx).items_len());
12297            let item_ids_in_pane =
12298                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12299            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12300            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12301
12302            // Join into next from right pane into bottom
12303            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12304        });
12305
12306        workspace.update_in(cx, |workspace, window, cx| {
12307            let active_pane = workspace.active_pane();
12308            assert_eq!(bottom_pane_id, active_pane.entity_id());
12309            assert_eq!(3, active_pane.read(cx).items_len());
12310            let item_ids_in_pane =
12311                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12312            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12313            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12314            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12315
12316            // Join into next from bottom pane into left
12317            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12318        });
12319
12320        workspace.update_in(cx, |workspace, window, cx| {
12321            let active_pane = workspace.active_pane();
12322            assert_eq!(left_pane_id, active_pane.entity_id());
12323            assert_eq!(4, active_pane.read(cx).items_len());
12324            let item_ids_in_pane =
12325                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12326            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12327            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12328            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12329            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12330
12331            // Join into next from left pane into top
12332            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12333        });
12334
12335        workspace.update_in(cx, |workspace, window, cx| {
12336            let active_pane = workspace.active_pane();
12337            assert_eq!(top_pane_id, active_pane.entity_id());
12338            assert_eq!(5, active_pane.read(cx).items_len());
12339            let item_ids_in_pane =
12340                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12341            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12342            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12343            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12344            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12345            assert!(item_ids_in_pane.contains(&top_item.item_id()));
12346
12347            // Single pane left: no-op
12348            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12349        });
12350
12351        workspace.update(cx, |workspace, _cx| {
12352            let active_pane = workspace.active_pane();
12353            assert_eq!(top_pane_id, active_pane.entity_id());
12354        });
12355    }
12356
12357    fn add_an_item_to_active_pane(
12358        cx: &mut VisualTestContext,
12359        workspace: &Entity<Workspace>,
12360        item_id: u64,
12361    ) -> Entity<TestItem> {
12362        let item = cx.new(|cx| {
12363            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12364                item_id,
12365                "item{item_id}.txt",
12366                cx,
12367            )])
12368        });
12369        workspace.update_in(cx, |workspace, window, cx| {
12370            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12371        });
12372        item
12373    }
12374
12375    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12376        workspace.update_in(cx, |workspace, window, cx| {
12377            workspace.split_pane(
12378                workspace.active_pane().clone(),
12379                SplitDirection::Right,
12380                window,
12381                cx,
12382            )
12383        })
12384    }
12385
12386    #[gpui::test]
12387    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12388        init_test(cx);
12389        let fs = FakeFs::new(cx.executor());
12390        let project = Project::test(fs, None, cx).await;
12391        let (workspace, cx) =
12392            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12393
12394        add_an_item_to_active_pane(cx, &workspace, 1);
12395        split_pane(cx, &workspace);
12396        add_an_item_to_active_pane(cx, &workspace, 2);
12397        split_pane(cx, &workspace); // empty pane
12398        split_pane(cx, &workspace);
12399        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12400
12401        cx.executor().run_until_parked();
12402
12403        workspace.update(cx, |workspace, cx| {
12404            let num_panes = workspace.panes().len();
12405            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12406            let active_item = workspace
12407                .active_pane()
12408                .read(cx)
12409                .active_item()
12410                .expect("item is in focus");
12411
12412            assert_eq!(num_panes, 4);
12413            assert_eq!(num_items_in_current_pane, 1);
12414            assert_eq!(active_item.item_id(), last_item.item_id());
12415        });
12416
12417        workspace.update_in(cx, |workspace, window, cx| {
12418            workspace.join_all_panes(window, cx);
12419        });
12420
12421        workspace.update(cx, |workspace, cx| {
12422            let num_panes = workspace.panes().len();
12423            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12424            let active_item = workspace
12425                .active_pane()
12426                .read(cx)
12427                .active_item()
12428                .expect("item is in focus");
12429
12430            assert_eq!(num_panes, 1);
12431            assert_eq!(num_items_in_current_pane, 3);
12432            assert_eq!(active_item.item_id(), last_item.item_id());
12433        });
12434    }
12435
12436    #[gpui::test]
12437    async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12438        init_test(cx);
12439        let fs = FakeFs::new(cx.executor());
12440
12441        let project = Project::test(fs, [], cx).await;
12442        let (multi_workspace, cx) =
12443            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12444        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12445
12446        workspace.update(cx, |workspace, _cx| {
12447            workspace.bounds.size.width = px(800.);
12448        });
12449
12450        workspace.update_in(cx, |workspace, window, cx| {
12451            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12452            workspace.add_panel(panel, window, cx);
12453            workspace.toggle_dock(DockPosition::Right, window, cx);
12454        });
12455
12456        let (panel, resized_width, ratio_basis_width) =
12457            workspace.update_in(cx, |workspace, window, cx| {
12458                let item = cx.new(|cx| {
12459                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12460                });
12461                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12462
12463                let dock = workspace.right_dock().read(cx);
12464                let workspace_width = workspace.bounds.size.width;
12465                let initial_width = workspace
12466                    .dock_size(&dock, window, cx)
12467                    .expect("flexible dock should have an initial width");
12468
12469                assert_eq!(initial_width, workspace_width / 2.);
12470
12471                workspace.resize_right_dock(px(300.), window, cx);
12472
12473                let dock = workspace.right_dock().read(cx);
12474                let resized_width = workspace
12475                    .dock_size(&dock, window, cx)
12476                    .expect("flexible dock should keep its resized width");
12477
12478                assert_eq!(resized_width, px(300.));
12479
12480                let panel = workspace
12481                    .right_dock()
12482                    .read(cx)
12483                    .visible_panel()
12484                    .expect("flexible dock should have a visible panel")
12485                    .panel_id();
12486
12487                (panel, resized_width, workspace_width)
12488            });
12489
12490        workspace.update_in(cx, |workspace, window, cx| {
12491            workspace.toggle_dock(DockPosition::Right, window, cx);
12492            workspace.toggle_dock(DockPosition::Right, window, cx);
12493
12494            let dock = workspace.right_dock().read(cx);
12495            let reopened_width = workspace
12496                .dock_size(&dock, window, cx)
12497                .expect("flexible dock should restore when reopened");
12498
12499            assert_eq!(reopened_width, resized_width);
12500
12501            let right_dock = workspace.right_dock().read(cx);
12502            let flexible_panel = right_dock
12503                .visible_panel()
12504                .expect("flexible dock should still have a visible panel");
12505            assert_eq!(flexible_panel.panel_id(), panel);
12506            assert_eq!(
12507                right_dock
12508                    .stored_panel_size_state(flexible_panel.as_ref())
12509                    .and_then(|size_state| size_state.flex),
12510                Some(
12511                    resized_width.to_f64() as f32
12512                        / (workspace.bounds.size.width - resized_width).to_f64() as f32
12513                )
12514            );
12515        });
12516
12517        workspace.update_in(cx, |workspace, window, cx| {
12518            workspace.split_pane(
12519                workspace.active_pane().clone(),
12520                SplitDirection::Right,
12521                window,
12522                cx,
12523            );
12524
12525            let dock = workspace.right_dock().read(cx);
12526            let split_width = workspace
12527                .dock_size(&dock, window, cx)
12528                .expect("flexible dock should keep its user-resized proportion");
12529
12530            assert_eq!(split_width, px(300.));
12531
12532            workspace.bounds.size.width = px(1600.);
12533
12534            let dock = workspace.right_dock().read(cx);
12535            let resized_window_width = workspace
12536                .dock_size(&dock, window, cx)
12537                .expect("flexible dock should preserve proportional size on window resize");
12538
12539            assert_eq!(
12540                resized_window_width,
12541                workspace.bounds.size.width
12542                    * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12543            );
12544        });
12545    }
12546
12547    #[gpui::test]
12548    async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12549        init_test(cx);
12550        let fs = FakeFs::new(cx.executor());
12551
12552        // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12553        {
12554            let project = Project::test(fs.clone(), [], cx).await;
12555            let (multi_workspace, cx) =
12556                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12557            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12558
12559            workspace.update(cx, |workspace, _cx| {
12560                workspace.set_random_database_id();
12561                workspace.bounds.size.width = px(800.);
12562            });
12563
12564            let panel = workspace.update_in(cx, |workspace, window, cx| {
12565                let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12566                workspace.add_panel(panel.clone(), window, cx);
12567                workspace.toggle_dock(DockPosition::Left, window, cx);
12568                panel
12569            });
12570
12571            workspace.update_in(cx, |workspace, window, cx| {
12572                workspace.resize_left_dock(px(350.), window, cx);
12573            });
12574
12575            cx.run_until_parked();
12576
12577            let persisted = workspace.read_with(cx, |workspace, cx| {
12578                workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12579            });
12580            assert_eq!(
12581                persisted.and_then(|s| s.size),
12582                Some(px(350.)),
12583                "fixed-width panel size should be persisted to KVP"
12584            );
12585
12586            // Remove the panel and re-add a fresh instance with the same key.
12587            // The new instance should have its size state restored from KVP.
12588            workspace.update_in(cx, |workspace, window, cx| {
12589                workspace.remove_panel(&panel, window, cx);
12590            });
12591
12592            workspace.update_in(cx, |workspace, window, cx| {
12593                let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12594                workspace.add_panel(new_panel, window, cx);
12595
12596                let left_dock = workspace.left_dock().read(cx);
12597                let size_state = left_dock
12598                    .panel::<TestPanel>()
12599                    .and_then(|p| left_dock.stored_panel_size_state(&p));
12600                assert_eq!(
12601                    size_state.and_then(|s| s.size),
12602                    Some(px(350.)),
12603                    "re-added fixed-width panel should restore persisted size from KVP"
12604                );
12605            });
12606        }
12607
12608        // Flexible panel: both pixel size and ratio are persisted and restored.
12609        {
12610            let project = Project::test(fs.clone(), [], cx).await;
12611            let (multi_workspace, cx) =
12612                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12613            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12614
12615            workspace.update(cx, |workspace, _cx| {
12616                workspace.set_random_database_id();
12617                workspace.bounds.size.width = px(800.);
12618            });
12619
12620            let panel = workspace.update_in(cx, |workspace, window, cx| {
12621                let item = cx.new(|cx| {
12622                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12623                });
12624                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12625
12626                let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12627                workspace.add_panel(panel.clone(), window, cx);
12628                workspace.toggle_dock(DockPosition::Right, window, cx);
12629                panel
12630            });
12631
12632            workspace.update_in(cx, |workspace, window, cx| {
12633                workspace.resize_right_dock(px(300.), window, cx);
12634            });
12635
12636            cx.run_until_parked();
12637
12638            let persisted = workspace
12639                .read_with(cx, |workspace, cx| {
12640                    workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12641                })
12642                .expect("flexible panel state should be persisted to KVP");
12643            assert_eq!(
12644                persisted.size, None,
12645                "flexible panel should not persist a redundant pixel size"
12646            );
12647            let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12648
12649            // Remove the panel and re-add: both size and ratio should be restored.
12650            workspace.update_in(cx, |workspace, window, cx| {
12651                workspace.remove_panel(&panel, window, cx);
12652            });
12653
12654            workspace.update_in(cx, |workspace, window, cx| {
12655                let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12656                workspace.add_panel(new_panel, window, cx);
12657
12658                let right_dock = workspace.right_dock().read(cx);
12659                let size_state = right_dock
12660                    .panel::<TestPanel>()
12661                    .and_then(|p| right_dock.stored_panel_size_state(&p))
12662                    .expect("re-added flexible panel should have restored size state from KVP");
12663                assert_eq!(
12664                    size_state.size, None,
12665                    "re-added flexible panel should not have a persisted pixel size"
12666                );
12667                assert_eq!(
12668                    size_state.flex,
12669                    Some(original_ratio),
12670                    "re-added flexible panel should restore persisted flex"
12671                );
12672            });
12673        }
12674    }
12675
12676    #[gpui::test]
12677    async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12678        init_test(cx);
12679        let fs = FakeFs::new(cx.executor());
12680
12681        let project = Project::test(fs, [], cx).await;
12682        let (multi_workspace, cx) =
12683            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12684        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12685
12686        workspace.update(cx, |workspace, _cx| {
12687            workspace.bounds.size.width = px(900.);
12688        });
12689
12690        // Step 1: Add a tab to the center pane then open a flexible panel in the left
12691        // dock. With one full-width center pane the default ratio is 0.5, so the panel
12692        // and the center pane each take half the workspace width.
12693        workspace.update_in(cx, |workspace, window, cx| {
12694            let item = cx.new(|cx| {
12695                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12696            });
12697            workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12698
12699            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12700            workspace.add_panel(panel, window, cx);
12701            workspace.toggle_dock(DockPosition::Left, window, cx);
12702
12703            let left_dock = workspace.left_dock().read(cx);
12704            let left_width = workspace
12705                .dock_size(&left_dock, window, cx)
12706                .expect("left dock should have an active panel");
12707
12708            assert_eq!(
12709                left_width,
12710                workspace.bounds.size.width / 2.,
12711                "flexible left panel should split evenly with the center pane"
12712            );
12713        });
12714
12715        // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12716        // change horizontal width fractions, so the flexible panel stays at the same
12717        // width as each half of the split.
12718        workspace.update_in(cx, |workspace, window, cx| {
12719            workspace.split_pane(
12720                workspace.active_pane().clone(),
12721                SplitDirection::Down,
12722                window,
12723                cx,
12724            );
12725
12726            let left_dock = workspace.left_dock().read(cx);
12727            let left_width = workspace
12728                .dock_size(&left_dock, window, cx)
12729                .expect("left dock should still have an active panel after vertical split");
12730
12731            assert_eq!(
12732                left_width,
12733                workspace.bounds.size.width / 2.,
12734                "flexible left panel width should match each vertically-split pane"
12735            );
12736        });
12737
12738        // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12739        // size reduces the available width, so the flexible left panel and the center
12740        // panes all shrink proportionally to accommodate it.
12741        workspace.update_in(cx, |workspace, window, cx| {
12742            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12743            workspace.add_panel(panel, window, cx);
12744            workspace.toggle_dock(DockPosition::Right, window, cx);
12745
12746            let right_dock = workspace.right_dock().read(cx);
12747            let right_width = workspace
12748                .dock_size(&right_dock, window, cx)
12749                .expect("right dock should have an active panel");
12750
12751            let left_dock = workspace.left_dock().read(cx);
12752            let left_width = workspace
12753                .dock_size(&left_dock, window, cx)
12754                .expect("left dock should still have an active panel");
12755
12756            let available_width = workspace.bounds.size.width - right_width;
12757            assert_eq!(
12758                left_width,
12759                available_width / 2.,
12760                "flexible left panel should shrink proportionally as the right dock takes space"
12761            );
12762        });
12763
12764        // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12765        // flex sizing and the workspace width is divided among left-flex, center
12766        // (implicit flex 1.0), and right-flex.
12767        workspace.update_in(cx, |workspace, window, cx| {
12768            let right_dock = workspace.right_dock().clone();
12769            let right_panel = right_dock
12770                .read(cx)
12771                .visible_panel()
12772                .expect("right dock should have a visible panel")
12773                .clone();
12774            workspace.toggle_dock_panel_flexible_size(
12775                &right_dock,
12776                right_panel.as_ref(),
12777                window,
12778                cx,
12779            );
12780
12781            let right_dock = right_dock.read(cx);
12782            let right_panel = right_dock
12783                .visible_panel()
12784                .expect("right dock should still have a visible panel");
12785            assert!(
12786                right_panel.has_flexible_size(window, cx),
12787                "right panel should now be flexible"
12788            );
12789
12790            let right_size_state = right_dock
12791                .stored_panel_size_state(right_panel.as_ref())
12792                .expect("right panel should have a stored size state after toggling");
12793            let right_flex = right_size_state
12794                .flex
12795                .expect("right panel should have a flex value after toggling");
12796
12797            let left_dock = workspace.left_dock().read(cx);
12798            let left_width = workspace
12799                .dock_size(&left_dock, window, cx)
12800                .expect("left dock should still have an active panel");
12801            let right_width = workspace
12802                .dock_size(&right_dock, window, cx)
12803                .expect("right dock should still have an active panel");
12804
12805            let left_flex = workspace
12806                .default_dock_flex(DockPosition::Left)
12807                .expect("left dock should have a default flex");
12808
12809            let total_flex = left_flex + 1.0 + right_flex;
12810            let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12811            let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12812            assert_eq!(
12813                left_width, expected_left,
12814                "flexible left panel should share workspace width via flex ratios"
12815            );
12816            assert_eq!(
12817                right_width, expected_right,
12818                "flexible right panel should share workspace width via flex ratios"
12819            );
12820        });
12821    }
12822
12823    struct TestModal(FocusHandle);
12824
12825    impl TestModal {
12826        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12827            Self(cx.focus_handle())
12828        }
12829    }
12830
12831    impl EventEmitter<DismissEvent> for TestModal {}
12832
12833    impl Focusable for TestModal {
12834        fn focus_handle(&self, _cx: &App) -> FocusHandle {
12835            self.0.clone()
12836        }
12837    }
12838
12839    impl ModalView for TestModal {}
12840
12841    impl Render for TestModal {
12842        fn render(
12843            &mut self,
12844            _window: &mut Window,
12845            _cx: &mut Context<TestModal>,
12846        ) -> impl IntoElement {
12847            div().track_focus(&self.0)
12848        }
12849    }
12850
12851    #[gpui::test]
12852    async fn test_panels(cx: &mut gpui::TestAppContext) {
12853        init_test(cx);
12854        let fs = FakeFs::new(cx.executor());
12855
12856        let project = Project::test(fs, [], cx).await;
12857        let (multi_workspace, cx) =
12858            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12859        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12860
12861        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12862            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12863            workspace.add_panel(panel_1.clone(), window, cx);
12864            workspace.toggle_dock(DockPosition::Left, window, cx);
12865            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12866            workspace.add_panel(panel_2.clone(), window, cx);
12867            workspace.toggle_dock(DockPosition::Right, window, cx);
12868
12869            let left_dock = workspace.left_dock();
12870            assert_eq!(
12871                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12872                panel_1.panel_id()
12873            );
12874            assert_eq!(
12875                workspace.dock_size(&left_dock.read(cx), window, cx),
12876                Some(px(300.))
12877            );
12878
12879            workspace.resize_left_dock(px(1337.), window, cx);
12880            assert_eq!(
12881                workspace
12882                    .right_dock()
12883                    .read(cx)
12884                    .visible_panel()
12885                    .unwrap()
12886                    .panel_id(),
12887                panel_2.panel_id(),
12888            );
12889
12890            (panel_1, panel_2)
12891        });
12892
12893        // Move panel_1 to the right
12894        panel_1.update_in(cx, |panel_1, window, cx| {
12895            panel_1.set_position(DockPosition::Right, window, cx)
12896        });
12897
12898        workspace.update_in(cx, |workspace, window, cx| {
12899            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12900            // Since it was the only panel on the left, the left dock should now be closed.
12901            assert!(!workspace.left_dock().read(cx).is_open());
12902            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12903            let right_dock = workspace.right_dock();
12904            assert_eq!(
12905                right_dock.read(cx).visible_panel().unwrap().panel_id(),
12906                panel_1.panel_id()
12907            );
12908            assert_eq!(
12909                right_dock
12910                    .read(cx)
12911                    .active_panel_size()
12912                    .unwrap()
12913                    .size
12914                    .unwrap(),
12915                px(1337.)
12916            );
12917
12918            // Now we move panel_2 to the left
12919            panel_2.set_position(DockPosition::Left, window, cx);
12920        });
12921
12922        workspace.update(cx, |workspace, cx| {
12923            // Since panel_2 was not visible on the right, we don't open the left dock.
12924            assert!(!workspace.left_dock().read(cx).is_open());
12925            // And the right dock is unaffected in its displaying of panel_1
12926            assert!(workspace.right_dock().read(cx).is_open());
12927            assert_eq!(
12928                workspace
12929                    .right_dock()
12930                    .read(cx)
12931                    .visible_panel()
12932                    .unwrap()
12933                    .panel_id(),
12934                panel_1.panel_id(),
12935            );
12936        });
12937
12938        // Move panel_1 back to the left
12939        panel_1.update_in(cx, |panel_1, window, cx| {
12940            panel_1.set_position(DockPosition::Left, window, cx)
12941        });
12942
12943        workspace.update_in(cx, |workspace, window, cx| {
12944            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12945            let left_dock = workspace.left_dock();
12946            assert!(left_dock.read(cx).is_open());
12947            assert_eq!(
12948                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12949                panel_1.panel_id()
12950            );
12951            assert_eq!(
12952                workspace.dock_size(&left_dock.read(cx), window, cx),
12953                Some(px(1337.))
12954            );
12955            // And the right dock should be closed as it no longer has any panels.
12956            assert!(!workspace.right_dock().read(cx).is_open());
12957
12958            // Now we move panel_1 to the bottom
12959            panel_1.set_position(DockPosition::Bottom, window, cx);
12960        });
12961
12962        workspace.update_in(cx, |workspace, window, cx| {
12963            // Since panel_1 was visible on the left, we close the left dock.
12964            assert!(!workspace.left_dock().read(cx).is_open());
12965            // The bottom dock is sized based on the panel's default size,
12966            // since the panel orientation changed from vertical to horizontal.
12967            let bottom_dock = workspace.bottom_dock();
12968            assert_eq!(
12969                workspace.dock_size(&bottom_dock.read(cx), window, cx),
12970                Some(px(300.))
12971            );
12972            // Close bottom dock and move panel_1 back to the left.
12973            bottom_dock.update(cx, |bottom_dock, cx| {
12974                bottom_dock.set_open(false, window, cx)
12975            });
12976            panel_1.set_position(DockPosition::Left, window, cx);
12977        });
12978
12979        // Emit activated event on panel 1
12980        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12981
12982        // Now the left dock is open and panel_1 is active and focused.
12983        workspace.update_in(cx, |workspace, window, cx| {
12984            let left_dock = workspace.left_dock();
12985            assert!(left_dock.read(cx).is_open());
12986            assert_eq!(
12987                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12988                panel_1.panel_id(),
12989            );
12990            assert!(panel_1.focus_handle(cx).is_focused(window));
12991        });
12992
12993        // Emit closed event on panel 2, which is not active
12994        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12995
12996        // Wo don't close the left dock, because panel_2 wasn't the active panel
12997        workspace.update(cx, |workspace, cx| {
12998            let left_dock = workspace.left_dock();
12999            assert!(left_dock.read(cx).is_open());
13000            assert_eq!(
13001                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13002                panel_1.panel_id(),
13003            );
13004        });
13005
13006        // Emitting a ZoomIn event shows the panel as zoomed.
13007        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
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::Left));
13011        });
13012
13013        // Move panel to another dock while it is zoomed
13014        panel_1.update_in(cx, |panel, window, cx| {
13015            panel.set_position(DockPosition::Right, window, cx)
13016        });
13017        workspace.read_with(cx, |workspace, _| {
13018            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13019
13020            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13021        });
13022
13023        // This is a helper for getting a:
13024        // - valid focus on an element,
13025        // - that isn't a part of the panes and panels system of the Workspace,
13026        // - and doesn't trigger the 'on_focus_lost' API.
13027        let focus_other_view = {
13028            let workspace = workspace.clone();
13029            move |cx: &mut VisualTestContext| {
13030                workspace.update_in(cx, |workspace, window, cx| {
13031                    if workspace.active_modal::<TestModal>(cx).is_some() {
13032                        workspace.toggle_modal(window, cx, TestModal::new);
13033                        workspace.toggle_modal(window, cx, TestModal::new);
13034                    } else {
13035                        workspace.toggle_modal(window, cx, TestModal::new);
13036                    }
13037                })
13038            }
13039        };
13040
13041        // If focus is transferred to another view that's not a panel or another pane, we still show
13042        // the panel as zoomed.
13043        focus_other_view(cx);
13044        workspace.read_with(cx, |workspace, _| {
13045            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13046            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13047        });
13048
13049        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13050        workspace.update_in(cx, |_workspace, window, cx| {
13051            cx.focus_self(window);
13052        });
13053        workspace.read_with(cx, |workspace, _| {
13054            assert_eq!(workspace.zoomed, None);
13055            assert_eq!(workspace.zoomed_position, None);
13056        });
13057
13058        // If focus is transferred again to another view that's not a panel or a pane, we won't
13059        // show the panel as zoomed because it wasn't zoomed before.
13060        focus_other_view(cx);
13061        workspace.read_with(cx, |workspace, _| {
13062            assert_eq!(workspace.zoomed, None);
13063            assert_eq!(workspace.zoomed_position, None);
13064        });
13065
13066        // When the panel is activated, it is zoomed again.
13067        cx.dispatch_action(ToggleRightDock);
13068        workspace.read_with(cx, |workspace, _| {
13069            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13070            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13071        });
13072
13073        // Emitting a ZoomOut event unzooms the panel.
13074        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13075        workspace.read_with(cx, |workspace, _| {
13076            assert_eq!(workspace.zoomed, None);
13077            assert_eq!(workspace.zoomed_position, None);
13078        });
13079
13080        // Emit closed event on panel 1, which is active
13081        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13082
13083        // Now the left dock is closed, because panel_1 was the active panel
13084        workspace.update(cx, |workspace, cx| {
13085            let right_dock = workspace.right_dock();
13086            assert!(!right_dock.read(cx).is_open());
13087        });
13088    }
13089
13090    #[gpui::test]
13091    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13092        init_test(cx);
13093
13094        let fs = FakeFs::new(cx.background_executor.clone());
13095        let project = Project::test(fs, [], cx).await;
13096        let (workspace, cx) =
13097            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13098        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13099
13100        let dirty_regular_buffer = cx.new(|cx| {
13101            TestItem::new(cx)
13102                .with_dirty(true)
13103                .with_label("1.txt")
13104                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13105        });
13106        let dirty_regular_buffer_2 = cx.new(|cx| {
13107            TestItem::new(cx)
13108                .with_dirty(true)
13109                .with_label("2.txt")
13110                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13111        });
13112        let dirty_multi_buffer_with_both = cx.new(|cx| {
13113            TestItem::new(cx)
13114                .with_dirty(true)
13115                .with_buffer_kind(ItemBufferKind::Multibuffer)
13116                .with_label("Fake Project Search")
13117                .with_project_items(&[
13118                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13119                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13120                ])
13121        });
13122        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13123        workspace.update_in(cx, |workspace, window, cx| {
13124            workspace.add_item(
13125                pane.clone(),
13126                Box::new(dirty_regular_buffer.clone()),
13127                None,
13128                false,
13129                false,
13130                window,
13131                cx,
13132            );
13133            workspace.add_item(
13134                pane.clone(),
13135                Box::new(dirty_regular_buffer_2.clone()),
13136                None,
13137                false,
13138                false,
13139                window,
13140                cx,
13141            );
13142            workspace.add_item(
13143                pane.clone(),
13144                Box::new(dirty_multi_buffer_with_both.clone()),
13145                None,
13146                false,
13147                false,
13148                window,
13149                cx,
13150            );
13151        });
13152
13153        pane.update_in(cx, |pane, window, cx| {
13154            pane.activate_item(2, true, true, window, cx);
13155            assert_eq!(
13156                pane.active_item().unwrap().item_id(),
13157                multi_buffer_with_both_files_id,
13158                "Should select the multi buffer in the pane"
13159            );
13160        });
13161        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13162            pane.close_other_items(
13163                &CloseOtherItems {
13164                    save_intent: Some(SaveIntent::Save),
13165                    close_pinned: true,
13166                },
13167                None,
13168                window,
13169                cx,
13170            )
13171        });
13172        cx.background_executor.run_until_parked();
13173        assert!(!cx.has_pending_prompt());
13174        close_all_but_multi_buffer_task
13175            .await
13176            .expect("Closing all buffers but the multi buffer failed");
13177        pane.update(cx, |pane, cx| {
13178            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13179            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13180            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13181            assert_eq!(pane.items_len(), 1);
13182            assert_eq!(
13183                pane.active_item().unwrap().item_id(),
13184                multi_buffer_with_both_files_id,
13185                "Should have only the multi buffer left in the pane"
13186            );
13187            assert!(
13188                dirty_multi_buffer_with_both.read(cx).is_dirty,
13189                "The multi buffer containing the unsaved buffer should still be dirty"
13190            );
13191        });
13192
13193        dirty_regular_buffer.update(cx, |buffer, cx| {
13194            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13195        });
13196
13197        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13198            pane.close_active_item(
13199                &CloseActiveItem {
13200                    save_intent: Some(SaveIntent::Close),
13201                    close_pinned: false,
13202                },
13203                window,
13204                cx,
13205            )
13206        });
13207        cx.background_executor.run_until_parked();
13208        assert!(
13209            cx.has_pending_prompt(),
13210            "Dirty multi buffer should prompt a save dialog"
13211        );
13212        cx.simulate_prompt_answer("Save");
13213        cx.background_executor.run_until_parked();
13214        close_multi_buffer_task
13215            .await
13216            .expect("Closing the multi buffer failed");
13217        pane.update(cx, |pane, cx| {
13218            assert_eq!(
13219                dirty_multi_buffer_with_both.read(cx).save_count,
13220                1,
13221                "Multi buffer item should get be saved"
13222            );
13223            // Test impl does not save inner items, so we do not assert them
13224            assert_eq!(
13225                pane.items_len(),
13226                0,
13227                "No more items should be left in the pane"
13228            );
13229            assert!(pane.active_item().is_none());
13230        });
13231    }
13232
13233    #[gpui::test]
13234    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13235        cx: &mut TestAppContext,
13236    ) {
13237        init_test(cx);
13238
13239        let fs = FakeFs::new(cx.background_executor.clone());
13240        let project = Project::test(fs, [], cx).await;
13241        let (workspace, cx) =
13242            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13243        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13244
13245        let dirty_regular_buffer = cx.new(|cx| {
13246            TestItem::new(cx)
13247                .with_dirty(true)
13248                .with_label("1.txt")
13249                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13250        });
13251        let dirty_regular_buffer_2 = cx.new(|cx| {
13252            TestItem::new(cx)
13253                .with_dirty(true)
13254                .with_label("2.txt")
13255                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13256        });
13257        let clear_regular_buffer = cx.new(|cx| {
13258            TestItem::new(cx)
13259                .with_label("3.txt")
13260                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13261        });
13262
13263        let dirty_multi_buffer_with_both = cx.new(|cx| {
13264            TestItem::new(cx)
13265                .with_dirty(true)
13266                .with_buffer_kind(ItemBufferKind::Multibuffer)
13267                .with_label("Fake Project Search")
13268                .with_project_items(&[
13269                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13270                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13271                    clear_regular_buffer.read(cx).project_items[0].clone(),
13272                ])
13273        });
13274        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13275        workspace.update_in(cx, |workspace, window, cx| {
13276            workspace.add_item(
13277                pane.clone(),
13278                Box::new(dirty_regular_buffer.clone()),
13279                None,
13280                false,
13281                false,
13282                window,
13283                cx,
13284            );
13285            workspace.add_item(
13286                pane.clone(),
13287                Box::new(dirty_multi_buffer_with_both.clone()),
13288                None,
13289                false,
13290                false,
13291                window,
13292                cx,
13293            );
13294        });
13295
13296        pane.update_in(cx, |pane, window, cx| {
13297            pane.activate_item(1, true, true, window, cx);
13298            assert_eq!(
13299                pane.active_item().unwrap().item_id(),
13300                multi_buffer_with_both_files_id,
13301                "Should select the multi buffer in the pane"
13302            );
13303        });
13304        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13305            pane.close_active_item(
13306                &CloseActiveItem {
13307                    save_intent: None,
13308                    close_pinned: false,
13309                },
13310                window,
13311                cx,
13312            )
13313        });
13314        cx.background_executor.run_until_parked();
13315        assert!(
13316            cx.has_pending_prompt(),
13317            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13318        );
13319    }
13320
13321    /// Tests that when `close_on_file_delete` is enabled, files are automatically
13322    /// closed when they are deleted from disk.
13323    #[gpui::test]
13324    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13325        init_test(cx);
13326
13327        // Enable the close_on_disk_deletion setting
13328        cx.update_global(|store: &mut SettingsStore, cx| {
13329            store.update_user_settings(cx, |settings| {
13330                settings.workspace.close_on_file_delete = Some(true);
13331            });
13332        });
13333
13334        let fs = FakeFs::new(cx.background_executor.clone());
13335        let project = Project::test(fs, [], cx).await;
13336        let (workspace, cx) =
13337            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13338        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13339
13340        // Create a test item that simulates a file
13341        let item = cx.new(|cx| {
13342            TestItem::new(cx)
13343                .with_label("test.txt")
13344                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13345        });
13346
13347        // Add item to workspace
13348        workspace.update_in(cx, |workspace, window, cx| {
13349            workspace.add_item(
13350                pane.clone(),
13351                Box::new(item.clone()),
13352                None,
13353                false,
13354                false,
13355                window,
13356                cx,
13357            );
13358        });
13359
13360        // Verify the item is in the pane
13361        pane.read_with(cx, |pane, _| {
13362            assert_eq!(pane.items().count(), 1);
13363        });
13364
13365        // Simulate file deletion by setting the item's deleted state
13366        item.update(cx, |item, _| {
13367            item.set_has_deleted_file(true);
13368        });
13369
13370        // Emit UpdateTab event to trigger the close behavior
13371        cx.run_until_parked();
13372        item.update(cx, |_, cx| {
13373            cx.emit(ItemEvent::UpdateTab);
13374        });
13375
13376        // Allow the close operation to complete
13377        cx.run_until_parked();
13378
13379        // Verify the item was automatically closed
13380        pane.read_with(cx, |pane, _| {
13381            assert_eq!(
13382                pane.items().count(),
13383                0,
13384                "Item should be automatically closed when file is deleted"
13385            );
13386        });
13387    }
13388
13389    /// Tests that when `close_on_file_delete` is disabled (default), files remain
13390    /// open with a strikethrough when they are deleted from disk.
13391    #[gpui::test]
13392    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13393        init_test(cx);
13394
13395        // Ensure close_on_disk_deletion is disabled (default)
13396        cx.update_global(|store: &mut SettingsStore, cx| {
13397            store.update_user_settings(cx, |settings| {
13398                settings.workspace.close_on_file_delete = Some(false);
13399            });
13400        });
13401
13402        let fs = FakeFs::new(cx.background_executor.clone());
13403        let project = Project::test(fs, [], cx).await;
13404        let (workspace, cx) =
13405            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13406        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13407
13408        // Create a test item that simulates a file
13409        let item = cx.new(|cx| {
13410            TestItem::new(cx)
13411                .with_label("test.txt")
13412                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13413        });
13414
13415        // Add item to workspace
13416        workspace.update_in(cx, |workspace, window, cx| {
13417            workspace.add_item(
13418                pane.clone(),
13419                Box::new(item.clone()),
13420                None,
13421                false,
13422                false,
13423                window,
13424                cx,
13425            );
13426        });
13427
13428        // Verify the item is in the pane
13429        pane.read_with(cx, |pane, _| {
13430            assert_eq!(pane.items().count(), 1);
13431        });
13432
13433        // Simulate file deletion
13434        item.update(cx, |item, _| {
13435            item.set_has_deleted_file(true);
13436        });
13437
13438        // Emit UpdateTab event
13439        cx.run_until_parked();
13440        item.update(cx, |_, cx| {
13441            cx.emit(ItemEvent::UpdateTab);
13442        });
13443
13444        // Allow any potential close operation to complete
13445        cx.run_until_parked();
13446
13447        // Verify the item remains open (with strikethrough)
13448        pane.read_with(cx, |pane, _| {
13449            assert_eq!(
13450                pane.items().count(),
13451                1,
13452                "Item should remain open when close_on_disk_deletion is disabled"
13453            );
13454        });
13455
13456        // Verify the item shows as deleted
13457        item.read_with(cx, |item, _| {
13458            assert!(
13459                item.has_deleted_file,
13460                "Item should be marked as having deleted file"
13461            );
13462        });
13463    }
13464
13465    /// Tests that dirty files are not automatically closed when deleted from disk,
13466    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13467    /// unsaved changes without being prompted.
13468    #[gpui::test]
13469    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13470        init_test(cx);
13471
13472        // Enable the close_on_file_delete setting
13473        cx.update_global(|store: &mut SettingsStore, cx| {
13474            store.update_user_settings(cx, |settings| {
13475                settings.workspace.close_on_file_delete = Some(true);
13476            });
13477        });
13478
13479        let fs = FakeFs::new(cx.background_executor.clone());
13480        let project = Project::test(fs, [], cx).await;
13481        let (workspace, cx) =
13482            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13483        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13484
13485        // Create a dirty test item
13486        let item = cx.new(|cx| {
13487            TestItem::new(cx)
13488                .with_dirty(true)
13489                .with_label("test.txt")
13490                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13491        });
13492
13493        // Add item to workspace
13494        workspace.update_in(cx, |workspace, window, cx| {
13495            workspace.add_item(
13496                pane.clone(),
13497                Box::new(item.clone()),
13498                None,
13499                false,
13500                false,
13501                window,
13502                cx,
13503            );
13504        });
13505
13506        // Simulate file deletion
13507        item.update(cx, |item, _| {
13508            item.set_has_deleted_file(true);
13509        });
13510
13511        // Emit UpdateTab event to trigger the close behavior
13512        cx.run_until_parked();
13513        item.update(cx, |_, cx| {
13514            cx.emit(ItemEvent::UpdateTab);
13515        });
13516
13517        // Allow any potential close operation to complete
13518        cx.run_until_parked();
13519
13520        // Verify the item remains open (dirty files are not auto-closed)
13521        pane.read_with(cx, |pane, _| {
13522            assert_eq!(
13523                pane.items().count(),
13524                1,
13525                "Dirty items should not be automatically closed even when file is deleted"
13526            );
13527        });
13528
13529        // Verify the item is marked as deleted and still dirty
13530        item.read_with(cx, |item, _| {
13531            assert!(
13532                item.has_deleted_file,
13533                "Item should be marked as having deleted file"
13534            );
13535            assert!(item.is_dirty, "Item should still be dirty");
13536        });
13537    }
13538
13539    /// Tests that navigation history is cleaned up when files are auto-closed
13540    /// due to deletion from disk.
13541    #[gpui::test]
13542    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13543        init_test(cx);
13544
13545        // Enable the close_on_file_delete setting
13546        cx.update_global(|store: &mut SettingsStore, cx| {
13547            store.update_user_settings(cx, |settings| {
13548                settings.workspace.close_on_file_delete = Some(true);
13549            });
13550        });
13551
13552        let fs = FakeFs::new(cx.background_executor.clone());
13553        let project = Project::test(fs, [], cx).await;
13554        let (workspace, cx) =
13555            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13556        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13557
13558        // Create test items
13559        let item1 = cx.new(|cx| {
13560            TestItem::new(cx)
13561                .with_label("test1.txt")
13562                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13563        });
13564        let item1_id = item1.item_id();
13565
13566        let item2 = cx.new(|cx| {
13567            TestItem::new(cx)
13568                .with_label("test2.txt")
13569                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13570        });
13571
13572        // Add items to workspace
13573        workspace.update_in(cx, |workspace, window, cx| {
13574            workspace.add_item(
13575                pane.clone(),
13576                Box::new(item1.clone()),
13577                None,
13578                false,
13579                false,
13580                window,
13581                cx,
13582            );
13583            workspace.add_item(
13584                pane.clone(),
13585                Box::new(item2.clone()),
13586                None,
13587                false,
13588                false,
13589                window,
13590                cx,
13591            );
13592        });
13593
13594        // Activate item1 to ensure it gets navigation entries
13595        pane.update_in(cx, |pane, window, cx| {
13596            pane.activate_item(0, true, true, window, cx);
13597        });
13598
13599        // Switch to item2 and back to create navigation history
13600        pane.update_in(cx, |pane, window, cx| {
13601            pane.activate_item(1, true, true, window, cx);
13602        });
13603        cx.run_until_parked();
13604
13605        pane.update_in(cx, |pane, window, cx| {
13606            pane.activate_item(0, true, true, window, cx);
13607        });
13608        cx.run_until_parked();
13609
13610        // Simulate file deletion for item1
13611        item1.update(cx, |item, _| {
13612            item.set_has_deleted_file(true);
13613        });
13614
13615        // Emit UpdateTab event to trigger the close behavior
13616        item1.update(cx, |_, cx| {
13617            cx.emit(ItemEvent::UpdateTab);
13618        });
13619        cx.run_until_parked();
13620
13621        // Verify item1 was closed
13622        pane.read_with(cx, |pane, _| {
13623            assert_eq!(
13624                pane.items().count(),
13625                1,
13626                "Should have 1 item remaining after auto-close"
13627            );
13628        });
13629
13630        // Check navigation history after close
13631        let has_item = pane.read_with(cx, |pane, cx| {
13632            let mut has_item = false;
13633            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13634                if entry.item.id() == item1_id {
13635                    has_item = true;
13636                }
13637            });
13638            has_item
13639        });
13640
13641        assert!(
13642            !has_item,
13643            "Navigation history should not contain closed item entries"
13644        );
13645    }
13646
13647    #[gpui::test]
13648    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13649        cx: &mut TestAppContext,
13650    ) {
13651        init_test(cx);
13652
13653        let fs = FakeFs::new(cx.background_executor.clone());
13654        let project = Project::test(fs, [], cx).await;
13655        let (workspace, cx) =
13656            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13657        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13658
13659        let dirty_regular_buffer = cx.new(|cx| {
13660            TestItem::new(cx)
13661                .with_dirty(true)
13662                .with_label("1.txt")
13663                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13664        });
13665        let dirty_regular_buffer_2 = cx.new(|cx| {
13666            TestItem::new(cx)
13667                .with_dirty(true)
13668                .with_label("2.txt")
13669                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13670        });
13671        let clear_regular_buffer = cx.new(|cx| {
13672            TestItem::new(cx)
13673                .with_label("3.txt")
13674                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13675        });
13676
13677        let dirty_multi_buffer = cx.new(|cx| {
13678            TestItem::new(cx)
13679                .with_dirty(true)
13680                .with_buffer_kind(ItemBufferKind::Multibuffer)
13681                .with_label("Fake Project Search")
13682                .with_project_items(&[
13683                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13684                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13685                    clear_regular_buffer.read(cx).project_items[0].clone(),
13686                ])
13687        });
13688        workspace.update_in(cx, |workspace, window, cx| {
13689            workspace.add_item(
13690                pane.clone(),
13691                Box::new(dirty_regular_buffer.clone()),
13692                None,
13693                false,
13694                false,
13695                window,
13696                cx,
13697            );
13698            workspace.add_item(
13699                pane.clone(),
13700                Box::new(dirty_regular_buffer_2.clone()),
13701                None,
13702                false,
13703                false,
13704                window,
13705                cx,
13706            );
13707            workspace.add_item(
13708                pane.clone(),
13709                Box::new(dirty_multi_buffer.clone()),
13710                None,
13711                false,
13712                false,
13713                window,
13714                cx,
13715            );
13716        });
13717
13718        pane.update_in(cx, |pane, window, cx| {
13719            pane.activate_item(2, true, true, window, cx);
13720            assert_eq!(
13721                pane.active_item().unwrap().item_id(),
13722                dirty_multi_buffer.item_id(),
13723                "Should select the multi buffer in the pane"
13724            );
13725        });
13726        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13727            pane.close_active_item(
13728                &CloseActiveItem {
13729                    save_intent: None,
13730                    close_pinned: false,
13731                },
13732                window,
13733                cx,
13734            )
13735        });
13736        cx.background_executor.run_until_parked();
13737        assert!(
13738            !cx.has_pending_prompt(),
13739            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13740        );
13741        close_multi_buffer_task
13742            .await
13743            .expect("Closing multi buffer failed");
13744        pane.update(cx, |pane, cx| {
13745            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13746            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13747            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13748            assert_eq!(
13749                pane.items()
13750                    .map(|item| item.item_id())
13751                    .sorted()
13752                    .collect::<Vec<_>>(),
13753                vec![
13754                    dirty_regular_buffer.item_id(),
13755                    dirty_regular_buffer_2.item_id(),
13756                ],
13757                "Should have no multi buffer left in the pane"
13758            );
13759            assert!(dirty_regular_buffer.read(cx).is_dirty);
13760            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13761        });
13762    }
13763
13764    #[gpui::test]
13765    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13766        init_test(cx);
13767        let fs = FakeFs::new(cx.executor());
13768        let project = Project::test(fs, [], cx).await;
13769        let (multi_workspace, cx) =
13770            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13771        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13772
13773        // Add a new panel to the right dock, opening the dock and setting the
13774        // focus to the new panel.
13775        let panel = workspace.update_in(cx, |workspace, window, cx| {
13776            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13777            workspace.add_panel(panel.clone(), window, cx);
13778
13779            workspace
13780                .right_dock()
13781                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13782
13783            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13784
13785            panel
13786        });
13787
13788        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13789        // panel to the next valid position which, in this case, is the left
13790        // dock.
13791        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13792        workspace.update(cx, |workspace, cx| {
13793            assert!(workspace.left_dock().read(cx).is_open());
13794            assert_eq!(panel.read(cx).position, DockPosition::Left);
13795        });
13796
13797        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13798        // panel to the next valid position which, in this case, is the bottom
13799        // dock.
13800        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13801        workspace.update(cx, |workspace, cx| {
13802            assert!(workspace.bottom_dock().read(cx).is_open());
13803            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13804        });
13805
13806        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13807        // around moving the panel to its initial position, the right dock.
13808        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13809        workspace.update(cx, |workspace, cx| {
13810            assert!(workspace.right_dock().read(cx).is_open());
13811            assert_eq!(panel.read(cx).position, DockPosition::Right);
13812        });
13813
13814        // Remove focus from the panel, ensuring that, if the panel is not
13815        // focused, the `MoveFocusedPanelToNextPosition` action does not update
13816        // the panel's position, so the panel is still in the right dock.
13817        workspace.update_in(cx, |workspace, window, cx| {
13818            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13819        });
13820
13821        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13822        workspace.update(cx, |workspace, cx| {
13823            assert!(workspace.right_dock().read(cx).is_open());
13824            assert_eq!(panel.read(cx).position, DockPosition::Right);
13825        });
13826    }
13827
13828    #[gpui::test]
13829    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13830        init_test(cx);
13831
13832        let fs = FakeFs::new(cx.executor());
13833        let project = Project::test(fs, [], cx).await;
13834        let (workspace, cx) =
13835            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13836
13837        let item_1 = cx.new(|cx| {
13838            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13839        });
13840        workspace.update_in(cx, |workspace, window, cx| {
13841            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
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            workspace.move_item_to_pane_at_index(
13852                &MoveItemToPane {
13853                    destination: 3,
13854                    focus: true,
13855                    clone: false,
13856                },
13857                window,
13858                cx,
13859            );
13860
13861            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13862            assert_eq!(
13863                pane_items_paths(&workspace.active_pane, cx),
13864                vec!["first.txt".to_string()],
13865                "Single item was not moved anywhere"
13866            );
13867        });
13868
13869        let item_2 = cx.new(|cx| {
13870            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13871        });
13872        workspace.update_in(cx, |workspace, window, cx| {
13873            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13874            assert_eq!(
13875                pane_items_paths(&workspace.panes[0], cx),
13876                vec!["first.txt".to_string(), "second.txt".to_string()],
13877            );
13878            workspace.move_item_to_pane_in_direction(
13879                &MoveItemToPaneInDirection {
13880                    direction: SplitDirection::Right,
13881                    focus: true,
13882                    clone: false,
13883                },
13884                window,
13885                cx,
13886            );
13887
13888            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13889            assert_eq!(
13890                pane_items_paths(&workspace.panes[0], 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                "New item should have been moved to the new pane"
13898            );
13899        });
13900
13901        let item_3 = cx.new(|cx| {
13902            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13903        });
13904        workspace.update_in(cx, |workspace, window, cx| {
13905            let original_pane = workspace.panes[0].clone();
13906            workspace.set_active_pane(&original_pane, window, cx);
13907            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13908            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13909            assert_eq!(
13910                pane_items_paths(&workspace.active_pane, cx),
13911                vec!["first.txt".to_string(), "third.txt".to_string()],
13912                "New pane should be ready to move one item out"
13913            );
13914
13915            workspace.move_item_to_pane_at_index(
13916                &MoveItemToPane {
13917                    destination: 3,
13918                    focus: true,
13919                    clone: false,
13920                },
13921                window,
13922                cx,
13923            );
13924            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13925            assert_eq!(
13926                pane_items_paths(&workspace.active_pane, cx),
13927                vec!["first.txt".to_string()],
13928                "After moving, one item should be left in the original pane"
13929            );
13930            assert_eq!(
13931                pane_items_paths(&workspace.panes[1], cx),
13932                vec!["second.txt".to_string()],
13933                "Previously created pane should be unchanged"
13934            );
13935            assert_eq!(
13936                pane_items_paths(&workspace.panes[2], cx),
13937                vec!["third.txt".to_string()],
13938                "New item should have been moved to the new pane"
13939            );
13940        });
13941    }
13942
13943    #[gpui::test]
13944    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13945        init_test(cx);
13946
13947        let fs = FakeFs::new(cx.executor());
13948        let project = Project::test(fs, [], cx).await;
13949        let (workspace, cx) =
13950            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13951
13952        let item_1 = cx.new(|cx| {
13953            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13954        });
13955        workspace.update_in(cx, |workspace, window, cx| {
13956            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13957            workspace.move_item_to_pane_in_direction(
13958                &MoveItemToPaneInDirection {
13959                    direction: SplitDirection::Right,
13960                    focus: true,
13961                    clone: true,
13962                },
13963                window,
13964                cx,
13965            );
13966        });
13967        cx.run_until_parked();
13968        workspace.update_in(cx, |workspace, window, cx| {
13969            workspace.move_item_to_pane_at_index(
13970                &MoveItemToPane {
13971                    destination: 3,
13972                    focus: true,
13973                    clone: true,
13974                },
13975                window,
13976                cx,
13977            );
13978        });
13979        cx.run_until_parked();
13980
13981        workspace.update(cx, |workspace, cx| {
13982            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13983            for pane in workspace.panes() {
13984                assert_eq!(
13985                    pane_items_paths(pane, cx),
13986                    vec!["first.txt".to_string()],
13987                    "Single item exists in all panes"
13988                );
13989            }
13990        });
13991
13992        // verify that the active pane has been updated after waiting for the
13993        // pane focus event to fire and resolve
13994        workspace.read_with(cx, |workspace, _app| {
13995            assert_eq!(
13996                workspace.active_pane(),
13997                &workspace.panes[2],
13998                "The third pane should be the active one: {:?}",
13999                workspace.panes
14000            );
14001        })
14002    }
14003
14004    #[gpui::test]
14005    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
14006        init_test(cx);
14007
14008        let fs = FakeFs::new(cx.executor());
14009        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
14010
14011        let project = Project::test(fs, ["root".as_ref()], cx).await;
14012        let (workspace, cx) =
14013            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14014
14015        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14016        // Add item to pane A with project path
14017        let item_a = cx.new(|cx| {
14018            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14019        });
14020        workspace.update_in(cx, |workspace, window, cx| {
14021            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14022        });
14023
14024        // Split to create pane B
14025        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14026            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14027        });
14028
14029        // Add item with SAME project path to pane B, and pin it
14030        let item_b = cx.new(|cx| {
14031            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14032        });
14033        pane_b.update_in(cx, |pane, window, cx| {
14034            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14035            pane.set_pinned_count(1);
14036        });
14037
14038        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14039        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14040
14041        // close_pinned: false should only close the unpinned copy
14042        workspace.update_in(cx, |workspace, window, cx| {
14043            workspace.close_item_in_all_panes(
14044                &CloseItemInAllPanes {
14045                    save_intent: Some(SaveIntent::Close),
14046                    close_pinned: false,
14047                },
14048                window,
14049                cx,
14050            )
14051        });
14052        cx.executor().run_until_parked();
14053
14054        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14055        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14056        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14057        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14058
14059        // Split again, seeing as closing the previous item also closed its
14060        // pane, so only pane remains, which does not allow us to properly test
14061        // that both items close when `close_pinned: true`.
14062        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14063            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14064        });
14065
14066        // Add an item with the same project path to pane C so that
14067        // close_item_in_all_panes can determine what to close across all panes
14068        // (it reads the active item from the active pane, and split_pane
14069        // creates an empty pane).
14070        let item_c = cx.new(|cx| {
14071            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14072        });
14073        pane_c.update_in(cx, |pane, window, cx| {
14074            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14075        });
14076
14077        // close_pinned: true should close the pinned copy too
14078        workspace.update_in(cx, |workspace, window, cx| {
14079            let panes_count = workspace.panes().len();
14080            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14081
14082            workspace.close_item_in_all_panes(
14083                &CloseItemInAllPanes {
14084                    save_intent: Some(SaveIntent::Close),
14085                    close_pinned: true,
14086                },
14087                window,
14088                cx,
14089            )
14090        });
14091        cx.executor().run_until_parked();
14092
14093        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14094        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14095        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14096        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14097    }
14098
14099    mod register_project_item_tests {
14100
14101        use super::*;
14102
14103        // View
14104        struct TestPngItemView {
14105            focus_handle: FocusHandle,
14106        }
14107        // Model
14108        struct TestPngItem {}
14109
14110        impl project::ProjectItem for TestPngItem {
14111            fn try_open(
14112                _project: &Entity<Project>,
14113                path: &ProjectPath,
14114                cx: &mut App,
14115            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14116                if path.path.extension().unwrap() == "png" {
14117                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14118                } else {
14119                    None
14120                }
14121            }
14122
14123            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14124                None
14125            }
14126
14127            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14128                None
14129            }
14130
14131            fn is_dirty(&self) -> bool {
14132                false
14133            }
14134        }
14135
14136        impl Item for TestPngItemView {
14137            type Event = ();
14138            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14139                "".into()
14140            }
14141        }
14142        impl EventEmitter<()> for TestPngItemView {}
14143        impl Focusable for TestPngItemView {
14144            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14145                self.focus_handle.clone()
14146            }
14147        }
14148
14149        impl Render for TestPngItemView {
14150            fn render(
14151                &mut self,
14152                _window: &mut Window,
14153                _cx: &mut Context<Self>,
14154            ) -> impl IntoElement {
14155                Empty
14156            }
14157        }
14158
14159        impl ProjectItem for TestPngItemView {
14160            type Item = TestPngItem;
14161
14162            fn for_project_item(
14163                _project: Entity<Project>,
14164                _pane: Option<&Pane>,
14165                _item: Entity<Self::Item>,
14166                _: &mut Window,
14167                cx: &mut Context<Self>,
14168            ) -> Self
14169            where
14170                Self: Sized,
14171            {
14172                Self {
14173                    focus_handle: cx.focus_handle(),
14174                }
14175            }
14176        }
14177
14178        // View
14179        struct TestIpynbItemView {
14180            focus_handle: FocusHandle,
14181        }
14182        // Model
14183        struct TestIpynbItem {}
14184
14185        impl project::ProjectItem for TestIpynbItem {
14186            fn try_open(
14187                _project: &Entity<Project>,
14188                path: &ProjectPath,
14189                cx: &mut App,
14190            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14191                if path.path.extension().unwrap() == "ipynb" {
14192                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14193                } else {
14194                    None
14195                }
14196            }
14197
14198            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14199                None
14200            }
14201
14202            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14203                None
14204            }
14205
14206            fn is_dirty(&self) -> bool {
14207                false
14208            }
14209        }
14210
14211        impl Item for TestIpynbItemView {
14212            type Event = ();
14213            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14214                "".into()
14215            }
14216        }
14217        impl EventEmitter<()> for TestIpynbItemView {}
14218        impl Focusable for TestIpynbItemView {
14219            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14220                self.focus_handle.clone()
14221            }
14222        }
14223
14224        impl Render for TestIpynbItemView {
14225            fn render(
14226                &mut self,
14227                _window: &mut Window,
14228                _cx: &mut Context<Self>,
14229            ) -> impl IntoElement {
14230                Empty
14231            }
14232        }
14233
14234        impl ProjectItem for TestIpynbItemView {
14235            type Item = TestIpynbItem;
14236
14237            fn for_project_item(
14238                _project: Entity<Project>,
14239                _pane: Option<&Pane>,
14240                _item: Entity<Self::Item>,
14241                _: &mut Window,
14242                cx: &mut Context<Self>,
14243            ) -> Self
14244            where
14245                Self: Sized,
14246            {
14247                Self {
14248                    focus_handle: cx.focus_handle(),
14249                }
14250            }
14251        }
14252
14253        struct TestAlternatePngItemView {
14254            focus_handle: FocusHandle,
14255        }
14256
14257        impl Item for TestAlternatePngItemView {
14258            type Event = ();
14259            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14260                "".into()
14261            }
14262        }
14263
14264        impl EventEmitter<()> for TestAlternatePngItemView {}
14265        impl Focusable for TestAlternatePngItemView {
14266            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14267                self.focus_handle.clone()
14268            }
14269        }
14270
14271        impl Render for TestAlternatePngItemView {
14272            fn render(
14273                &mut self,
14274                _window: &mut Window,
14275                _cx: &mut Context<Self>,
14276            ) -> impl IntoElement {
14277                Empty
14278            }
14279        }
14280
14281        impl ProjectItem for TestAlternatePngItemView {
14282            type Item = TestPngItem;
14283
14284            fn for_project_item(
14285                _project: Entity<Project>,
14286                _pane: Option<&Pane>,
14287                _item: Entity<Self::Item>,
14288                _: &mut Window,
14289                cx: &mut Context<Self>,
14290            ) -> Self
14291            where
14292                Self: Sized,
14293            {
14294                Self {
14295                    focus_handle: cx.focus_handle(),
14296                }
14297            }
14298        }
14299
14300        #[gpui::test]
14301        async fn test_register_project_item(cx: &mut TestAppContext) {
14302            init_test(cx);
14303
14304            cx.update(|cx| {
14305                register_project_item::<TestPngItemView>(cx);
14306                register_project_item::<TestIpynbItemView>(cx);
14307            });
14308
14309            let fs = FakeFs::new(cx.executor());
14310            fs.insert_tree(
14311                "/root1",
14312                json!({
14313                    "one.png": "BINARYDATAHERE",
14314                    "two.ipynb": "{ totally a notebook }",
14315                    "three.txt": "editing text, sure why not?"
14316                }),
14317            )
14318            .await;
14319
14320            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14321            let (workspace, cx) =
14322                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14323
14324            let worktree_id = project.update(cx, |project, cx| {
14325                project.worktrees(cx).next().unwrap().read(cx).id()
14326            });
14327
14328            let handle = workspace
14329                .update_in(cx, |workspace, window, cx| {
14330                    let project_path = (worktree_id, rel_path("one.png"));
14331                    workspace.open_path(project_path, None, true, window, cx)
14332                })
14333                .await
14334                .unwrap();
14335
14336            // Now we can check if the handle we got back errored or not
14337            assert_eq!(
14338                handle.to_any_view().entity_type(),
14339                TypeId::of::<TestPngItemView>()
14340            );
14341
14342            let handle = workspace
14343                .update_in(cx, |workspace, window, cx| {
14344                    let project_path = (worktree_id, rel_path("two.ipynb"));
14345                    workspace.open_path(project_path, None, true, window, cx)
14346                })
14347                .await
14348                .unwrap();
14349
14350            assert_eq!(
14351                handle.to_any_view().entity_type(),
14352                TypeId::of::<TestIpynbItemView>()
14353            );
14354
14355            let handle = workspace
14356                .update_in(cx, |workspace, window, cx| {
14357                    let project_path = (worktree_id, rel_path("three.txt"));
14358                    workspace.open_path(project_path, None, true, window, cx)
14359                })
14360                .await;
14361            assert!(handle.is_err());
14362        }
14363
14364        #[gpui::test]
14365        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14366            init_test(cx);
14367
14368            cx.update(|cx| {
14369                register_project_item::<TestPngItemView>(cx);
14370                register_project_item::<TestAlternatePngItemView>(cx);
14371            });
14372
14373            let fs = FakeFs::new(cx.executor());
14374            fs.insert_tree(
14375                "/root1",
14376                json!({
14377                    "one.png": "BINARYDATAHERE",
14378                    "two.ipynb": "{ totally a notebook }",
14379                    "three.txt": "editing text, sure why not?"
14380                }),
14381            )
14382            .await;
14383            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14384            let (workspace, cx) =
14385                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14386            let worktree_id = project.update(cx, |project, cx| {
14387                project.worktrees(cx).next().unwrap().read(cx).id()
14388            });
14389
14390            let handle = workspace
14391                .update_in(cx, |workspace, window, cx| {
14392                    let project_path = (worktree_id, rel_path("one.png"));
14393                    workspace.open_path(project_path, None, true, window, cx)
14394                })
14395                .await
14396                .unwrap();
14397
14398            // This _must_ be the second item registered
14399            assert_eq!(
14400                handle.to_any_view().entity_type(),
14401                TypeId::of::<TestAlternatePngItemView>()
14402            );
14403
14404            let handle = workspace
14405                .update_in(cx, |workspace, window, cx| {
14406                    let project_path = (worktree_id, rel_path("three.txt"));
14407                    workspace.open_path(project_path, None, true, window, cx)
14408                })
14409                .await;
14410            assert!(handle.is_err());
14411        }
14412    }
14413
14414    #[gpui::test]
14415    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14416        init_test(cx);
14417
14418        let fs = FakeFs::new(cx.executor());
14419        let project = Project::test(fs, [], cx).await;
14420        let (workspace, _cx) =
14421            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14422
14423        // Test with status bar shown (default)
14424        workspace.read_with(cx, |workspace, cx| {
14425            let visible = workspace.status_bar_visible(cx);
14426            assert!(visible, "Status bar should be visible by default");
14427        });
14428
14429        // Test with status bar hidden
14430        cx.update_global(|store: &mut SettingsStore, cx| {
14431            store.update_user_settings(cx, |settings| {
14432                settings.status_bar.get_or_insert_default().show = Some(false);
14433            });
14434        });
14435
14436        workspace.read_with(cx, |workspace, cx| {
14437            let visible = workspace.status_bar_visible(cx);
14438            assert!(!visible, "Status bar should be hidden when show is false");
14439        });
14440
14441        // Test with status bar shown explicitly
14442        cx.update_global(|store: &mut SettingsStore, cx| {
14443            store.update_user_settings(cx, |settings| {
14444                settings.status_bar.get_or_insert_default().show = Some(true);
14445            });
14446        });
14447
14448        workspace.read_with(cx, |workspace, cx| {
14449            let visible = workspace.status_bar_visible(cx);
14450            assert!(visible, "Status bar should be visible when show is true");
14451        });
14452    }
14453
14454    #[gpui::test]
14455    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14456        init_test(cx);
14457
14458        let fs = FakeFs::new(cx.executor());
14459        let project = Project::test(fs, [], cx).await;
14460        let (multi_workspace, cx) =
14461            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14462        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14463        let panel = workspace.update_in(cx, |workspace, window, cx| {
14464            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14465            workspace.add_panel(panel.clone(), window, cx);
14466
14467            workspace
14468                .right_dock()
14469                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14470
14471            panel
14472        });
14473
14474        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14475        let item_a = cx.new(TestItem::new);
14476        let item_b = cx.new(TestItem::new);
14477        let item_a_id = item_a.entity_id();
14478        let item_b_id = item_b.entity_id();
14479
14480        pane.update_in(cx, |pane, window, cx| {
14481            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14482            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14483        });
14484
14485        pane.read_with(cx, |pane, _| {
14486            assert_eq!(pane.items_len(), 2);
14487            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14488        });
14489
14490        workspace.update_in(cx, |workspace, window, cx| {
14491            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14492        });
14493
14494        workspace.update_in(cx, |_, window, cx| {
14495            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14496        });
14497
14498        // Assert that the `pane::CloseActiveItem` action is handled at the
14499        // workspace level when one of the dock panels is focused and, in that
14500        // case, the center pane's active item is closed but the focus is not
14501        // moved.
14502        cx.dispatch_action(pane::CloseActiveItem::default());
14503        cx.run_until_parked();
14504
14505        pane.read_with(cx, |pane, _| {
14506            assert_eq!(pane.items_len(), 1);
14507            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14508        });
14509
14510        workspace.update_in(cx, |workspace, window, cx| {
14511            assert!(workspace.right_dock().read(cx).is_open());
14512            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14513        });
14514    }
14515
14516    #[gpui::test]
14517    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14518        init_test(cx);
14519        let fs = FakeFs::new(cx.executor());
14520
14521        let project_a = Project::test(fs.clone(), [], cx).await;
14522        let project_b = Project::test(fs, [], cx).await;
14523
14524        let multi_workspace_handle =
14525            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14526        cx.run_until_parked();
14527
14528        let workspace_a = multi_workspace_handle
14529            .read_with(cx, |mw, _| mw.workspace().clone())
14530            .unwrap();
14531
14532        let _workspace_b = multi_workspace_handle
14533            .update(cx, |mw, window, cx| {
14534                mw.test_add_workspace(project_b, window, cx)
14535            })
14536            .unwrap();
14537
14538        // Switch to workspace A
14539        multi_workspace_handle
14540            .update(cx, |mw, window, cx| {
14541                let workspace = mw.workspaces()[0].clone();
14542                mw.activate(workspace, window, cx);
14543            })
14544            .unwrap();
14545
14546        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14547
14548        // Add a panel to workspace A's right dock and open the dock
14549        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14550            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14551            workspace.add_panel(panel.clone(), window, cx);
14552            workspace
14553                .right_dock()
14554                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14555            panel
14556        });
14557
14558        // Focus the panel through the workspace (matching existing test pattern)
14559        workspace_a.update_in(cx, |workspace, window, cx| {
14560            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14561        });
14562
14563        // Zoom the panel
14564        panel.update_in(cx, |panel, window, cx| {
14565            panel.set_zoomed(true, window, cx);
14566        });
14567
14568        // Verify the panel is zoomed and the dock is open
14569        workspace_a.update_in(cx, |workspace, window, cx| {
14570            assert!(
14571                workspace.right_dock().read(cx).is_open(),
14572                "dock should be open before switch"
14573            );
14574            assert!(
14575                panel.is_zoomed(window, cx),
14576                "panel should be zoomed before switch"
14577            );
14578            assert!(
14579                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14580                "panel should be focused before switch"
14581            );
14582        });
14583
14584        // Switch to workspace B
14585        multi_workspace_handle
14586            .update(cx, |mw, window, cx| {
14587                let workspace = mw.workspaces()[1].clone();
14588                mw.activate(workspace, window, cx);
14589            })
14590            .unwrap();
14591        cx.run_until_parked();
14592
14593        // Switch back to workspace A
14594        multi_workspace_handle
14595            .update(cx, |mw, window, cx| {
14596                let workspace = mw.workspaces()[0].clone();
14597                mw.activate(workspace, window, cx);
14598            })
14599            .unwrap();
14600        cx.run_until_parked();
14601
14602        // Verify the panel is still zoomed and the dock is still open
14603        workspace_a.update_in(cx, |workspace, window, cx| {
14604            assert!(
14605                workspace.right_dock().read(cx).is_open(),
14606                "dock should still be open after switching back"
14607            );
14608            assert!(
14609                panel.is_zoomed(window, cx),
14610                "panel should still be zoomed after switching back"
14611            );
14612        });
14613    }
14614
14615    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14616        pane.read(cx)
14617            .items()
14618            .flat_map(|item| {
14619                item.project_paths(cx)
14620                    .into_iter()
14621                    .map(|path| path.path.display(PathStyle::local()).into_owned())
14622            })
14623            .collect()
14624    }
14625
14626    pub fn init_test(cx: &mut TestAppContext) {
14627        cx.update(|cx| {
14628            let settings_store = SettingsStore::test(cx);
14629            cx.set_global(settings_store);
14630            cx.set_global(db::AppDatabase::test_new());
14631            theme_settings::init(theme::LoadThemes::JustBase, cx);
14632        });
14633    }
14634
14635    #[gpui::test]
14636    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14637        use settings::{ThemeName, ThemeSelection};
14638        use theme::SystemAppearance;
14639        use zed_actions::theme::ToggleMode;
14640
14641        init_test(cx);
14642
14643        let fs = FakeFs::new(cx.executor());
14644        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14645
14646        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14647            .await;
14648
14649        // Build a test project and workspace view so the test can invoke
14650        // the workspace action handler the same way the UI would.
14651        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14652        let (workspace, cx) =
14653            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14654
14655        // Seed the settings file with a plain static light theme so the
14656        // first toggle always starts from a known persisted state.
14657        workspace.update_in(cx, |_workspace, _window, cx| {
14658            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14659            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14660                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14661            });
14662        });
14663        cx.executor().advance_clock(Duration::from_millis(200));
14664        cx.run_until_parked();
14665
14666        // Confirm the initial persisted settings contain the static theme
14667        // we just wrote before any toggling happens.
14668        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14669        assert!(settings_text.contains(r#""theme": "One Light""#));
14670
14671        // Toggle once. This should migrate the persisted theme settings
14672        // into light/dark slots and enable system mode.
14673        workspace.update_in(cx, |workspace, window, cx| {
14674            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14675        });
14676        cx.executor().advance_clock(Duration::from_millis(200));
14677        cx.run_until_parked();
14678
14679        // 1. Static -> Dynamic
14680        // this assertion checks theme changed from static to dynamic.
14681        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14682        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14683        assert_eq!(
14684            parsed["theme"],
14685            serde_json::json!({
14686                "mode": "system",
14687                "light": "One Light",
14688                "dark": "One Dark"
14689            })
14690        );
14691
14692        // 2. Toggle again, suppose it will change the mode to light
14693        workspace.update_in(cx, |workspace, window, cx| {
14694            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14695        });
14696        cx.executor().advance_clock(Duration::from_millis(200));
14697        cx.run_until_parked();
14698
14699        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14700        assert!(settings_text.contains(r#""mode": "light""#));
14701    }
14702
14703    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14704        let item = TestProjectItem::new(id, path, cx);
14705        item.update(cx, |item, _| {
14706            item.is_dirty = true;
14707        });
14708        item
14709    }
14710
14711    #[gpui::test]
14712    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14713        cx: &mut gpui::TestAppContext,
14714    ) {
14715        init_test(cx);
14716        let fs = FakeFs::new(cx.executor());
14717
14718        let project = Project::test(fs, [], cx).await;
14719        let (workspace, cx) =
14720            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14721
14722        let panel = workspace.update_in(cx, |workspace, window, cx| {
14723            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14724            workspace.add_panel(panel.clone(), window, cx);
14725            workspace
14726                .right_dock()
14727                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14728            panel
14729        });
14730
14731        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14732        pane.update_in(cx, |pane, window, cx| {
14733            let item = cx.new(TestItem::new);
14734            pane.add_item(Box::new(item), true, true, None, window, cx);
14735        });
14736
14737        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14738        // mirrors the real-world flow and avoids side effects from directly
14739        // focusing the panel while the center pane is active.
14740        workspace.update_in(cx, |workspace, window, cx| {
14741            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14742        });
14743
14744        panel.update_in(cx, |panel, window, cx| {
14745            panel.set_zoomed(true, window, cx);
14746        });
14747
14748        workspace.update_in(cx, |workspace, window, cx| {
14749            assert!(workspace.right_dock().read(cx).is_open());
14750            assert!(panel.is_zoomed(window, cx));
14751            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14752        });
14753
14754        // Simulate a spurious pane::Event::Focus on the center pane while the
14755        // panel still has focus. This mirrors what happens during macOS window
14756        // activation: the center pane fires a focus event even though actual
14757        // focus remains on the dock panel.
14758        pane.update_in(cx, |_, _, cx| {
14759            cx.emit(pane::Event::Focus);
14760        });
14761
14762        // The dock must remain open because the panel had focus at the time the
14763        // event was processed. Before the fix, dock_to_preserve was None for
14764        // panels that don't implement pane(), causing the dock to close.
14765        workspace.update_in(cx, |workspace, window, cx| {
14766            assert!(
14767                workspace.right_dock().read(cx).is_open(),
14768                "Dock should stay open when its zoomed panel (without pane()) still has focus"
14769            );
14770            assert!(panel.is_zoomed(window, cx));
14771        });
14772    }
14773
14774    #[gpui::test]
14775    async fn test_panels_stay_open_after_position_change_and_settings_update(
14776        cx: &mut gpui::TestAppContext,
14777    ) {
14778        init_test(cx);
14779        let fs = FakeFs::new(cx.executor());
14780        let project = Project::test(fs, [], cx).await;
14781        let (workspace, cx) =
14782            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14783
14784        // Add two panels to the left dock and open it.
14785        let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14786            let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14787            let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14788            workspace.add_panel(panel_a.clone(), window, cx);
14789            workspace.add_panel(panel_b.clone(), window, cx);
14790            workspace.left_dock().update(cx, |dock, cx| {
14791                dock.set_open(true, window, cx);
14792                dock.activate_panel(0, window, cx);
14793            });
14794            (panel_a, panel_b)
14795        });
14796
14797        workspace.update_in(cx, |workspace, _, cx| {
14798            assert!(workspace.left_dock().read(cx).is_open());
14799        });
14800
14801        // Simulate a feature flag changing default dock positions: both panels
14802        // move from Left to Right.
14803        workspace.update_in(cx, |_workspace, _window, cx| {
14804            panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14805            panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14806            cx.update_global::<SettingsStore, _>(|_, _| {});
14807        });
14808
14809        // Both panels should now be in the right dock.
14810        workspace.update_in(cx, |workspace, _, cx| {
14811            let right_dock = workspace.right_dock().read(cx);
14812            assert_eq!(right_dock.panels_len(), 2);
14813        });
14814
14815        // Open the right dock and activate panel_b (simulating the user
14816        // opening the panel after it moved).
14817        workspace.update_in(cx, |workspace, window, cx| {
14818            workspace.right_dock().update(cx, |dock, cx| {
14819                dock.set_open(true, window, cx);
14820                dock.activate_panel(1, window, cx);
14821            });
14822        });
14823
14824        // Now trigger another SettingsStore change
14825        workspace.update_in(cx, |_workspace, _window, cx| {
14826            cx.update_global::<SettingsStore, _>(|_, _| {});
14827        });
14828
14829        workspace.update_in(cx, |workspace, _, cx| {
14830            assert!(
14831                workspace.right_dock().read(cx).is_open(),
14832                "Right dock should still be open after a settings change"
14833            );
14834            assert_eq!(
14835                workspace.right_dock().read(cx).panels_len(),
14836                2,
14837                "Both panels should still be in the right dock"
14838            );
14839        });
14840    }
14841}