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;
    8pub mod notifications;
    9pub mod pane;
   10pub mod pane_group;
   11pub mod path_list {
   12    pub use util::path_list::{PathList, SerializedPathList};
   13}
   14mod persistence;
   15pub mod searchable;
   16mod security_modal;
   17pub mod shared_screen;
   18use db::smol::future::yield_now;
   19pub use shared_screen::SharedScreen;
   20mod status_bar;
   21pub mod tasks;
   22mod theme_preview;
   23mod toast_layer;
   24mod toolbar;
   25pub mod welcome;
   26mod workspace_settings;
   27
   28pub use crate::notifications::NotificationFrame;
   29pub use dock::Panel;
   30pub use multi_workspace::{
   31    CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
   32    MultiWorkspaceEvent, NextWorkspace, PreviousWorkspace, Sidebar, SidebarHandle,
   33    SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar, sidebar_side_context_menu,
   34};
   35pub use path_list::{PathList, SerializedPathList};
   36pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   37
   38use anyhow::{Context as _, Result, anyhow};
   39use client::{
   40    ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
   41    proto::{self, ErrorCode, PanelId, PeerId},
   42};
   43use collections::{HashMap, HashSet, hash_map};
   44use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   45use fs::Fs;
   46use futures::{
   47    Future, FutureExt, StreamExt,
   48    channel::{
   49        mpsc::{self, UnboundedReceiver, UnboundedSender},
   50        oneshot,
   51    },
   52    future::{Shared, try_join_all},
   53};
   54use gpui::{
   55    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
   56    Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   57    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   58    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   59    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   60    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   61};
   62pub use history_manager::*;
   63pub use item::{
   64    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   65    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   66};
   67use itertools::Itertools;
   68use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   69pub use modal_layer::*;
   70use node_runtime::NodeRuntime;
   71use notifications::{
   72    DetachAndPromptErr, Notifications, dismiss_app_notification,
   73    simple_message_notification::MessageNotification,
   74};
   75pub use pane::*;
   76pub use pane_group::{
   77    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   78    SplitDirection,
   79};
   80use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
   81pub use persistence::{
   82    WorkspaceDb, delete_unloaded_items,
   83    model::{
   84        DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
   85        SessionWorkspace,
   86    },
   87    read_serialized_multi_workspaces, resolve_worktree_workspaces,
   88};
   89use postage::stream::Stream;
   90use project::{
   91    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
   92    WorktreeSettings,
   93    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   94    project_settings::ProjectSettings,
   95    toolchain_store::ToolchainStoreEvent,
   96    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
   97};
   98use remote::{
   99    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
  100    remote_client::ConnectionIdentifier,
  101};
  102use schemars::JsonSchema;
  103use serde::Deserialize;
  104use session::AppSession;
  105use settings::{
  106    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  107};
  108
  109use sqlez::{
  110    bindable::{Bind, Column, StaticColumnCount},
  111    statement::Statement,
  112};
  113use status_bar::StatusBar;
  114pub use status_bar::StatusItemView;
  115use std::{
  116    any::TypeId,
  117    borrow::Cow,
  118    cell::RefCell,
  119    cmp,
  120    collections::VecDeque,
  121    env,
  122    hash::Hash,
  123    path::{Path, PathBuf},
  124    process::ExitStatus,
  125    rc::Rc,
  126    sync::{
  127        Arc, LazyLock, Weak,
  128        atomic::{AtomicBool, AtomicUsize},
  129    },
  130    time::Duration,
  131};
  132use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  133use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
  134pub use toolbar::{
  135    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  136};
  137pub use ui;
  138use ui::{Window, prelude::*};
  139use util::{
  140    ResultExt, TryFutureExt,
  141    paths::{PathStyle, SanitizedPath},
  142    rel_path::RelPath,
  143    serde::default_true,
  144};
  145use uuid::Uuid;
  146pub use workspace_settings::{
  147    AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
  148    WorkspaceSettings,
  149};
  150use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
  151
  152use crate::{item::ItemBufferKind, notifications::NotificationId};
  153use crate::{
  154    persistence::{
  155        SerializedAxis,
  156        model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
  157    },
  158    security_modal::SecurityModal,
  159};
  160
  161pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  162
  163static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  164    env::var("ZED_WINDOW_SIZE")
  165        .ok()
  166        .as_deref()
  167        .and_then(parse_pixel_size_env_var)
  168});
  169
  170static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  171    env::var("ZED_WINDOW_POSITION")
  172        .ok()
  173        .as_deref()
  174        .and_then(parse_pixel_position_env_var)
  175});
  176
  177pub trait TerminalProvider {
  178    fn spawn(
  179        &self,
  180        task: SpawnInTerminal,
  181        window: &mut Window,
  182        cx: &mut App,
  183    ) -> Task<Option<Result<ExitStatus>>>;
  184}
  185
  186pub trait DebuggerProvider {
  187    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  188    fn start_session(
  189        &self,
  190        definition: DebugScenario,
  191        task_context: SharedTaskContext,
  192        active_buffer: Option<Entity<Buffer>>,
  193        worktree_id: Option<WorktreeId>,
  194        window: &mut Window,
  195        cx: &mut App,
  196    );
  197
  198    fn spawn_task_or_modal(
  199        &self,
  200        workspace: &mut Workspace,
  201        action: &Spawn,
  202        window: &mut Window,
  203        cx: &mut Context<Workspace>,
  204    );
  205
  206    fn task_scheduled(&self, cx: &mut App);
  207    fn debug_scenario_scheduled(&self, cx: &mut App);
  208    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  209
  210    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  211}
  212
  213/// Opens a file or directory.
  214#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  215#[action(namespace = workspace)]
  216pub struct Open {
  217    /// When true, opens in a new window. When false, adds to the current
  218    /// window as a new workspace (multi-workspace).
  219    #[serde(default = "Open::default_create_new_window")]
  220    pub create_new_window: bool,
  221}
  222
  223impl Open {
  224    pub const DEFAULT: Self = Self {
  225        create_new_window: true,
  226    };
  227
  228    /// Used by `#[serde(default)]` on the `create_new_window` field so that
  229    /// the serde default and `Open::DEFAULT` stay in sync.
  230    fn default_create_new_window() -> bool {
  231        Self::DEFAULT.create_new_window
  232    }
  233}
  234
  235impl Default for Open {
  236    fn default() -> Self {
  237        Self::DEFAULT
  238    }
  239}
  240
  241actions!(
  242    workspace,
  243    [
  244        /// Activates the next pane in the workspace.
  245        ActivateNextPane,
  246        /// Activates the previous pane in the workspace.
  247        ActivatePreviousPane,
  248        /// Activates the last pane in the workspace.
  249        ActivateLastPane,
  250        /// Switches to the next window.
  251        ActivateNextWindow,
  252        /// Switches to the previous window.
  253        ActivatePreviousWindow,
  254        /// Adds a folder to the current project.
  255        AddFolderToProject,
  256        /// Clears all notifications.
  257        ClearAllNotifications,
  258        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  259        ClearNavigationHistory,
  260        /// Closes the active dock.
  261        CloseActiveDock,
  262        /// Closes all docks.
  263        CloseAllDocks,
  264        /// Toggles all docks.
  265        ToggleAllDocks,
  266        /// Closes the current window.
  267        CloseWindow,
  268        /// Closes the current project.
  269        CloseProject,
  270        /// Opens the feedback dialog.
  271        Feedback,
  272        /// Follows the next collaborator in the session.
  273        FollowNextCollaborator,
  274        /// Moves the focused panel to the next position.
  275        MoveFocusedPanelToNextPosition,
  276        /// Creates a new file.
  277        NewFile,
  278        /// Creates a new file in a vertical split.
  279        NewFileSplitVertical,
  280        /// Creates a new file in a horizontal split.
  281        NewFileSplitHorizontal,
  282        /// Opens a new search.
  283        NewSearch,
  284        /// Opens a new window.
  285        NewWindow,
  286        /// Opens multiple files.
  287        OpenFiles,
  288        /// Opens the current location in terminal.
  289        OpenInTerminal,
  290        /// Opens the component preview.
  291        OpenComponentPreview,
  292        /// Reloads the active item.
  293        ReloadActiveItem,
  294        /// Resets the active dock to its default size.
  295        ResetActiveDockSize,
  296        /// Resets all open docks to their default sizes.
  297        ResetOpenDocksSize,
  298        /// Reloads the application
  299        Reload,
  300        /// Saves the current file with a new name.
  301        SaveAs,
  302        /// Saves without formatting.
  303        SaveWithoutFormat,
  304        /// Shuts down all debug adapters.
  305        ShutdownDebugAdapters,
  306        /// Suppresses the current notification.
  307        SuppressNotification,
  308        /// Toggles the bottom dock.
  309        ToggleBottomDock,
  310        /// Toggles centered layout mode.
  311        ToggleCenteredLayout,
  312        /// Toggles edit prediction feature globally for all files.
  313        ToggleEditPrediction,
  314        /// Toggles the left dock.
  315        ToggleLeftDock,
  316        /// Toggles the right dock.
  317        ToggleRightDock,
  318        /// Toggles zoom on the active pane.
  319        ToggleZoom,
  320        /// Toggles read-only mode for the active item (if supported by that item).
  321        ToggleReadOnlyFile,
  322        /// Zooms in on the active pane.
  323        ZoomIn,
  324        /// Zooms out of the active pane.
  325        ZoomOut,
  326        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  327        /// If the modal is shown already, closes it without trusting any worktree.
  328        ToggleWorktreeSecurity,
  329        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  330        /// Requires restart to take effect on already opened projects.
  331        ClearTrustedWorktrees,
  332        /// Stops following a collaborator.
  333        Unfollow,
  334        /// Restores the banner.
  335        RestoreBanner,
  336        /// Toggles expansion of the selected item.
  337        ToggleExpandItem,
  338    ]
  339);
  340
  341/// Activates a specific pane by its index.
  342#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  343#[action(namespace = workspace)]
  344pub struct ActivatePane(pub usize);
  345
  346/// Moves an item to a specific pane by index.
  347#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  348#[action(namespace = workspace)]
  349#[serde(deny_unknown_fields)]
  350pub struct MoveItemToPane {
  351    #[serde(default = "default_1")]
  352    pub destination: usize,
  353    #[serde(default = "default_true")]
  354    pub focus: bool,
  355    #[serde(default)]
  356    pub clone: bool,
  357}
  358
  359fn default_1() -> usize {
  360    1
  361}
  362
  363/// Moves an item to a pane in the specified direction.
  364#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  365#[action(namespace = workspace)]
  366#[serde(deny_unknown_fields)]
  367pub struct MoveItemToPaneInDirection {
  368    #[serde(default = "default_right")]
  369    pub direction: SplitDirection,
  370    #[serde(default = "default_true")]
  371    pub focus: bool,
  372    #[serde(default)]
  373    pub clone: bool,
  374}
  375
  376/// Creates a new file in a split of the desired direction.
  377#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  378#[action(namespace = workspace)]
  379#[serde(deny_unknown_fields)]
  380pub struct NewFileSplit(pub SplitDirection);
  381
  382fn default_right() -> SplitDirection {
  383    SplitDirection::Right
  384}
  385
  386/// Saves all open files in the workspace.
  387#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  388#[action(namespace = workspace)]
  389#[serde(deny_unknown_fields)]
  390pub struct SaveAll {
  391    #[serde(default)]
  392    pub save_intent: Option<SaveIntent>,
  393}
  394
  395/// Saves the current file with the specified options.
  396#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  397#[action(namespace = workspace)]
  398#[serde(deny_unknown_fields)]
  399pub struct Save {
  400    #[serde(default)]
  401    pub save_intent: Option<SaveIntent>,
  402}
  403
  404/// Moves Focus to the central panes in the workspace.
  405#[derive(Clone, Debug, PartialEq, Eq, Action)]
  406#[action(namespace = workspace)]
  407pub struct FocusCenterPane;
  408
  409///  Closes all items and panes in the workspace.
  410#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  411#[action(namespace = workspace)]
  412#[serde(deny_unknown_fields)]
  413pub struct CloseAllItemsAndPanes {
  414    #[serde(default)]
  415    pub save_intent: Option<SaveIntent>,
  416}
  417
  418/// Closes all inactive tabs and panes in the workspace.
  419#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  420#[action(namespace = workspace)]
  421#[serde(deny_unknown_fields)]
  422pub struct CloseInactiveTabsAndPanes {
  423    #[serde(default)]
  424    pub save_intent: Option<SaveIntent>,
  425}
  426
  427/// Closes the active item across all panes.
  428#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  429#[action(namespace = workspace)]
  430#[serde(deny_unknown_fields)]
  431pub struct CloseItemInAllPanes {
  432    #[serde(default)]
  433    pub save_intent: Option<SaveIntent>,
  434    #[serde(default)]
  435    pub close_pinned: bool,
  436}
  437
  438/// Sends a sequence of keystrokes to the active element.
  439#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  440#[action(namespace = workspace)]
  441pub struct SendKeystrokes(pub String);
  442
  443actions!(
  444    project_symbols,
  445    [
  446        /// Toggles the project symbols search.
  447        #[action(name = "Toggle")]
  448        ToggleProjectSymbols
  449    ]
  450);
  451
  452/// Toggles the file finder interface.
  453#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  454#[action(namespace = file_finder, name = "Toggle")]
  455#[serde(deny_unknown_fields)]
  456pub struct ToggleFileFinder {
  457    #[serde(default)]
  458    pub separate_history: bool,
  459}
  460
  461/// Opens a new terminal in the center.
  462#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  463#[action(namespace = workspace)]
  464#[serde(deny_unknown_fields)]
  465pub struct NewCenterTerminal {
  466    /// If true, creates a local terminal even in remote projects.
  467    #[serde(default)]
  468    pub local: bool,
  469}
  470
  471/// Opens a new terminal.
  472#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  473#[action(namespace = workspace)]
  474#[serde(deny_unknown_fields)]
  475pub struct NewTerminal {
  476    /// If true, creates a local terminal even in remote projects.
  477    #[serde(default)]
  478    pub local: bool,
  479}
  480
  481/// Increases size of a currently focused dock by a given amount of pixels.
  482#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  483#[action(namespace = workspace)]
  484#[serde(deny_unknown_fields)]
  485pub struct IncreaseActiveDockSize {
  486    /// For 0px parameter, uses UI font size value.
  487    #[serde(default)]
  488    pub px: u32,
  489}
  490
  491/// Decreases size of a currently focused dock by a given amount of pixels.
  492#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  493#[action(namespace = workspace)]
  494#[serde(deny_unknown_fields)]
  495pub struct DecreaseActiveDockSize {
  496    /// For 0px parameter, uses UI font size value.
  497    #[serde(default)]
  498    pub px: u32,
  499}
  500
  501/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  502#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  503#[action(namespace = workspace)]
  504#[serde(deny_unknown_fields)]
  505pub struct IncreaseOpenDocksSize {
  506    /// For 0px parameter, uses UI font size value.
  507    #[serde(default)]
  508    pub px: u32,
  509}
  510
  511/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  512#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  513#[action(namespace = workspace)]
  514#[serde(deny_unknown_fields)]
  515pub struct DecreaseOpenDocksSize {
  516    /// For 0px parameter, uses UI font size value.
  517    #[serde(default)]
  518    pub px: u32,
  519}
  520
  521actions!(
  522    workspace,
  523    [
  524        /// Activates the pane to the left.
  525        ActivatePaneLeft,
  526        /// Activates the pane to the right.
  527        ActivatePaneRight,
  528        /// Activates the pane above.
  529        ActivatePaneUp,
  530        /// Activates the pane below.
  531        ActivatePaneDown,
  532        /// Swaps the current pane with the one to the left.
  533        SwapPaneLeft,
  534        /// Swaps the current pane with the one to the right.
  535        SwapPaneRight,
  536        /// Swaps the current pane with the one above.
  537        SwapPaneUp,
  538        /// Swaps the current pane with the one below.
  539        SwapPaneDown,
  540        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  541        SwapPaneAdjacent,
  542        /// Move the current pane to be at the far left.
  543        MovePaneLeft,
  544        /// Move the current pane to be at the far right.
  545        MovePaneRight,
  546        /// Move the current pane to be at the very top.
  547        MovePaneUp,
  548        /// Move the current pane to be at the very bottom.
  549        MovePaneDown,
  550    ]
  551);
  552
  553#[derive(PartialEq, Eq, Debug)]
  554pub enum CloseIntent {
  555    /// Quit the program entirely.
  556    Quit,
  557    /// Close a window.
  558    CloseWindow,
  559    /// Replace the workspace in an existing window.
  560    ReplaceWindow,
  561}
  562
  563#[derive(Clone)]
  564pub struct Toast {
  565    id: NotificationId,
  566    msg: Cow<'static, str>,
  567    autohide: bool,
  568    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  569}
  570
  571impl Toast {
  572    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  573        Toast {
  574            id,
  575            msg: msg.into(),
  576            on_click: None,
  577            autohide: false,
  578        }
  579    }
  580
  581    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  582    where
  583        M: Into<Cow<'static, str>>,
  584        F: Fn(&mut Window, &mut App) + 'static,
  585    {
  586        self.on_click = Some((message.into(), Arc::new(on_click)));
  587        self
  588    }
  589
  590    pub fn autohide(mut self) -> Self {
  591        self.autohide = true;
  592        self
  593    }
  594}
  595
  596impl PartialEq for Toast {
  597    fn eq(&self, other: &Self) -> bool {
  598        self.id == other.id
  599            && self.msg == other.msg
  600            && self.on_click.is_some() == other.on_click.is_some()
  601    }
  602}
  603
  604/// Opens a new terminal with the specified working directory.
  605#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  606#[action(namespace = workspace)]
  607#[serde(deny_unknown_fields)]
  608pub struct OpenTerminal {
  609    pub working_directory: PathBuf,
  610    /// If true, creates a local terminal even in remote projects.
  611    #[serde(default)]
  612    pub local: bool,
  613}
  614
  615#[derive(
  616    Clone,
  617    Copy,
  618    Debug,
  619    Default,
  620    Hash,
  621    PartialEq,
  622    Eq,
  623    PartialOrd,
  624    Ord,
  625    serde::Serialize,
  626    serde::Deserialize,
  627)]
  628pub struct WorkspaceId(i64);
  629
  630impl WorkspaceId {
  631    pub fn from_i64(value: i64) -> Self {
  632        Self(value)
  633    }
  634}
  635
  636impl StaticColumnCount for WorkspaceId {}
  637impl Bind for WorkspaceId {
  638    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  639        self.0.bind(statement, start_index)
  640    }
  641}
  642impl Column for WorkspaceId {
  643    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  644        i64::column(statement, start_index)
  645            .map(|(i, next_index)| (Self(i), next_index))
  646            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  647    }
  648}
  649impl From<WorkspaceId> for i64 {
  650    fn from(val: WorkspaceId) -> Self {
  651        val.0
  652    }
  653}
  654
  655fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
  656    if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
  657        workspace_window
  658            .update(cx, |multi_workspace, window, cx| {
  659                let workspace = multi_workspace.workspace().clone();
  660                workspace.update(cx, |workspace, cx| {
  661                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  662                });
  663            })
  664            .ok();
  665    } else {
  666        let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, true, cx);
  667        cx.spawn(async move |cx| {
  668            let OpenResult { window, .. } = task.await?;
  669            window.update(cx, |multi_workspace, window, cx| {
  670                window.activate_window();
  671                let workspace = multi_workspace.workspace().clone();
  672                workspace.update(cx, |workspace, cx| {
  673                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  674                });
  675            })?;
  676            anyhow::Ok(())
  677        })
  678        .detach_and_log_err(cx);
  679    }
  680}
  681
  682pub fn prompt_for_open_path_and_open(
  683    workspace: &mut Workspace,
  684    app_state: Arc<AppState>,
  685    options: PathPromptOptions,
  686    create_new_window: bool,
  687    window: &mut Window,
  688    cx: &mut Context<Workspace>,
  689) {
  690    let paths = workspace.prompt_for_open_path(
  691        options,
  692        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  693        window,
  694        cx,
  695    );
  696    let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
  697    cx.spawn_in(window, async move |this, cx| {
  698        let Some(paths) = paths.await.log_err().flatten() else {
  699            return;
  700        };
  701        if !create_new_window {
  702            if let Some(handle) = multi_workspace_handle {
  703                if let Some(task) = handle
  704                    .update(cx, |multi_workspace, window, cx| {
  705                        multi_workspace.open_project(paths, window, cx)
  706                    })
  707                    .log_err()
  708                {
  709                    task.await.log_err();
  710                }
  711                return;
  712            }
  713        }
  714        if let Some(task) = this
  715            .update_in(cx, |this, window, cx| {
  716                this.open_workspace_for_paths(false, paths, window, cx)
  717            })
  718            .log_err()
  719        {
  720            task.await.log_err();
  721        }
  722    })
  723    .detach();
  724}
  725
  726pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  727    component::init();
  728    theme_preview::init(cx);
  729    toast_layer::init(cx);
  730    history_manager::init(app_state.fs.clone(), cx);
  731
  732    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  733        .on_action(|_: &Reload, cx| reload(cx))
  734        .on_action({
  735            let app_state = Arc::downgrade(&app_state);
  736            move |_: &Open, cx: &mut App| {
  737                if let Some(app_state) = app_state.upgrade() {
  738                    prompt_and_open_paths(
  739                        app_state,
  740                        PathPromptOptions {
  741                            files: true,
  742                            directories: true,
  743                            multiple: true,
  744                            prompt: None,
  745                        },
  746                        cx,
  747                    );
  748                }
  749            }
  750        })
  751        .on_action({
  752            let app_state = Arc::downgrade(&app_state);
  753            move |_: &OpenFiles, cx: &mut App| {
  754                let directories = cx.can_select_mixed_files_and_dirs();
  755                if let Some(app_state) = app_state.upgrade() {
  756                    prompt_and_open_paths(
  757                        app_state,
  758                        PathPromptOptions {
  759                            files: true,
  760                            directories,
  761                            multiple: true,
  762                            prompt: None,
  763                        },
  764                        cx,
  765                    );
  766                }
  767            }
  768        });
  769}
  770
  771type BuildProjectItemFn =
  772    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  773
  774type BuildProjectItemForPathFn =
  775    fn(
  776        &Entity<Project>,
  777        &ProjectPath,
  778        &mut Window,
  779        &mut App,
  780    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  781
  782#[derive(Clone, Default)]
  783struct ProjectItemRegistry {
  784    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  785    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  786}
  787
  788impl ProjectItemRegistry {
  789    fn register<T: ProjectItem>(&mut self) {
  790        self.build_project_item_fns_by_type.insert(
  791            TypeId::of::<T::Item>(),
  792            |item, project, pane, window, cx| {
  793                let item = item.downcast().unwrap();
  794                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  795                    as Box<dyn ItemHandle>
  796            },
  797        );
  798        self.build_project_item_for_path_fns
  799            .push(|project, project_path, window, cx| {
  800                let project_path = project_path.clone();
  801                let is_file = project
  802                    .read(cx)
  803                    .entry_for_path(&project_path, cx)
  804                    .is_some_and(|entry| entry.is_file());
  805                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  806                let is_local = project.read(cx).is_local();
  807                let project_item =
  808                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  809                let project = project.clone();
  810                Some(window.spawn(cx, async move |cx| {
  811                    match project_item.await.with_context(|| {
  812                        format!(
  813                            "opening project path {:?}",
  814                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  815                        )
  816                    }) {
  817                        Ok(project_item) => {
  818                            let project_item = project_item;
  819                            let project_entry_id: Option<ProjectEntryId> =
  820                                project_item.read_with(cx, project::ProjectItem::entry_id);
  821                            let build_workspace_item = Box::new(
  822                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  823                                    Box::new(cx.new(|cx| {
  824                                        T::for_project_item(
  825                                            project,
  826                                            Some(pane),
  827                                            project_item,
  828                                            window,
  829                                            cx,
  830                                        )
  831                                    })) as Box<dyn ItemHandle>
  832                                },
  833                            ) as Box<_>;
  834                            Ok((project_entry_id, build_workspace_item))
  835                        }
  836                        Err(e) => {
  837                            log::warn!("Failed to open a project item: {e:#}");
  838                            if e.error_code() == ErrorCode::Internal {
  839                                if let Some(abs_path) =
  840                                    entry_abs_path.as_deref().filter(|_| is_file)
  841                                {
  842                                    if let Some(broken_project_item_view) =
  843                                        cx.update(|window, cx| {
  844                                            T::for_broken_project_item(
  845                                                abs_path, is_local, &e, window, cx,
  846                                            )
  847                                        })?
  848                                    {
  849                                        let build_workspace_item = Box::new(
  850                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  851                                                cx.new(|_| broken_project_item_view).boxed_clone()
  852                                            },
  853                                        )
  854                                        as Box<_>;
  855                                        return Ok((None, build_workspace_item));
  856                                    }
  857                                }
  858                            }
  859                            Err(e)
  860                        }
  861                    }
  862                }))
  863            });
  864    }
  865
  866    fn open_path(
  867        &self,
  868        project: &Entity<Project>,
  869        path: &ProjectPath,
  870        window: &mut Window,
  871        cx: &mut App,
  872    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  873        let Some(open_project_item) = self
  874            .build_project_item_for_path_fns
  875            .iter()
  876            .rev()
  877            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  878        else {
  879            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  880        };
  881        open_project_item
  882    }
  883
  884    fn build_item<T: project::ProjectItem>(
  885        &self,
  886        item: Entity<T>,
  887        project: Entity<Project>,
  888        pane: Option<&Pane>,
  889        window: &mut Window,
  890        cx: &mut App,
  891    ) -> Option<Box<dyn ItemHandle>> {
  892        let build = self
  893            .build_project_item_fns_by_type
  894            .get(&TypeId::of::<T>())?;
  895        Some(build(item.into_any(), project, pane, window, cx))
  896    }
  897}
  898
  899type WorkspaceItemBuilder =
  900    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  901
  902impl Global for ProjectItemRegistry {}
  903
  904/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  905/// items will get a chance to open the file, starting from the project item that
  906/// was added last.
  907pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  908    cx.default_global::<ProjectItemRegistry>().register::<I>();
  909}
  910
  911#[derive(Default)]
  912pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  913
  914struct FollowableViewDescriptor {
  915    from_state_proto: fn(
  916        Entity<Workspace>,
  917        ViewId,
  918        &mut Option<proto::view::Variant>,
  919        &mut Window,
  920        &mut App,
  921    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  922    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  923}
  924
  925impl Global for FollowableViewRegistry {}
  926
  927impl FollowableViewRegistry {
  928    pub fn register<I: FollowableItem>(cx: &mut App) {
  929        cx.default_global::<Self>().0.insert(
  930            TypeId::of::<I>(),
  931            FollowableViewDescriptor {
  932                from_state_proto: |workspace, id, state, window, cx| {
  933                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  934                        cx.foreground_executor()
  935                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  936                    })
  937                },
  938                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  939            },
  940        );
  941    }
  942
  943    pub fn from_state_proto(
  944        workspace: Entity<Workspace>,
  945        view_id: ViewId,
  946        mut state: Option<proto::view::Variant>,
  947        window: &mut Window,
  948        cx: &mut App,
  949    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  950        cx.update_default_global(|this: &mut Self, cx| {
  951            this.0.values().find_map(|descriptor| {
  952                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  953            })
  954        })
  955    }
  956
  957    pub fn to_followable_view(
  958        view: impl Into<AnyView>,
  959        cx: &App,
  960    ) -> Option<Box<dyn FollowableItemHandle>> {
  961        let this = cx.try_global::<Self>()?;
  962        let view = view.into();
  963        let descriptor = this.0.get(&view.entity_type())?;
  964        Some((descriptor.to_followable_view)(&view))
  965    }
  966}
  967
  968#[derive(Copy, Clone)]
  969struct SerializableItemDescriptor {
  970    deserialize: fn(
  971        Entity<Project>,
  972        WeakEntity<Workspace>,
  973        WorkspaceId,
  974        ItemId,
  975        &mut Window,
  976        &mut Context<Pane>,
  977    ) -> Task<Result<Box<dyn ItemHandle>>>,
  978    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  979    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  980}
  981
  982#[derive(Default)]
  983struct SerializableItemRegistry {
  984    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  985    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  986}
  987
  988impl Global for SerializableItemRegistry {}
  989
  990impl SerializableItemRegistry {
  991    fn deserialize(
  992        item_kind: &str,
  993        project: Entity<Project>,
  994        workspace: WeakEntity<Workspace>,
  995        workspace_id: WorkspaceId,
  996        item_item: ItemId,
  997        window: &mut Window,
  998        cx: &mut Context<Pane>,
  999    ) -> Task<Result<Box<dyn ItemHandle>>> {
 1000        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1001            return Task::ready(Err(anyhow!(
 1002                "cannot deserialize {}, descriptor not found",
 1003                item_kind
 1004            )));
 1005        };
 1006
 1007        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
 1008    }
 1009
 1010    fn cleanup(
 1011        item_kind: &str,
 1012        workspace_id: WorkspaceId,
 1013        loaded_items: Vec<ItemId>,
 1014        window: &mut Window,
 1015        cx: &mut App,
 1016    ) -> Task<Result<()>> {
 1017        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1018            return Task::ready(Err(anyhow!(
 1019                "cannot cleanup {}, descriptor not found",
 1020                item_kind
 1021            )));
 1022        };
 1023
 1024        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
 1025    }
 1026
 1027    fn view_to_serializable_item_handle(
 1028        view: AnyView,
 1029        cx: &App,
 1030    ) -> Option<Box<dyn SerializableItemHandle>> {
 1031        let this = cx.try_global::<Self>()?;
 1032        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
 1033        Some((descriptor.view_to_serializable_item)(view))
 1034    }
 1035
 1036    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
 1037        let this = cx.try_global::<Self>()?;
 1038        this.descriptors_by_kind.get(item_kind).copied()
 1039    }
 1040}
 1041
 1042pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
 1043    let serialized_item_kind = I::serialized_item_kind();
 1044
 1045    let registry = cx.default_global::<SerializableItemRegistry>();
 1046    let descriptor = SerializableItemDescriptor {
 1047        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
 1048            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
 1049            cx.foreground_executor()
 1050                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 1051        },
 1052        cleanup: |workspace_id, loaded_items, window, cx| {
 1053            I::cleanup(workspace_id, loaded_items, window, cx)
 1054        },
 1055        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1056    };
 1057    registry
 1058        .descriptors_by_kind
 1059        .insert(Arc::from(serialized_item_kind), descriptor);
 1060    registry
 1061        .descriptors_by_type
 1062        .insert(TypeId::of::<I>(), descriptor);
 1063}
 1064
 1065pub struct AppState {
 1066    pub languages: Arc<LanguageRegistry>,
 1067    pub client: Arc<Client>,
 1068    pub user_store: Entity<UserStore>,
 1069    pub workspace_store: Entity<WorkspaceStore>,
 1070    pub fs: Arc<dyn fs::Fs>,
 1071    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1072    pub node_runtime: NodeRuntime,
 1073    pub session: Entity<AppSession>,
 1074}
 1075
 1076struct GlobalAppState(Weak<AppState>);
 1077
 1078impl Global for GlobalAppState {}
 1079
 1080pub struct WorkspaceStore {
 1081    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1082    client: Arc<Client>,
 1083    _subscriptions: Vec<client::Subscription>,
 1084}
 1085
 1086#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1087pub enum CollaboratorId {
 1088    PeerId(PeerId),
 1089    Agent,
 1090}
 1091
 1092impl From<PeerId> for CollaboratorId {
 1093    fn from(peer_id: PeerId) -> Self {
 1094        CollaboratorId::PeerId(peer_id)
 1095    }
 1096}
 1097
 1098impl From<&PeerId> for CollaboratorId {
 1099    fn from(peer_id: &PeerId) -> Self {
 1100        CollaboratorId::PeerId(*peer_id)
 1101    }
 1102}
 1103
 1104#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1105struct Follower {
 1106    project_id: Option<u64>,
 1107    peer_id: PeerId,
 1108}
 1109
 1110impl AppState {
 1111    #[track_caller]
 1112    pub fn global(cx: &App) -> Weak<Self> {
 1113        cx.global::<GlobalAppState>().0.clone()
 1114    }
 1115    pub fn try_global(cx: &App) -> Option<Weak<Self>> {
 1116        cx.try_global::<GlobalAppState>()
 1117            .map(|state| state.0.clone())
 1118    }
 1119    pub fn set_global(state: Weak<AppState>, cx: &mut App) {
 1120        cx.set_global(GlobalAppState(state));
 1121    }
 1122
 1123    #[cfg(any(test, feature = "test-support"))]
 1124    pub fn test(cx: &mut App) -> Arc<Self> {
 1125        use fs::Fs;
 1126        use node_runtime::NodeRuntime;
 1127        use session::Session;
 1128        use settings::SettingsStore;
 1129
 1130        if !cx.has_global::<SettingsStore>() {
 1131            let settings_store = SettingsStore::test(cx);
 1132            cx.set_global(settings_store);
 1133        }
 1134
 1135        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1136        <dyn Fs>::set_global(fs.clone(), cx);
 1137        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1138        let clock = Arc::new(clock::FakeSystemClock::new());
 1139        let http_client = http_client::FakeHttpClient::with_404_response();
 1140        let client = Client::new(clock, http_client, cx);
 1141        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1142        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1143        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1144
 1145        theme::init(theme::LoadThemes::JustBase, cx);
 1146        client::init(&client, cx);
 1147
 1148        Arc::new(Self {
 1149            client,
 1150            fs,
 1151            languages,
 1152            user_store,
 1153            workspace_store,
 1154            node_runtime: NodeRuntime::unavailable(),
 1155            build_window_options: |_, _| Default::default(),
 1156            session,
 1157        })
 1158    }
 1159}
 1160
 1161struct DelayedDebouncedEditAction {
 1162    task: Option<Task<()>>,
 1163    cancel_channel: Option<oneshot::Sender<()>>,
 1164}
 1165
 1166impl DelayedDebouncedEditAction {
 1167    fn new() -> DelayedDebouncedEditAction {
 1168        DelayedDebouncedEditAction {
 1169            task: None,
 1170            cancel_channel: None,
 1171        }
 1172    }
 1173
 1174    fn fire_new<F>(
 1175        &mut self,
 1176        delay: Duration,
 1177        window: &mut Window,
 1178        cx: &mut Context<Workspace>,
 1179        func: F,
 1180    ) where
 1181        F: 'static
 1182            + Send
 1183            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1184    {
 1185        if let Some(channel) = self.cancel_channel.take() {
 1186            _ = channel.send(());
 1187        }
 1188
 1189        let (sender, mut receiver) = oneshot::channel::<()>();
 1190        self.cancel_channel = Some(sender);
 1191
 1192        let previous_task = self.task.take();
 1193        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1194            let mut timer = cx.background_executor().timer(delay).fuse();
 1195            if let Some(previous_task) = previous_task {
 1196                previous_task.await;
 1197            }
 1198
 1199            futures::select_biased! {
 1200                _ = receiver => return,
 1201                    _ = timer => {}
 1202            }
 1203
 1204            if let Some(result) = workspace
 1205                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1206                .log_err()
 1207            {
 1208                result.await.log_err();
 1209            }
 1210        }));
 1211    }
 1212}
 1213
 1214pub enum Event {
 1215    PaneAdded(Entity<Pane>),
 1216    PaneRemoved,
 1217    ItemAdded {
 1218        item: Box<dyn ItemHandle>,
 1219    },
 1220    ActiveItemChanged,
 1221    ItemRemoved {
 1222        item_id: EntityId,
 1223    },
 1224    UserSavedItem {
 1225        pane: WeakEntity<Pane>,
 1226        item: Box<dyn WeakItemHandle>,
 1227        save_intent: SaveIntent,
 1228    },
 1229    ContactRequestedJoin(u64),
 1230    WorkspaceCreated(WeakEntity<Workspace>),
 1231    OpenBundledFile {
 1232        text: Cow<'static, str>,
 1233        title: &'static str,
 1234        language: &'static str,
 1235    },
 1236    ZoomChanged,
 1237    ModalOpened,
 1238    Activate,
 1239    PanelAdded(AnyView),
 1240}
 1241
 1242#[derive(Debug, Clone)]
 1243pub enum OpenVisible {
 1244    All,
 1245    None,
 1246    OnlyFiles,
 1247    OnlyDirectories,
 1248}
 1249
 1250enum WorkspaceLocation {
 1251    // Valid local paths or SSH project to serialize
 1252    Location(SerializedWorkspaceLocation, PathList),
 1253    // No valid location found hence clear session id
 1254    DetachFromSession,
 1255    // No valid location found to serialize
 1256    None,
 1257}
 1258
 1259type PromptForNewPath = Box<
 1260    dyn Fn(
 1261        &mut Workspace,
 1262        DirectoryLister,
 1263        Option<String>,
 1264        &mut Window,
 1265        &mut Context<Workspace>,
 1266    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1267>;
 1268
 1269type PromptForOpenPath = Box<
 1270    dyn Fn(
 1271        &mut Workspace,
 1272        DirectoryLister,
 1273        &mut Window,
 1274        &mut Context<Workspace>,
 1275    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1276>;
 1277
 1278#[derive(Default)]
 1279struct DispatchingKeystrokes {
 1280    dispatched: HashSet<Vec<Keystroke>>,
 1281    queue: VecDeque<Keystroke>,
 1282    task: Option<Shared<Task<()>>>,
 1283}
 1284
 1285/// Collects everything project-related for a certain window opened.
 1286/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1287///
 1288/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1289/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1290/// that can be used to register a global action to be triggered from any place in the window.
 1291pub struct Workspace {
 1292    weak_self: WeakEntity<Self>,
 1293    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1294    zoomed: Option<AnyWeakView>,
 1295    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1296    zoomed_position: Option<DockPosition>,
 1297    center: PaneGroup,
 1298    left_dock: Entity<Dock>,
 1299    bottom_dock: Entity<Dock>,
 1300    right_dock: Entity<Dock>,
 1301    panes: Vec<Entity<Pane>>,
 1302    active_worktree_override: Option<WorktreeId>,
 1303    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1304    active_pane: Entity<Pane>,
 1305    last_active_center_pane: Option<WeakEntity<Pane>>,
 1306    last_active_view_id: Option<proto::ViewId>,
 1307    status_bar: Entity<StatusBar>,
 1308    pub(crate) modal_layer: Entity<ModalLayer>,
 1309    toast_layer: Entity<ToastLayer>,
 1310    titlebar_item: Option<AnyView>,
 1311    notifications: Notifications,
 1312    suppressed_notifications: HashSet<NotificationId>,
 1313    project: Entity<Project>,
 1314    follower_states: HashMap<CollaboratorId, FollowerState>,
 1315    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1316    window_edited: bool,
 1317    last_window_title: Option<String>,
 1318    dirty_items: HashMap<EntityId, Subscription>,
 1319    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1320    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1321    database_id: Option<WorkspaceId>,
 1322    app_state: Arc<AppState>,
 1323    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1324    _subscriptions: Vec<Subscription>,
 1325    _apply_leader_updates: Task<Result<()>>,
 1326    _observe_current_user: Task<Result<()>>,
 1327    _schedule_serialize_workspace: Option<Task<()>>,
 1328    _serialize_workspace_task: Option<Task<()>>,
 1329    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1330    pane_history_timestamp: Arc<AtomicUsize>,
 1331    bounds: Bounds<Pixels>,
 1332    pub centered_layout: bool,
 1333    bounds_save_task_queued: Option<Task<()>>,
 1334    on_prompt_for_new_path: Option<PromptForNewPath>,
 1335    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1336    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1337    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1338    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1339    _items_serializer: Task<Result<()>>,
 1340    session_id: Option<String>,
 1341    scheduled_tasks: Vec<Task<()>>,
 1342    last_open_dock_positions: Vec<DockPosition>,
 1343    removing: bool,
 1344    _panels_task: Option<Task<Result<()>>>,
 1345    sidebar_focus_handle: Option<FocusHandle>,
 1346    multi_workspace: Option<WeakEntity<MultiWorkspace>>,
 1347}
 1348
 1349impl EventEmitter<Event> for Workspace {}
 1350
 1351#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1352pub struct ViewId {
 1353    pub creator: CollaboratorId,
 1354    pub id: u64,
 1355}
 1356
 1357pub struct FollowerState {
 1358    center_pane: Entity<Pane>,
 1359    dock_pane: Option<Entity<Pane>>,
 1360    active_view_id: Option<ViewId>,
 1361    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1362}
 1363
 1364struct FollowerView {
 1365    view: Box<dyn FollowableItemHandle>,
 1366    location: Option<proto::PanelId>,
 1367}
 1368
 1369impl Workspace {
 1370    pub fn new(
 1371        workspace_id: Option<WorkspaceId>,
 1372        project: Entity<Project>,
 1373        app_state: Arc<AppState>,
 1374        window: &mut Window,
 1375        cx: &mut Context<Self>,
 1376    ) -> Self {
 1377        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1378            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1379                if let TrustedWorktreesEvent::Trusted(..) = e {
 1380                    // Do not persist auto trusted worktrees
 1381                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1382                        worktrees_store.update(cx, |worktrees_store, cx| {
 1383                            worktrees_store.schedule_serialization(
 1384                                cx,
 1385                                |new_trusted_worktrees, cx| {
 1386                                    let timeout =
 1387                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1388                                    let db = WorkspaceDb::global(cx);
 1389                                    cx.background_spawn(async move {
 1390                                        timeout.await;
 1391                                        db.save_trusted_worktrees(new_trusted_worktrees)
 1392                                            .await
 1393                                            .log_err();
 1394                                    })
 1395                                },
 1396                            )
 1397                        });
 1398                    }
 1399                }
 1400            })
 1401            .detach();
 1402
 1403            cx.observe_global::<SettingsStore>(|_, cx| {
 1404                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1405                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1406                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1407                            trusted_worktrees.auto_trust_all(cx);
 1408                        })
 1409                    }
 1410                }
 1411            })
 1412            .detach();
 1413        }
 1414
 1415        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1416            match event {
 1417                project::Event::RemoteIdChanged(_) => {
 1418                    this.update_window_title(window, cx);
 1419                }
 1420
 1421                project::Event::CollaboratorLeft(peer_id) => {
 1422                    this.collaborator_left(*peer_id, window, cx);
 1423                }
 1424
 1425                &project::Event::WorktreeRemoved(_) => {
 1426                    this.update_window_title(window, cx);
 1427                    this.serialize_workspace(window, cx);
 1428                    this.update_history(cx);
 1429                }
 1430
 1431                &project::Event::WorktreeAdded(id) => {
 1432                    this.update_window_title(window, cx);
 1433                    if this
 1434                        .project()
 1435                        .read(cx)
 1436                        .worktree_for_id(id, cx)
 1437                        .is_some_and(|wt| wt.read(cx).is_visible())
 1438                    {
 1439                        this.serialize_workspace(window, cx);
 1440                        this.update_history(cx);
 1441                    }
 1442                }
 1443                project::Event::WorktreeUpdatedEntries(..) => {
 1444                    this.update_window_title(window, cx);
 1445                    this.serialize_workspace(window, cx);
 1446                }
 1447
 1448                project::Event::DisconnectedFromHost => {
 1449                    this.update_window_edited(window, cx);
 1450                    let leaders_to_unfollow =
 1451                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1452                    for leader_id in leaders_to_unfollow {
 1453                        this.unfollow(leader_id, window, cx);
 1454                    }
 1455                }
 1456
 1457                project::Event::DisconnectedFromRemote {
 1458                    server_not_running: _,
 1459                } => {
 1460                    this.update_window_edited(window, cx);
 1461                }
 1462
 1463                project::Event::Closed => {
 1464                    window.remove_window();
 1465                }
 1466
 1467                project::Event::DeletedEntry(_, entry_id) => {
 1468                    for pane in this.panes.iter() {
 1469                        pane.update(cx, |pane, cx| {
 1470                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1471                        });
 1472                    }
 1473                }
 1474
 1475                project::Event::Toast {
 1476                    notification_id,
 1477                    message,
 1478                    link,
 1479                } => this.show_notification(
 1480                    NotificationId::named(notification_id.clone()),
 1481                    cx,
 1482                    |cx| {
 1483                        let mut notification = MessageNotification::new(message.clone(), cx);
 1484                        if let Some(link) = link {
 1485                            notification = notification
 1486                                .more_info_message(link.label)
 1487                                .more_info_url(link.url);
 1488                        }
 1489
 1490                        cx.new(|_| notification)
 1491                    },
 1492                ),
 1493
 1494                project::Event::HideToast { notification_id } => {
 1495                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1496                }
 1497
 1498                project::Event::LanguageServerPrompt(request) => {
 1499                    struct LanguageServerPrompt;
 1500
 1501                    this.show_notification(
 1502                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1503                        cx,
 1504                        |cx| {
 1505                            cx.new(|cx| {
 1506                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1507                            })
 1508                        },
 1509                    );
 1510                }
 1511
 1512                project::Event::AgentLocationChanged => {
 1513                    this.handle_agent_location_changed(window, cx)
 1514                }
 1515
 1516                _ => {}
 1517            }
 1518            cx.notify()
 1519        })
 1520        .detach();
 1521
 1522        cx.subscribe_in(
 1523            &project.read(cx).breakpoint_store(),
 1524            window,
 1525            |workspace, _, event, window, cx| match event {
 1526                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1527                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1528                    workspace.serialize_workspace(window, cx);
 1529                }
 1530                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1531            },
 1532        )
 1533        .detach();
 1534        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1535            cx.subscribe_in(
 1536                &toolchain_store,
 1537                window,
 1538                |workspace, _, event, window, cx| match event {
 1539                    ToolchainStoreEvent::CustomToolchainsModified => {
 1540                        workspace.serialize_workspace(window, cx);
 1541                    }
 1542                    _ => {}
 1543                },
 1544            )
 1545            .detach();
 1546        }
 1547
 1548        cx.on_focus_lost(window, |this, window, cx| {
 1549            let focus_handle = this.focus_handle(cx);
 1550            window.focus(&focus_handle, cx);
 1551        })
 1552        .detach();
 1553
 1554        let weak_handle = cx.entity().downgrade();
 1555        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1556
 1557        let center_pane = cx.new(|cx| {
 1558            let mut center_pane = Pane::new(
 1559                weak_handle.clone(),
 1560                project.clone(),
 1561                pane_history_timestamp.clone(),
 1562                None,
 1563                NewFile.boxed_clone(),
 1564                true,
 1565                window,
 1566                cx,
 1567            );
 1568            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1569            center_pane.set_should_display_welcome_page(true);
 1570            center_pane
 1571        });
 1572        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1573            .detach();
 1574
 1575        window.focus(&center_pane.focus_handle(cx), cx);
 1576
 1577        cx.emit(Event::PaneAdded(center_pane.clone()));
 1578
 1579        let any_window_handle = window.window_handle();
 1580        app_state.workspace_store.update(cx, |store, _| {
 1581            store
 1582                .workspaces
 1583                .insert((any_window_handle, weak_handle.clone()));
 1584        });
 1585
 1586        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1587        let mut connection_status = app_state.client.status();
 1588        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1589            current_user.next().await;
 1590            connection_status.next().await;
 1591            let mut stream =
 1592                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1593
 1594            while stream.recv().await.is_some() {
 1595                this.update(cx, |_, cx| cx.notify())?;
 1596            }
 1597            anyhow::Ok(())
 1598        });
 1599
 1600        // All leader updates are enqueued and then processed in a single task, so
 1601        // that each asynchronous operation can be run in order.
 1602        let (leader_updates_tx, mut leader_updates_rx) =
 1603            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1604        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1605            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1606                Self::process_leader_update(&this, leader_id, update, cx)
 1607                    .await
 1608                    .log_err();
 1609            }
 1610
 1611            Ok(())
 1612        });
 1613
 1614        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1615        let modal_layer = cx.new(|_| ModalLayer::new());
 1616        let toast_layer = cx.new(|_| ToastLayer::new());
 1617        cx.subscribe(
 1618            &modal_layer,
 1619            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1620                cx.emit(Event::ModalOpened);
 1621            },
 1622        )
 1623        .detach();
 1624
 1625        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1626        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1627        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1628        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1629        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1630        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1631        let multi_workspace = window
 1632            .root::<MultiWorkspace>()
 1633            .flatten()
 1634            .map(|mw| mw.downgrade());
 1635        let status_bar = cx.new(|cx| {
 1636            let mut status_bar =
 1637                StatusBar::new(&center_pane.clone(), multi_workspace.clone(), window, cx);
 1638            status_bar.add_left_item(left_dock_buttons, window, cx);
 1639            status_bar.add_right_item(right_dock_buttons, window, cx);
 1640            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1641            status_bar
 1642        });
 1643
 1644        let session_id = app_state.session.read(cx).id().to_owned();
 1645
 1646        let mut active_call = None;
 1647        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1648            let subscriptions =
 1649                vec![
 1650                    call.0
 1651                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1652                ];
 1653            active_call = Some((call, subscriptions));
 1654        }
 1655
 1656        let (serializable_items_tx, serializable_items_rx) =
 1657            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1658        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1659            Self::serialize_items(&this, serializable_items_rx, cx).await
 1660        });
 1661
 1662        let subscriptions = vec![
 1663            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1664            cx.observe_window_bounds(window, move |this, window, cx| {
 1665                if this.bounds_save_task_queued.is_some() {
 1666                    return;
 1667                }
 1668                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1669                    cx.background_executor()
 1670                        .timer(Duration::from_millis(100))
 1671                        .await;
 1672                    this.update_in(cx, |this, window, cx| {
 1673                        this.save_window_bounds(window, cx).detach();
 1674                        this.bounds_save_task_queued.take();
 1675                    })
 1676                    .ok();
 1677                }));
 1678                cx.notify();
 1679            }),
 1680            cx.observe_window_appearance(window, |_, window, cx| {
 1681                let window_appearance = window.appearance();
 1682
 1683                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1684
 1685                GlobalTheme::reload_theme(cx);
 1686                GlobalTheme::reload_icon_theme(cx);
 1687            }),
 1688            cx.on_release({
 1689                let weak_handle = weak_handle.clone();
 1690                move |this, cx| {
 1691                    this.app_state.workspace_store.update(cx, move |store, _| {
 1692                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1693                    })
 1694                }
 1695            }),
 1696        ];
 1697
 1698        cx.defer_in(window, move |this, window, cx| {
 1699            this.update_window_title(window, cx);
 1700            this.show_initial_notifications(cx);
 1701        });
 1702
 1703        let mut center = PaneGroup::new(center_pane.clone());
 1704        center.set_is_center(true);
 1705        center.mark_positions(cx);
 1706
 1707        Workspace {
 1708            weak_self: weak_handle.clone(),
 1709            zoomed: None,
 1710            zoomed_position: None,
 1711            previous_dock_drag_coordinates: None,
 1712            center,
 1713            panes: vec![center_pane.clone()],
 1714            panes_by_item: Default::default(),
 1715            active_pane: center_pane.clone(),
 1716            last_active_center_pane: Some(center_pane.downgrade()),
 1717            last_active_view_id: None,
 1718            status_bar,
 1719            modal_layer,
 1720            toast_layer,
 1721            titlebar_item: None,
 1722            active_worktree_override: None,
 1723            notifications: Notifications::default(),
 1724            suppressed_notifications: HashSet::default(),
 1725            left_dock,
 1726            bottom_dock,
 1727            right_dock,
 1728            _panels_task: None,
 1729            project: project.clone(),
 1730            follower_states: Default::default(),
 1731            last_leaders_by_pane: Default::default(),
 1732            dispatching_keystrokes: Default::default(),
 1733            window_edited: false,
 1734            last_window_title: None,
 1735            dirty_items: Default::default(),
 1736            active_call,
 1737            database_id: workspace_id,
 1738            app_state,
 1739            _observe_current_user,
 1740            _apply_leader_updates,
 1741            _schedule_serialize_workspace: None,
 1742            _serialize_workspace_task: None,
 1743            _schedule_serialize_ssh_paths: None,
 1744            leader_updates_tx,
 1745            _subscriptions: subscriptions,
 1746            pane_history_timestamp,
 1747            workspace_actions: Default::default(),
 1748            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1749            bounds: Default::default(),
 1750            centered_layout: false,
 1751            bounds_save_task_queued: None,
 1752            on_prompt_for_new_path: None,
 1753            on_prompt_for_open_path: None,
 1754            terminal_provider: None,
 1755            debugger_provider: None,
 1756            serializable_items_tx,
 1757            _items_serializer,
 1758            session_id: Some(session_id),
 1759
 1760            scheduled_tasks: Vec::new(),
 1761            last_open_dock_positions: Vec::new(),
 1762            removing: false,
 1763            sidebar_focus_handle: None,
 1764            multi_workspace,
 1765        }
 1766    }
 1767
 1768    pub fn new_local(
 1769        abs_paths: Vec<PathBuf>,
 1770        app_state: Arc<AppState>,
 1771        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1772        env: Option<HashMap<String, String>>,
 1773        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1774        activate: bool,
 1775        cx: &mut App,
 1776    ) -> Task<anyhow::Result<OpenResult>> {
 1777        let project_handle = Project::local(
 1778            app_state.client.clone(),
 1779            app_state.node_runtime.clone(),
 1780            app_state.user_store.clone(),
 1781            app_state.languages.clone(),
 1782            app_state.fs.clone(),
 1783            env,
 1784            Default::default(),
 1785            cx,
 1786        );
 1787
 1788        let db = WorkspaceDb::global(cx);
 1789        let kvp = db::kvp::KeyValueStore::global(cx);
 1790        cx.spawn(async move |cx| {
 1791            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1792            for path in abs_paths.into_iter() {
 1793                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1794                    paths_to_open.push(canonical)
 1795                } else {
 1796                    paths_to_open.push(path)
 1797                }
 1798            }
 1799
 1800            let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
 1801
 1802            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1803                paths_to_open = paths.ordered_paths().cloned().collect();
 1804                if !paths.is_lexicographically_ordered() {
 1805                    project_handle.update(cx, |project, cx| {
 1806                        project.set_worktrees_reordered(true, cx);
 1807                    });
 1808                }
 1809            }
 1810
 1811            // Get project paths for all of the abs_paths
 1812            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1813                Vec::with_capacity(paths_to_open.len());
 1814
 1815            for path in paths_to_open.into_iter() {
 1816                if let Some((_, project_entry)) = cx
 1817                    .update(|cx| {
 1818                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1819                    })
 1820                    .await
 1821                    .log_err()
 1822                {
 1823                    project_paths.push((path, Some(project_entry)));
 1824                } else {
 1825                    project_paths.push((path, None));
 1826                }
 1827            }
 1828
 1829            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1830                serialized_workspace.id
 1831            } else {
 1832                db.next_id().await.unwrap_or_else(|_| Default::default())
 1833            };
 1834
 1835            let toolchains = db.toolchains(workspace_id).await?;
 1836
 1837            for (toolchain, worktree_path, path) in toolchains {
 1838                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1839                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1840                    this.find_worktree(&worktree_path, cx)
 1841                        .and_then(|(worktree, rel_path)| {
 1842                            if rel_path.is_empty() {
 1843                                Some(worktree.read(cx).id())
 1844                            } else {
 1845                                None
 1846                            }
 1847                        })
 1848                }) else {
 1849                    // We did not find a worktree with a given path, but that's whatever.
 1850                    continue;
 1851                };
 1852                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1853                    continue;
 1854                }
 1855
 1856                project_handle
 1857                    .update(cx, |this, cx| {
 1858                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1859                    })
 1860                    .await;
 1861            }
 1862            if let Some(workspace) = serialized_workspace.as_ref() {
 1863                project_handle.update(cx, |this, cx| {
 1864                    for (scope, toolchains) in &workspace.user_toolchains {
 1865                        for toolchain in toolchains {
 1866                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1867                        }
 1868                    }
 1869                });
 1870            }
 1871
 1872            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1873                if let Some(window) = requesting_window {
 1874                    let centered_layout = serialized_workspace
 1875                        .as_ref()
 1876                        .map(|w| w.centered_layout)
 1877                        .unwrap_or(false);
 1878
 1879                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1880                        let workspace = cx.new(|cx| {
 1881                            let mut workspace = Workspace::new(
 1882                                Some(workspace_id),
 1883                                project_handle.clone(),
 1884                                app_state.clone(),
 1885                                window,
 1886                                cx,
 1887                            );
 1888
 1889                            workspace.centered_layout = centered_layout;
 1890
 1891                            // Call init callback to add items before window renders
 1892                            if let Some(init) = init {
 1893                                init(&mut workspace, window, cx);
 1894                            }
 1895
 1896                            workspace
 1897                        });
 1898                        if activate {
 1899                            multi_workspace.activate(workspace.clone(), cx);
 1900                        } else {
 1901                            multi_workspace.add_workspace(workspace.clone(), cx);
 1902                        }
 1903                        workspace
 1904                    })?;
 1905                    (window, workspace)
 1906                } else {
 1907                    let window_bounds_override = window_bounds_env_override();
 1908
 1909                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1910                        (Some(WindowBounds::Windowed(bounds)), None)
 1911                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1912                        && let Some(display) = workspace.display
 1913                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1914                    {
 1915                        // Reopening an existing workspace - restore its saved bounds
 1916                        (Some(bounds.0), Some(display))
 1917                    } else if let Some((display, bounds)) =
 1918                        persistence::read_default_window_bounds(&kvp)
 1919                    {
 1920                        // New or empty workspace - use the last known window bounds
 1921                        (Some(bounds), Some(display))
 1922                    } else {
 1923                        // New window - let GPUI's default_bounds() handle cascading
 1924                        (None, None)
 1925                    };
 1926
 1927                    // Use the serialized workspace to construct the new window
 1928                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1929                    options.window_bounds = window_bounds;
 1930                    let centered_layout = serialized_workspace
 1931                        .as_ref()
 1932                        .map(|w| w.centered_layout)
 1933                        .unwrap_or(false);
 1934                    let window = cx.open_window(options, {
 1935                        let app_state = app_state.clone();
 1936                        let project_handle = project_handle.clone();
 1937                        move |window, cx| {
 1938                            let workspace = cx.new(|cx| {
 1939                                let mut workspace = Workspace::new(
 1940                                    Some(workspace_id),
 1941                                    project_handle,
 1942                                    app_state,
 1943                                    window,
 1944                                    cx,
 1945                                );
 1946                                workspace.centered_layout = centered_layout;
 1947
 1948                                // Call init callback to add items before window renders
 1949                                if let Some(init) = init {
 1950                                    init(&mut workspace, window, cx);
 1951                                }
 1952
 1953                                workspace
 1954                            });
 1955                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 1956                        }
 1957                    })?;
 1958                    let workspace =
 1959                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 1960                            multi_workspace.workspace().clone()
 1961                        })?;
 1962                    (window, workspace)
 1963                };
 1964
 1965            notify_if_database_failed(window, cx);
 1966            // Check if this is an empty workspace (no paths to open)
 1967            // An empty workspace is one where project_paths is empty
 1968            let is_empty_workspace = project_paths.is_empty();
 1969            // Check if serialized workspace has paths before it's moved
 1970            let serialized_workspace_has_paths = serialized_workspace
 1971                .as_ref()
 1972                .map(|ws| !ws.paths.is_empty())
 1973                .unwrap_or(false);
 1974
 1975            let opened_items = window
 1976                .update(cx, |_, window, cx| {
 1977                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 1978                        open_items(serialized_workspace, project_paths, window, cx)
 1979                    })
 1980                })?
 1981                .await
 1982                .unwrap_or_default();
 1983
 1984            // Restore default dock state for empty workspaces
 1985            // Only restore if:
 1986            // 1. This is an empty workspace (no paths), AND
 1987            // 2. The serialized workspace either doesn't exist or has no paths
 1988            if is_empty_workspace && !serialized_workspace_has_paths {
 1989                if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
 1990                    window
 1991                        .update(cx, |_, window, cx| {
 1992                            workspace.update(cx, |workspace, cx| {
 1993                                for (dock, serialized_dock) in [
 1994                                    (&workspace.right_dock, &default_docks.right),
 1995                                    (&workspace.left_dock, &default_docks.left),
 1996                                    (&workspace.bottom_dock, &default_docks.bottom),
 1997                                ] {
 1998                                    dock.update(cx, |dock, cx| {
 1999                                        dock.serialized_dock = Some(serialized_dock.clone());
 2000                                        dock.restore_state(window, cx);
 2001                                    });
 2002                                }
 2003                                cx.notify();
 2004                            });
 2005                        })
 2006                        .log_err();
 2007                }
 2008            }
 2009
 2010            window
 2011                .update(cx, |_, _window, cx| {
 2012                    workspace.update(cx, |this: &mut Workspace, cx| {
 2013                        this.update_history(cx);
 2014                    });
 2015                })
 2016                .log_err();
 2017            Ok(OpenResult {
 2018                window,
 2019                workspace,
 2020                opened_items,
 2021            })
 2022        })
 2023    }
 2024
 2025    pub fn weak_handle(&self) -> WeakEntity<Self> {
 2026        self.weak_self.clone()
 2027    }
 2028
 2029    pub fn left_dock(&self) -> &Entity<Dock> {
 2030        &self.left_dock
 2031    }
 2032
 2033    pub fn bottom_dock(&self) -> &Entity<Dock> {
 2034        &self.bottom_dock
 2035    }
 2036
 2037    pub fn set_bottom_dock_layout(
 2038        &mut self,
 2039        layout: BottomDockLayout,
 2040        window: &mut Window,
 2041        cx: &mut Context<Self>,
 2042    ) {
 2043        let fs = self.project().read(cx).fs();
 2044        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 2045            content.workspace.bottom_dock_layout = Some(layout);
 2046        });
 2047
 2048        cx.notify();
 2049        self.serialize_workspace(window, cx);
 2050    }
 2051
 2052    pub fn right_dock(&self) -> &Entity<Dock> {
 2053        &self.right_dock
 2054    }
 2055
 2056    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 2057        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 2058    }
 2059
 2060    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 2061        let left_dock = self.left_dock.read(cx);
 2062        let left_visible = left_dock.is_open();
 2063        let left_active_panel = left_dock
 2064            .active_panel()
 2065            .map(|panel| panel.persistent_name().to_string());
 2066        // `zoomed_position` is kept in sync with individual panel zoom state
 2067        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2068        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2069
 2070        let right_dock = self.right_dock.read(cx);
 2071        let right_visible = right_dock.is_open();
 2072        let right_active_panel = right_dock
 2073            .active_panel()
 2074            .map(|panel| panel.persistent_name().to_string());
 2075        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2076
 2077        let bottom_dock = self.bottom_dock.read(cx);
 2078        let bottom_visible = bottom_dock.is_open();
 2079        let bottom_active_panel = bottom_dock
 2080            .active_panel()
 2081            .map(|panel| panel.persistent_name().to_string());
 2082        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2083
 2084        DockStructure {
 2085            left: DockData {
 2086                visible: left_visible,
 2087                active_panel: left_active_panel,
 2088                zoom: left_dock_zoom,
 2089            },
 2090            right: DockData {
 2091                visible: right_visible,
 2092                active_panel: right_active_panel,
 2093                zoom: right_dock_zoom,
 2094            },
 2095            bottom: DockData {
 2096                visible: bottom_visible,
 2097                active_panel: bottom_active_panel,
 2098                zoom: bottom_dock_zoom,
 2099            },
 2100        }
 2101    }
 2102
 2103    pub fn set_dock_structure(
 2104        &self,
 2105        docks: DockStructure,
 2106        window: &mut Window,
 2107        cx: &mut Context<Self>,
 2108    ) {
 2109        for (dock, data) in [
 2110            (&self.left_dock, docks.left),
 2111            (&self.bottom_dock, docks.bottom),
 2112            (&self.right_dock, docks.right),
 2113        ] {
 2114            dock.update(cx, |dock, cx| {
 2115                dock.serialized_dock = Some(data);
 2116                dock.restore_state(window, cx);
 2117            });
 2118        }
 2119    }
 2120
 2121    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2122        self.items(cx)
 2123            .filter_map(|item| {
 2124                let project_path = item.project_path(cx)?;
 2125                self.project.read(cx).absolute_path(&project_path, cx)
 2126            })
 2127            .collect()
 2128    }
 2129
 2130    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2131        match position {
 2132            DockPosition::Left => &self.left_dock,
 2133            DockPosition::Bottom => &self.bottom_dock,
 2134            DockPosition::Right => &self.right_dock,
 2135        }
 2136    }
 2137
 2138    pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
 2139        self.all_docks().into_iter().find_map(|dock| {
 2140            let dock = dock.read(cx);
 2141            dock.has_agent_panel(cx).then_some(dock.position())
 2142        })
 2143    }
 2144
 2145    pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
 2146        self.all_docks().into_iter().find_map(|dock| {
 2147            let dock = dock.read(cx);
 2148            let panel = dock.panel::<T>()?;
 2149            dock.stored_panel_size_state(&panel)
 2150        })
 2151    }
 2152
 2153    pub fn persisted_panel_size_state(
 2154        &self,
 2155        panel_key: &'static str,
 2156        cx: &App,
 2157    ) -> Option<dock::PanelSizeState> {
 2158        dock::Dock::load_persisted_size_state(self, panel_key, cx)
 2159    }
 2160
 2161    pub fn persist_panel_size_state(
 2162        &self,
 2163        panel_key: &str,
 2164        size_state: dock::PanelSizeState,
 2165        cx: &mut App,
 2166    ) {
 2167        let Some(workspace_id) = self
 2168            .database_id()
 2169            .map(|id| i64::from(id).to_string())
 2170            .or(self.session_id())
 2171        else {
 2172            return;
 2173        };
 2174
 2175        let kvp = db::kvp::KeyValueStore::global(cx);
 2176        let panel_key = panel_key.to_string();
 2177        cx.background_spawn(async move {
 2178            let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
 2179            scope
 2180                .write(
 2181                    format!("{workspace_id}:{panel_key}"),
 2182                    serde_json::to_string(&size_state)?,
 2183                )
 2184                .await
 2185        })
 2186        .detach_and_log_err(cx);
 2187    }
 2188
 2189    pub fn set_panel_size_state<T: Panel>(
 2190        &mut self,
 2191        size_state: dock::PanelSizeState,
 2192        window: &mut Window,
 2193        cx: &mut Context<Self>,
 2194    ) -> bool {
 2195        let Some(panel) = self.panel::<T>(cx) else {
 2196            return false;
 2197        };
 2198
 2199        let dock = self.dock_at_position(panel.position(window, cx));
 2200        let did_set = dock.update(cx, |dock, cx| {
 2201            dock.set_panel_size_state(&panel, size_state, cx)
 2202        });
 2203
 2204        if did_set {
 2205            self.persist_panel_size_state(T::panel_key(), size_state, cx);
 2206        }
 2207
 2208        did_set
 2209    }
 2210
 2211    fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
 2212        let panel = dock.active_panel()?;
 2213        let size_state = dock
 2214            .stored_panel_size_state(panel.as_ref())
 2215            .unwrap_or_default();
 2216        let position = dock.position();
 2217
 2218        if position.axis() == Axis::Horizontal
 2219            && panel.supports_flexible_size(window, cx)
 2220            && let Some(ratio) = size_state
 2221                .flexible_size_ratio
 2222                .or_else(|| self.default_flexible_dock_ratio(position))
 2223            && let Some(available_width) =
 2224                self.available_width_for_horizontal_dock(position, window, cx)
 2225        {
 2226            return Some((available_width * ratio.clamp(0.0, 1.0)).max(RESIZE_HANDLE_SIZE));
 2227        }
 2228
 2229        Some(
 2230            size_state
 2231                .size
 2232                .unwrap_or_else(|| panel.default_size(window, cx)),
 2233        )
 2234    }
 2235
 2236    pub fn flexible_dock_ratio_for_size(
 2237        &self,
 2238        position: DockPosition,
 2239        size: Pixels,
 2240        window: &Window,
 2241        cx: &App,
 2242    ) -> Option<f32> {
 2243        if position.axis() != Axis::Horizontal {
 2244            return None;
 2245        }
 2246
 2247        let available_width = self.available_width_for_horizontal_dock(position, window, cx)?;
 2248        let available_width = available_width.max(RESIZE_HANDLE_SIZE);
 2249        Some((size / available_width).clamp(0.0, 1.0))
 2250    }
 2251
 2252    fn available_width_for_horizontal_dock(
 2253        &self,
 2254        position: DockPosition,
 2255        window: &Window,
 2256        cx: &App,
 2257    ) -> Option<Pixels> {
 2258        let workspace_width = self.bounds.size.width;
 2259        if workspace_width <= Pixels::ZERO {
 2260            return None;
 2261        }
 2262
 2263        let opposite_position = match position {
 2264            DockPosition::Left => DockPosition::Right,
 2265            DockPosition::Right => DockPosition::Left,
 2266            DockPosition::Bottom => return None,
 2267        };
 2268
 2269        let opposite_width = self
 2270            .dock_at_position(opposite_position)
 2271            .read(cx)
 2272            .stored_active_panel_size(window, cx)
 2273            .unwrap_or(Pixels::ZERO);
 2274
 2275        Some((workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE))
 2276    }
 2277
 2278    pub fn default_flexible_dock_ratio(&self, position: DockPosition) -> Option<f32> {
 2279        if position.axis() != Axis::Horizontal {
 2280            return None;
 2281        }
 2282
 2283        let pane = self.last_active_center_pane.clone()?.upgrade()?;
 2284        let pane_fraction = self.center.width_fraction_for_pane(&pane).unwrap_or(1.0);
 2285        Some((pane_fraction / (1.0 + pane_fraction)).clamp(0.0, 1.0))
 2286    }
 2287
 2288    pub fn is_edited(&self) -> bool {
 2289        self.window_edited
 2290    }
 2291
 2292    pub fn add_panel<T: Panel>(
 2293        &mut self,
 2294        panel: Entity<T>,
 2295        window: &mut Window,
 2296        cx: &mut Context<Self>,
 2297    ) {
 2298        let focus_handle = panel.panel_focus_handle(cx);
 2299        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2300            .detach();
 2301
 2302        let dock_position = panel.position(window, cx);
 2303        let dock = self.dock_at_position(dock_position);
 2304        let any_panel = panel.to_any();
 2305        let persisted_size_state =
 2306            self.persisted_panel_size_state(T::panel_key(), cx)
 2307                .or_else(|| {
 2308                    load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
 2309                        let state = dock::PanelSizeState {
 2310                            size: Some(size),
 2311                            flexible_size_ratio: None,
 2312                        };
 2313                        self.persist_panel_size_state(T::panel_key(), state, cx);
 2314                        state
 2315                    })
 2316                });
 2317
 2318        dock.update(cx, |dock, cx| {
 2319            let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
 2320            if let Some(size_state) = persisted_size_state {
 2321                dock.set_panel_size_state(&panel, size_state, cx);
 2322            }
 2323            index
 2324        });
 2325
 2326        cx.emit(Event::PanelAdded(any_panel));
 2327    }
 2328
 2329    pub fn remove_panel<T: Panel>(
 2330        &mut self,
 2331        panel: &Entity<T>,
 2332        window: &mut Window,
 2333        cx: &mut Context<Self>,
 2334    ) {
 2335        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2336            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2337        }
 2338    }
 2339
 2340    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2341        &self.status_bar
 2342    }
 2343
 2344    pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
 2345        self.sidebar_focus_handle = handle;
 2346    }
 2347
 2348    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2349        StatusBarSettings::get_global(cx).show
 2350    }
 2351
 2352    pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
 2353        self.multi_workspace.as_ref()
 2354    }
 2355
 2356    pub fn set_multi_workspace(
 2357        &mut self,
 2358        multi_workspace: WeakEntity<MultiWorkspace>,
 2359        cx: &mut App,
 2360    ) {
 2361        self.status_bar.update(cx, |status_bar, cx| {
 2362            status_bar.set_multi_workspace(multi_workspace.clone(), cx);
 2363        });
 2364        self.multi_workspace = Some(multi_workspace);
 2365    }
 2366
 2367    pub fn app_state(&self) -> &Arc<AppState> {
 2368        &self.app_state
 2369    }
 2370
 2371    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2372        self._panels_task = Some(task);
 2373    }
 2374
 2375    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2376        self._panels_task.take()
 2377    }
 2378
 2379    pub fn user_store(&self) -> &Entity<UserStore> {
 2380        &self.app_state.user_store
 2381    }
 2382
 2383    pub fn project(&self) -> &Entity<Project> {
 2384        &self.project
 2385    }
 2386
 2387    pub fn path_style(&self, cx: &App) -> PathStyle {
 2388        self.project.read(cx).path_style(cx)
 2389    }
 2390
 2391    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2392        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2393
 2394        for pane_handle in &self.panes {
 2395            let pane = pane_handle.read(cx);
 2396
 2397            for entry in pane.activation_history() {
 2398                history.insert(
 2399                    entry.entity_id,
 2400                    history
 2401                        .get(&entry.entity_id)
 2402                        .cloned()
 2403                        .unwrap_or(0)
 2404                        .max(entry.timestamp),
 2405                );
 2406            }
 2407        }
 2408
 2409        history
 2410    }
 2411
 2412    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2413        let mut recent_item: Option<Entity<T>> = None;
 2414        let mut recent_timestamp = 0;
 2415        for pane_handle in &self.panes {
 2416            let pane = pane_handle.read(cx);
 2417            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2418                pane.items().map(|item| (item.item_id(), item)).collect();
 2419            for entry in pane.activation_history() {
 2420                if entry.timestamp > recent_timestamp
 2421                    && let Some(&item) = item_map.get(&entry.entity_id)
 2422                    && let Some(typed_item) = item.act_as::<T>(cx)
 2423                {
 2424                    recent_timestamp = entry.timestamp;
 2425                    recent_item = Some(typed_item);
 2426                }
 2427            }
 2428        }
 2429        recent_item
 2430    }
 2431
 2432    pub fn recent_navigation_history_iter(
 2433        &self,
 2434        cx: &App,
 2435    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2436        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2437        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2438
 2439        for pane in &self.panes {
 2440            let pane = pane.read(cx);
 2441
 2442            pane.nav_history()
 2443                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2444                    if let Some(fs_path) = &fs_path {
 2445                        abs_paths_opened
 2446                            .entry(fs_path.clone())
 2447                            .or_default()
 2448                            .insert(project_path.clone());
 2449                    }
 2450                    let timestamp = entry.timestamp;
 2451                    match history.entry(project_path) {
 2452                        hash_map::Entry::Occupied(mut entry) => {
 2453                            let (_, old_timestamp) = entry.get();
 2454                            if &timestamp > old_timestamp {
 2455                                entry.insert((fs_path, timestamp));
 2456                            }
 2457                        }
 2458                        hash_map::Entry::Vacant(entry) => {
 2459                            entry.insert((fs_path, timestamp));
 2460                        }
 2461                    }
 2462                });
 2463
 2464            if let Some(item) = pane.active_item()
 2465                && let Some(project_path) = item.project_path(cx)
 2466            {
 2467                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2468
 2469                if let Some(fs_path) = &fs_path {
 2470                    abs_paths_opened
 2471                        .entry(fs_path.clone())
 2472                        .or_default()
 2473                        .insert(project_path.clone());
 2474                }
 2475
 2476                history.insert(project_path, (fs_path, std::usize::MAX));
 2477            }
 2478        }
 2479
 2480        history
 2481            .into_iter()
 2482            .sorted_by_key(|(_, (_, order))| *order)
 2483            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2484            .rev()
 2485            .filter(move |(history_path, abs_path)| {
 2486                let latest_project_path_opened = abs_path
 2487                    .as_ref()
 2488                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2489                    .and_then(|project_paths| {
 2490                        project_paths
 2491                            .iter()
 2492                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2493                    });
 2494
 2495                latest_project_path_opened.is_none_or(|path| path == history_path)
 2496            })
 2497    }
 2498
 2499    pub fn recent_navigation_history(
 2500        &self,
 2501        limit: Option<usize>,
 2502        cx: &App,
 2503    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2504        self.recent_navigation_history_iter(cx)
 2505            .take(limit.unwrap_or(usize::MAX))
 2506            .collect()
 2507    }
 2508
 2509    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2510        for pane in &self.panes {
 2511            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2512        }
 2513    }
 2514
 2515    fn navigate_history(
 2516        &mut self,
 2517        pane: WeakEntity<Pane>,
 2518        mode: NavigationMode,
 2519        window: &mut Window,
 2520        cx: &mut Context<Workspace>,
 2521    ) -> Task<Result<()>> {
 2522        self.navigate_history_impl(
 2523            pane,
 2524            mode,
 2525            window,
 2526            &mut |history, cx| history.pop(mode, cx),
 2527            cx,
 2528        )
 2529    }
 2530
 2531    fn navigate_tag_history(
 2532        &mut self,
 2533        pane: WeakEntity<Pane>,
 2534        mode: TagNavigationMode,
 2535        window: &mut Window,
 2536        cx: &mut Context<Workspace>,
 2537    ) -> Task<Result<()>> {
 2538        self.navigate_history_impl(
 2539            pane,
 2540            NavigationMode::Normal,
 2541            window,
 2542            &mut |history, _cx| history.pop_tag(mode),
 2543            cx,
 2544        )
 2545    }
 2546
 2547    fn navigate_history_impl(
 2548        &mut self,
 2549        pane: WeakEntity<Pane>,
 2550        mode: NavigationMode,
 2551        window: &mut Window,
 2552        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2553        cx: &mut Context<Workspace>,
 2554    ) -> Task<Result<()>> {
 2555        let to_load = if let Some(pane) = pane.upgrade() {
 2556            pane.update(cx, |pane, cx| {
 2557                window.focus(&pane.focus_handle(cx), cx);
 2558                loop {
 2559                    // Retrieve the weak item handle from the history.
 2560                    let entry = cb(pane.nav_history_mut(), cx)?;
 2561
 2562                    // If the item is still present in this pane, then activate it.
 2563                    if let Some(index) = entry
 2564                        .item
 2565                        .upgrade()
 2566                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2567                    {
 2568                        let prev_active_item_index = pane.active_item_index();
 2569                        pane.nav_history_mut().set_mode(mode);
 2570                        pane.activate_item(index, true, true, window, cx);
 2571                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2572
 2573                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2574                        if let Some(data) = entry.data {
 2575                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2576                        }
 2577
 2578                        if navigated {
 2579                            break None;
 2580                        }
 2581                    } else {
 2582                        // If the item is no longer present in this pane, then retrieve its
 2583                        // path info in order to reopen it.
 2584                        break pane
 2585                            .nav_history()
 2586                            .path_for_item(entry.item.id())
 2587                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2588                    }
 2589                }
 2590            })
 2591        } else {
 2592            None
 2593        };
 2594
 2595        if let Some((project_path, abs_path, entry)) = to_load {
 2596            // If the item was no longer present, then load it again from its previous path, first try the local path
 2597            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2598
 2599            cx.spawn_in(window, async move  |workspace, cx| {
 2600                let open_by_project_path = open_by_project_path.await;
 2601                let mut navigated = false;
 2602                match open_by_project_path
 2603                    .with_context(|| format!("Navigating to {project_path:?}"))
 2604                {
 2605                    Ok((project_entry_id, build_item)) => {
 2606                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2607                            pane.nav_history_mut().set_mode(mode);
 2608                            pane.active_item().map(|p| p.item_id())
 2609                        })?;
 2610
 2611                        pane.update_in(cx, |pane, window, cx| {
 2612                            let item = pane.open_item(
 2613                                project_entry_id,
 2614                                project_path,
 2615                                true,
 2616                                entry.is_preview,
 2617                                true,
 2618                                None,
 2619                                window, cx,
 2620                                build_item,
 2621                            );
 2622                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2623                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2624                            if let Some(data) = entry.data {
 2625                                navigated |= item.navigate(data, window, cx);
 2626                            }
 2627                        })?;
 2628                    }
 2629                    Err(open_by_project_path_e) => {
 2630                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2631                        // and its worktree is now dropped
 2632                        if let Some(abs_path) = abs_path {
 2633                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2634                                pane.nav_history_mut().set_mode(mode);
 2635                                pane.active_item().map(|p| p.item_id())
 2636                            })?;
 2637                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2638                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2639                            })?;
 2640                            match open_by_abs_path
 2641                                .await
 2642                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2643                            {
 2644                                Ok(item) => {
 2645                                    pane.update_in(cx, |pane, window, cx| {
 2646                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2647                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2648                                        if let Some(data) = entry.data {
 2649                                            navigated |= item.navigate(data, window, cx);
 2650                                        }
 2651                                    })?;
 2652                                }
 2653                                Err(open_by_abs_path_e) => {
 2654                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2655                                }
 2656                            }
 2657                        }
 2658                    }
 2659                }
 2660
 2661                if !navigated {
 2662                    workspace
 2663                        .update_in(cx, |workspace, window, cx| {
 2664                            Self::navigate_history(workspace, pane, mode, window, cx)
 2665                        })?
 2666                        .await?;
 2667                }
 2668
 2669                Ok(())
 2670            })
 2671        } else {
 2672            Task::ready(Ok(()))
 2673        }
 2674    }
 2675
 2676    pub fn go_back(
 2677        &mut self,
 2678        pane: WeakEntity<Pane>,
 2679        window: &mut Window,
 2680        cx: &mut Context<Workspace>,
 2681    ) -> Task<Result<()>> {
 2682        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2683    }
 2684
 2685    pub fn go_forward(
 2686        &mut self,
 2687        pane: WeakEntity<Pane>,
 2688        window: &mut Window,
 2689        cx: &mut Context<Workspace>,
 2690    ) -> Task<Result<()>> {
 2691        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2692    }
 2693
 2694    pub fn reopen_closed_item(
 2695        &mut self,
 2696        window: &mut Window,
 2697        cx: &mut Context<Workspace>,
 2698    ) -> Task<Result<()>> {
 2699        self.navigate_history(
 2700            self.active_pane().downgrade(),
 2701            NavigationMode::ReopeningClosedItem,
 2702            window,
 2703            cx,
 2704        )
 2705    }
 2706
 2707    pub fn client(&self) -> &Arc<Client> {
 2708        &self.app_state.client
 2709    }
 2710
 2711    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2712        self.titlebar_item = Some(item);
 2713        cx.notify();
 2714    }
 2715
 2716    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2717        self.on_prompt_for_new_path = Some(prompt)
 2718    }
 2719
 2720    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2721        self.on_prompt_for_open_path = Some(prompt)
 2722    }
 2723
 2724    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2725        self.terminal_provider = Some(Box::new(provider));
 2726    }
 2727
 2728    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2729        self.debugger_provider = Some(Arc::new(provider));
 2730    }
 2731
 2732    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2733        self.debugger_provider.clone()
 2734    }
 2735
 2736    pub fn prompt_for_open_path(
 2737        &mut self,
 2738        path_prompt_options: PathPromptOptions,
 2739        lister: DirectoryLister,
 2740        window: &mut Window,
 2741        cx: &mut Context<Self>,
 2742    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2743        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2744            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2745            let rx = prompt(self, lister, window, cx);
 2746            self.on_prompt_for_open_path = Some(prompt);
 2747            rx
 2748        } else {
 2749            let (tx, rx) = oneshot::channel();
 2750            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2751
 2752            cx.spawn_in(window, async move |workspace, cx| {
 2753                let Ok(result) = abs_path.await else {
 2754                    return Ok(());
 2755                };
 2756
 2757                match result {
 2758                    Ok(result) => {
 2759                        tx.send(result).ok();
 2760                    }
 2761                    Err(err) => {
 2762                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2763                            workspace.show_portal_error(err.to_string(), cx);
 2764                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2765                            let rx = prompt(workspace, lister, window, cx);
 2766                            workspace.on_prompt_for_open_path = Some(prompt);
 2767                            rx
 2768                        })?;
 2769                        if let Ok(path) = rx.await {
 2770                            tx.send(path).ok();
 2771                        }
 2772                    }
 2773                };
 2774                anyhow::Ok(())
 2775            })
 2776            .detach();
 2777
 2778            rx
 2779        }
 2780    }
 2781
 2782    pub fn prompt_for_new_path(
 2783        &mut self,
 2784        lister: DirectoryLister,
 2785        suggested_name: Option<String>,
 2786        window: &mut Window,
 2787        cx: &mut Context<Self>,
 2788    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2789        if self.project.read(cx).is_via_collab()
 2790            || self.project.read(cx).is_via_remote_server()
 2791            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2792        {
 2793            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2794            let rx = prompt(self, lister, suggested_name, window, cx);
 2795            self.on_prompt_for_new_path = Some(prompt);
 2796            return rx;
 2797        }
 2798
 2799        let (tx, rx) = oneshot::channel();
 2800        cx.spawn_in(window, async move |workspace, cx| {
 2801            let abs_path = workspace.update(cx, |workspace, cx| {
 2802                let relative_to = workspace
 2803                    .most_recent_active_path(cx)
 2804                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2805                    .or_else(|| {
 2806                        let project = workspace.project.read(cx);
 2807                        project.visible_worktrees(cx).find_map(|worktree| {
 2808                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2809                        })
 2810                    })
 2811                    .or_else(std::env::home_dir)
 2812                    .unwrap_or_else(|| PathBuf::from(""));
 2813                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2814            })?;
 2815            let abs_path = match abs_path.await? {
 2816                Ok(path) => path,
 2817                Err(err) => {
 2818                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2819                        workspace.show_portal_error(err.to_string(), cx);
 2820
 2821                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2822                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2823                        workspace.on_prompt_for_new_path = Some(prompt);
 2824                        rx
 2825                    })?;
 2826                    if let Ok(path) = rx.await {
 2827                        tx.send(path).ok();
 2828                    }
 2829                    return anyhow::Ok(());
 2830                }
 2831            };
 2832
 2833            tx.send(abs_path.map(|path| vec![path])).ok();
 2834            anyhow::Ok(())
 2835        })
 2836        .detach();
 2837
 2838        rx
 2839    }
 2840
 2841    pub fn titlebar_item(&self) -> Option<AnyView> {
 2842        self.titlebar_item.clone()
 2843    }
 2844
 2845    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2846    /// When set, git-related operations should use this worktree instead of deriving
 2847    /// the active worktree from the focused file.
 2848    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2849        self.active_worktree_override
 2850    }
 2851
 2852    pub fn set_active_worktree_override(
 2853        &mut self,
 2854        worktree_id: Option<WorktreeId>,
 2855        cx: &mut Context<Self>,
 2856    ) {
 2857        self.active_worktree_override = worktree_id;
 2858        cx.notify();
 2859    }
 2860
 2861    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2862        self.active_worktree_override = None;
 2863        cx.notify();
 2864    }
 2865
 2866    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2867    ///
 2868    /// If the given workspace has a local project, then it will be passed
 2869    /// to the callback. Otherwise, a new empty window will be created.
 2870    pub fn with_local_workspace<T, F>(
 2871        &mut self,
 2872        window: &mut Window,
 2873        cx: &mut Context<Self>,
 2874        callback: F,
 2875    ) -> Task<Result<T>>
 2876    where
 2877        T: 'static,
 2878        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2879    {
 2880        if self.project.read(cx).is_local() {
 2881            Task::ready(Ok(callback(self, window, cx)))
 2882        } else {
 2883            let env = self.project.read(cx).cli_environment(cx);
 2884            let task = Self::new_local(
 2885                Vec::new(),
 2886                self.app_state.clone(),
 2887                None,
 2888                env,
 2889                None,
 2890                true,
 2891                cx,
 2892            );
 2893            cx.spawn_in(window, async move |_vh, cx| {
 2894                let OpenResult {
 2895                    window: multi_workspace_window,
 2896                    ..
 2897                } = task.await?;
 2898                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2899                    let workspace = multi_workspace.workspace().clone();
 2900                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2901                })
 2902            })
 2903        }
 2904    }
 2905
 2906    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2907    ///
 2908    /// If the given workspace has a local project, then it will be passed
 2909    /// to the callback. Otherwise, a new empty window will be created.
 2910    pub fn with_local_or_wsl_workspace<T, F>(
 2911        &mut self,
 2912        window: &mut Window,
 2913        cx: &mut Context<Self>,
 2914        callback: F,
 2915    ) -> Task<Result<T>>
 2916    where
 2917        T: 'static,
 2918        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2919    {
 2920        let project = self.project.read(cx);
 2921        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 2922            Task::ready(Ok(callback(self, window, cx)))
 2923        } else {
 2924            let env = self.project.read(cx).cli_environment(cx);
 2925            let task = Self::new_local(
 2926                Vec::new(),
 2927                self.app_state.clone(),
 2928                None,
 2929                env,
 2930                None,
 2931                true,
 2932                cx,
 2933            );
 2934            cx.spawn_in(window, async move |_vh, cx| {
 2935                let OpenResult {
 2936                    window: multi_workspace_window,
 2937                    ..
 2938                } = task.await?;
 2939                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2940                    let workspace = multi_workspace.workspace().clone();
 2941                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2942                })
 2943            })
 2944        }
 2945    }
 2946
 2947    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2948        self.project.read(cx).worktrees(cx)
 2949    }
 2950
 2951    pub fn visible_worktrees<'a>(
 2952        &self,
 2953        cx: &'a App,
 2954    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2955        self.project.read(cx).visible_worktrees(cx)
 2956    }
 2957
 2958    #[cfg(any(test, feature = "test-support"))]
 2959    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2960        let futures = self
 2961            .worktrees(cx)
 2962            .filter_map(|worktree| worktree.read(cx).as_local())
 2963            .map(|worktree| worktree.scan_complete())
 2964            .collect::<Vec<_>>();
 2965        async move {
 2966            for future in futures {
 2967                future.await;
 2968            }
 2969        }
 2970    }
 2971
 2972    pub fn close_global(cx: &mut App) {
 2973        cx.defer(|cx| {
 2974            cx.windows().iter().find(|window| {
 2975                window
 2976                    .update(cx, |_, window, _| {
 2977                        if window.is_window_active() {
 2978                            //This can only get called when the window's project connection has been lost
 2979                            //so we don't need to prompt the user for anything and instead just close the window
 2980                            window.remove_window();
 2981                            true
 2982                        } else {
 2983                            false
 2984                        }
 2985                    })
 2986                    .unwrap_or(false)
 2987            });
 2988        });
 2989    }
 2990
 2991    pub fn move_focused_panel_to_next_position(
 2992        &mut self,
 2993        _: &MoveFocusedPanelToNextPosition,
 2994        window: &mut Window,
 2995        cx: &mut Context<Self>,
 2996    ) {
 2997        let docks = self.all_docks();
 2998        let active_dock = docks
 2999            .into_iter()
 3000            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 3001
 3002        if let Some(dock) = active_dock {
 3003            dock.update(cx, |dock, cx| {
 3004                let active_panel = dock
 3005                    .active_panel()
 3006                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 3007
 3008                if let Some(panel) = active_panel {
 3009                    panel.move_to_next_position(window, cx);
 3010                }
 3011            })
 3012        }
 3013    }
 3014
 3015    pub fn prepare_to_close(
 3016        &mut self,
 3017        close_intent: CloseIntent,
 3018        window: &mut Window,
 3019        cx: &mut Context<Self>,
 3020    ) -> Task<Result<bool>> {
 3021        let active_call = self.active_global_call();
 3022
 3023        cx.spawn_in(window, async move |this, cx| {
 3024            this.update(cx, |this, _| {
 3025                if close_intent == CloseIntent::CloseWindow {
 3026                    this.removing = true;
 3027                }
 3028            })?;
 3029
 3030            let workspace_count = cx.update(|_window, cx| {
 3031                cx.windows()
 3032                    .iter()
 3033                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 3034                    .count()
 3035            })?;
 3036
 3037            #[cfg(target_os = "macos")]
 3038            let save_last_workspace = false;
 3039
 3040            // On Linux and Windows, closing the last window should restore the last workspace.
 3041            #[cfg(not(target_os = "macos"))]
 3042            let save_last_workspace = {
 3043                let remaining_workspaces = cx.update(|_window, cx| {
 3044                    cx.windows()
 3045                        .iter()
 3046                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 3047                        .filter_map(|multi_workspace| {
 3048                            multi_workspace
 3049                                .update(cx, |multi_workspace, _, cx| {
 3050                                    multi_workspace.workspace().read(cx).removing
 3051                                })
 3052                                .ok()
 3053                        })
 3054                        .filter(|removing| !removing)
 3055                        .count()
 3056                })?;
 3057
 3058                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 3059            };
 3060
 3061            if let Some(active_call) = active_call
 3062                && workspace_count == 1
 3063                && cx
 3064                    .update(|_window, cx| active_call.0.is_in_room(cx))
 3065                    .unwrap_or(false)
 3066            {
 3067                if close_intent == CloseIntent::CloseWindow {
 3068                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3069                    let answer = cx.update(|window, cx| {
 3070                        window.prompt(
 3071                            PromptLevel::Warning,
 3072                            "Do you want to leave the current call?",
 3073                            None,
 3074                            &["Close window and hang up", "Cancel"],
 3075                            cx,
 3076                        )
 3077                    })?;
 3078
 3079                    if answer.await.log_err() == Some(1) {
 3080                        return anyhow::Ok(false);
 3081                    } else {
 3082                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 3083                            task.await.log_err();
 3084                        }
 3085                    }
 3086                }
 3087                if close_intent == CloseIntent::ReplaceWindow {
 3088                    _ = cx.update(|_window, cx| {
 3089                        let multi_workspace = cx
 3090                            .windows()
 3091                            .iter()
 3092                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 3093                            .next()
 3094                            .unwrap();
 3095                        let project = multi_workspace
 3096                            .read(cx)?
 3097                            .workspace()
 3098                            .read(cx)
 3099                            .project
 3100                            .clone();
 3101                        if project.read(cx).is_shared() {
 3102                            active_call.0.unshare_project(project, cx)?;
 3103                        }
 3104                        Ok::<_, anyhow::Error>(())
 3105                    });
 3106                }
 3107            }
 3108
 3109            let save_result = this
 3110                .update_in(cx, |this, window, cx| {
 3111                    this.save_all_internal(SaveIntent::Close, window, cx)
 3112                })?
 3113                .await;
 3114
 3115            // If we're not quitting, but closing, we remove the workspace from
 3116            // the current session.
 3117            if close_intent != CloseIntent::Quit
 3118                && !save_last_workspace
 3119                && save_result.as_ref().is_ok_and(|&res| res)
 3120            {
 3121                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 3122                    .await;
 3123            }
 3124
 3125            save_result
 3126        })
 3127    }
 3128
 3129    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 3130        self.save_all_internal(
 3131            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 3132            window,
 3133            cx,
 3134        )
 3135        .detach_and_log_err(cx);
 3136    }
 3137
 3138    fn send_keystrokes(
 3139        &mut self,
 3140        action: &SendKeystrokes,
 3141        window: &mut Window,
 3142        cx: &mut Context<Self>,
 3143    ) {
 3144        let keystrokes: Vec<Keystroke> = action
 3145            .0
 3146            .split(' ')
 3147            .flat_map(|k| Keystroke::parse(k).log_err())
 3148            .map(|k| {
 3149                cx.keyboard_mapper()
 3150                    .map_key_equivalent(k, false)
 3151                    .inner()
 3152                    .clone()
 3153            })
 3154            .collect();
 3155        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 3156    }
 3157
 3158    pub fn send_keystrokes_impl(
 3159        &mut self,
 3160        keystrokes: Vec<Keystroke>,
 3161        window: &mut Window,
 3162        cx: &mut Context<Self>,
 3163    ) -> Shared<Task<()>> {
 3164        let mut state = self.dispatching_keystrokes.borrow_mut();
 3165        if !state.dispatched.insert(keystrokes.clone()) {
 3166            cx.propagate();
 3167            return state.task.clone().unwrap();
 3168        }
 3169
 3170        state.queue.extend(keystrokes);
 3171
 3172        let keystrokes = self.dispatching_keystrokes.clone();
 3173        if state.task.is_none() {
 3174            state.task = Some(
 3175                window
 3176                    .spawn(cx, async move |cx| {
 3177                        // limit to 100 keystrokes to avoid infinite recursion.
 3178                        for _ in 0..100 {
 3179                            let keystroke = {
 3180                                let mut state = keystrokes.borrow_mut();
 3181                                let Some(keystroke) = state.queue.pop_front() else {
 3182                                    state.dispatched.clear();
 3183                                    state.task.take();
 3184                                    return;
 3185                                };
 3186                                keystroke
 3187                            };
 3188                            cx.update(|window, cx| {
 3189                                let focused = window.focused(cx);
 3190                                window.dispatch_keystroke(keystroke.clone(), cx);
 3191                                if window.focused(cx) != focused {
 3192                                    // dispatch_keystroke may cause the focus to change.
 3193                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3194                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 3195                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 3196                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3197                                    // )
 3198                                    window.draw(cx).clear();
 3199                                }
 3200                            })
 3201                            .ok();
 3202
 3203                            // Yield between synthetic keystrokes so deferred focus and
 3204                            // other effects can settle before dispatching the next key.
 3205                            yield_now().await;
 3206                        }
 3207
 3208                        *keystrokes.borrow_mut() = Default::default();
 3209                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3210                    })
 3211                    .shared(),
 3212            );
 3213        }
 3214        state.task.clone().unwrap()
 3215    }
 3216
 3217    fn save_all_internal(
 3218        &mut self,
 3219        mut save_intent: SaveIntent,
 3220        window: &mut Window,
 3221        cx: &mut Context<Self>,
 3222    ) -> Task<Result<bool>> {
 3223        if self.project.read(cx).is_disconnected(cx) {
 3224            return Task::ready(Ok(true));
 3225        }
 3226        let dirty_items = self
 3227            .panes
 3228            .iter()
 3229            .flat_map(|pane| {
 3230                pane.read(cx).items().filter_map(|item| {
 3231                    if item.is_dirty(cx) {
 3232                        item.tab_content_text(0, cx);
 3233                        Some((pane.downgrade(), item.boxed_clone()))
 3234                    } else {
 3235                        None
 3236                    }
 3237                })
 3238            })
 3239            .collect::<Vec<_>>();
 3240
 3241        let project = self.project.clone();
 3242        cx.spawn_in(window, async move |workspace, cx| {
 3243            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3244                let (serialize_tasks, remaining_dirty_items) =
 3245                    workspace.update_in(cx, |workspace, window, cx| {
 3246                        let mut remaining_dirty_items = Vec::new();
 3247                        let mut serialize_tasks = Vec::new();
 3248                        for (pane, item) in dirty_items {
 3249                            if let Some(task) = item
 3250                                .to_serializable_item_handle(cx)
 3251                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3252                            {
 3253                                serialize_tasks.push(task);
 3254                            } else {
 3255                                remaining_dirty_items.push((pane, item));
 3256                            }
 3257                        }
 3258                        (serialize_tasks, remaining_dirty_items)
 3259                    })?;
 3260
 3261                futures::future::try_join_all(serialize_tasks).await?;
 3262
 3263                if !remaining_dirty_items.is_empty() {
 3264                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3265                }
 3266
 3267                if remaining_dirty_items.len() > 1 {
 3268                    let answer = workspace.update_in(cx, |_, window, cx| {
 3269                        let detail = Pane::file_names_for_prompt(
 3270                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3271                            cx,
 3272                        );
 3273                        window.prompt(
 3274                            PromptLevel::Warning,
 3275                            "Do you want to save all changes in the following files?",
 3276                            Some(&detail),
 3277                            &["Save all", "Discard all", "Cancel"],
 3278                            cx,
 3279                        )
 3280                    })?;
 3281                    match answer.await.log_err() {
 3282                        Some(0) => save_intent = SaveIntent::SaveAll,
 3283                        Some(1) => save_intent = SaveIntent::Skip,
 3284                        Some(2) => return Ok(false),
 3285                        _ => {}
 3286                    }
 3287                }
 3288
 3289                remaining_dirty_items
 3290            } else {
 3291                dirty_items
 3292            };
 3293
 3294            for (pane, item) in dirty_items {
 3295                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3296                    (
 3297                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3298                        item.project_entry_ids(cx),
 3299                    )
 3300                })?;
 3301                if (singleton || !project_entry_ids.is_empty())
 3302                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3303                {
 3304                    return Ok(false);
 3305                }
 3306            }
 3307            Ok(true)
 3308        })
 3309    }
 3310
 3311    pub fn open_workspace_for_paths(
 3312        &mut self,
 3313        replace_current_window: bool,
 3314        paths: Vec<PathBuf>,
 3315        window: &mut Window,
 3316        cx: &mut Context<Self>,
 3317    ) -> Task<Result<Entity<Workspace>>> {
 3318        let window_handle = window.window_handle().downcast::<MultiWorkspace>();
 3319        let is_remote = self.project.read(cx).is_via_collab();
 3320        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3321        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3322
 3323        let window_to_replace = if replace_current_window {
 3324            window_handle
 3325        } else if is_remote || has_worktree || has_dirty_items {
 3326            None
 3327        } else {
 3328            window_handle
 3329        };
 3330        let app_state = self.app_state.clone();
 3331
 3332        cx.spawn(async move |_, cx| {
 3333            let OpenResult { workspace, .. } = cx
 3334                .update(|cx| {
 3335                    open_paths(
 3336                        &paths,
 3337                        app_state,
 3338                        OpenOptions {
 3339                            replace_window: window_to_replace,
 3340                            ..Default::default()
 3341                        },
 3342                        cx,
 3343                    )
 3344                })
 3345                .await?;
 3346            Ok(workspace)
 3347        })
 3348    }
 3349
 3350    #[allow(clippy::type_complexity)]
 3351    pub fn open_paths(
 3352        &mut self,
 3353        mut abs_paths: Vec<PathBuf>,
 3354        options: OpenOptions,
 3355        pane: Option<WeakEntity<Pane>>,
 3356        window: &mut Window,
 3357        cx: &mut Context<Self>,
 3358    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3359        let fs = self.app_state.fs.clone();
 3360
 3361        let caller_ordered_abs_paths = abs_paths.clone();
 3362
 3363        // Sort the paths to ensure we add worktrees for parents before their children.
 3364        abs_paths.sort_unstable();
 3365        cx.spawn_in(window, async move |this, cx| {
 3366            let mut tasks = Vec::with_capacity(abs_paths.len());
 3367
 3368            for abs_path in &abs_paths {
 3369                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3370                    OpenVisible::All => Some(true),
 3371                    OpenVisible::None => Some(false),
 3372                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3373                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3374                        Some(None) => Some(true),
 3375                        None => None,
 3376                    },
 3377                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3378                        Some(Some(metadata)) => Some(metadata.is_dir),
 3379                        Some(None) => Some(false),
 3380                        None => None,
 3381                    },
 3382                };
 3383                let project_path = match visible {
 3384                    Some(visible) => match this
 3385                        .update(cx, |this, cx| {
 3386                            Workspace::project_path_for_path(
 3387                                this.project.clone(),
 3388                                abs_path,
 3389                                visible,
 3390                                cx,
 3391                            )
 3392                        })
 3393                        .log_err()
 3394                    {
 3395                        Some(project_path) => project_path.await.log_err(),
 3396                        None => None,
 3397                    },
 3398                    None => None,
 3399                };
 3400
 3401                let this = this.clone();
 3402                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3403                let fs = fs.clone();
 3404                let pane = pane.clone();
 3405                let task = cx.spawn(async move |cx| {
 3406                    let (_worktree, project_path) = project_path?;
 3407                    if fs.is_dir(&abs_path).await {
 3408                        // Opening a directory should not race to update the active entry.
 3409                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3410                        None
 3411                    } else {
 3412                        Some(
 3413                            this.update_in(cx, |this, window, cx| {
 3414                                this.open_path(
 3415                                    project_path,
 3416                                    pane,
 3417                                    options.focus.unwrap_or(true),
 3418                                    window,
 3419                                    cx,
 3420                                )
 3421                            })
 3422                            .ok()?
 3423                            .await,
 3424                        )
 3425                    }
 3426                });
 3427                tasks.push(task);
 3428            }
 3429
 3430            let results = futures::future::join_all(tasks).await;
 3431
 3432            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3433            let mut winner: Option<(PathBuf, bool)> = None;
 3434            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3435                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3436                    if !metadata.is_dir {
 3437                        winner = Some((abs_path, false));
 3438                        break;
 3439                    }
 3440                    if winner.is_none() {
 3441                        winner = Some((abs_path, true));
 3442                    }
 3443                } else if winner.is_none() {
 3444                    winner = Some((abs_path, false));
 3445                }
 3446            }
 3447
 3448            // Compute the winner entry id on the foreground thread and emit once, after all
 3449            // paths finish opening. This avoids races between concurrently-opening paths
 3450            // (directories in particular) and makes the resulting project panel selection
 3451            // deterministic.
 3452            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3453                'emit_winner: {
 3454                    let winner_abs_path: Arc<Path> =
 3455                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3456
 3457                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3458                        OpenVisible::All => true,
 3459                        OpenVisible::None => false,
 3460                        OpenVisible::OnlyFiles => !winner_is_dir,
 3461                        OpenVisible::OnlyDirectories => winner_is_dir,
 3462                    };
 3463
 3464                    let Some(worktree_task) = this
 3465                        .update(cx, |workspace, cx| {
 3466                            workspace.project.update(cx, |project, cx| {
 3467                                project.find_or_create_worktree(
 3468                                    winner_abs_path.as_ref(),
 3469                                    visible,
 3470                                    cx,
 3471                                )
 3472                            })
 3473                        })
 3474                        .ok()
 3475                    else {
 3476                        break 'emit_winner;
 3477                    };
 3478
 3479                    let Ok((worktree, _)) = worktree_task.await else {
 3480                        break 'emit_winner;
 3481                    };
 3482
 3483                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3484                        let worktree = worktree.read(cx);
 3485                        let worktree_abs_path = worktree.abs_path();
 3486                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3487                            worktree.root_entry()
 3488                        } else {
 3489                            winner_abs_path
 3490                                .strip_prefix(worktree_abs_path.as_ref())
 3491                                .ok()
 3492                                .and_then(|relative_path| {
 3493                                    let relative_path =
 3494                                        RelPath::new(relative_path, PathStyle::local())
 3495                                            .log_err()?;
 3496                                    worktree.entry_for_path(&relative_path)
 3497                                })
 3498                        }?;
 3499                        Some(entry.id)
 3500                    }) else {
 3501                        break 'emit_winner;
 3502                    };
 3503
 3504                    this.update(cx, |workspace, cx| {
 3505                        workspace.project.update(cx, |_, cx| {
 3506                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3507                        });
 3508                    })
 3509                    .ok();
 3510                }
 3511            }
 3512
 3513            results
 3514        })
 3515    }
 3516
 3517    pub fn open_resolved_path(
 3518        &mut self,
 3519        path: ResolvedPath,
 3520        window: &mut Window,
 3521        cx: &mut Context<Self>,
 3522    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3523        match path {
 3524            ResolvedPath::ProjectPath { project_path, .. } => {
 3525                self.open_path(project_path, None, true, window, cx)
 3526            }
 3527            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3528                PathBuf::from(path),
 3529                OpenOptions {
 3530                    visible: Some(OpenVisible::None),
 3531                    ..Default::default()
 3532                },
 3533                window,
 3534                cx,
 3535            ),
 3536        }
 3537    }
 3538
 3539    pub fn absolute_path_of_worktree(
 3540        &self,
 3541        worktree_id: WorktreeId,
 3542        cx: &mut Context<Self>,
 3543    ) -> Option<PathBuf> {
 3544        self.project
 3545            .read(cx)
 3546            .worktree_for_id(worktree_id, cx)
 3547            // TODO: use `abs_path` or `root_dir`
 3548            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3549    }
 3550
 3551    pub fn add_folder_to_project(
 3552        &mut self,
 3553        _: &AddFolderToProject,
 3554        window: &mut Window,
 3555        cx: &mut Context<Self>,
 3556    ) {
 3557        let project = self.project.read(cx);
 3558        if project.is_via_collab() {
 3559            self.show_error(
 3560                &anyhow!("You cannot add folders to someone else's project"),
 3561                cx,
 3562            );
 3563            return;
 3564        }
 3565        let paths = self.prompt_for_open_path(
 3566            PathPromptOptions {
 3567                files: false,
 3568                directories: true,
 3569                multiple: true,
 3570                prompt: None,
 3571            },
 3572            DirectoryLister::Project(self.project.clone()),
 3573            window,
 3574            cx,
 3575        );
 3576        cx.spawn_in(window, async move |this, cx| {
 3577            if let Some(paths) = paths.await.log_err().flatten() {
 3578                let results = this
 3579                    .update_in(cx, |this, window, cx| {
 3580                        this.open_paths(
 3581                            paths,
 3582                            OpenOptions {
 3583                                visible: Some(OpenVisible::All),
 3584                                ..Default::default()
 3585                            },
 3586                            None,
 3587                            window,
 3588                            cx,
 3589                        )
 3590                    })?
 3591                    .await;
 3592                for result in results.into_iter().flatten() {
 3593                    result.log_err();
 3594                }
 3595            }
 3596            anyhow::Ok(())
 3597        })
 3598        .detach_and_log_err(cx);
 3599    }
 3600
 3601    pub fn project_path_for_path(
 3602        project: Entity<Project>,
 3603        abs_path: &Path,
 3604        visible: bool,
 3605        cx: &mut App,
 3606    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3607        let entry = project.update(cx, |project, cx| {
 3608            project.find_or_create_worktree(abs_path, visible, cx)
 3609        });
 3610        cx.spawn(async move |cx| {
 3611            let (worktree, path) = entry.await?;
 3612            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3613            Ok((worktree, ProjectPath { worktree_id, path }))
 3614        })
 3615    }
 3616
 3617    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3618        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3619    }
 3620
 3621    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3622        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3623    }
 3624
 3625    pub fn items_of_type<'a, T: Item>(
 3626        &'a self,
 3627        cx: &'a App,
 3628    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3629        self.panes
 3630            .iter()
 3631            .flat_map(|pane| pane.read(cx).items_of_type())
 3632    }
 3633
 3634    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3635        self.active_pane().read(cx).active_item()
 3636    }
 3637
 3638    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3639        let item = self.active_item(cx)?;
 3640        item.to_any_view().downcast::<I>().ok()
 3641    }
 3642
 3643    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3644        self.active_item(cx).and_then(|item| item.project_path(cx))
 3645    }
 3646
 3647    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3648        self.recent_navigation_history_iter(cx)
 3649            .filter_map(|(path, abs_path)| {
 3650                let worktree = self
 3651                    .project
 3652                    .read(cx)
 3653                    .worktree_for_id(path.worktree_id, cx)?;
 3654                if worktree.read(cx).is_visible() {
 3655                    abs_path
 3656                } else {
 3657                    None
 3658                }
 3659            })
 3660            .next()
 3661    }
 3662
 3663    pub fn save_active_item(
 3664        &mut self,
 3665        save_intent: SaveIntent,
 3666        window: &mut Window,
 3667        cx: &mut App,
 3668    ) -> Task<Result<()>> {
 3669        let project = self.project.clone();
 3670        let pane = self.active_pane();
 3671        let item = pane.read(cx).active_item();
 3672        let pane = pane.downgrade();
 3673
 3674        window.spawn(cx, async move |cx| {
 3675            if let Some(item) = item {
 3676                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3677                    .await
 3678                    .map(|_| ())
 3679            } else {
 3680                Ok(())
 3681            }
 3682        })
 3683    }
 3684
 3685    pub fn close_inactive_items_and_panes(
 3686        &mut self,
 3687        action: &CloseInactiveTabsAndPanes,
 3688        window: &mut Window,
 3689        cx: &mut Context<Self>,
 3690    ) {
 3691        if let Some(task) = self.close_all_internal(
 3692            true,
 3693            action.save_intent.unwrap_or(SaveIntent::Close),
 3694            window,
 3695            cx,
 3696        ) {
 3697            task.detach_and_log_err(cx)
 3698        }
 3699    }
 3700
 3701    pub fn close_all_items_and_panes(
 3702        &mut self,
 3703        action: &CloseAllItemsAndPanes,
 3704        window: &mut Window,
 3705        cx: &mut Context<Self>,
 3706    ) {
 3707        if let Some(task) = self.close_all_internal(
 3708            false,
 3709            action.save_intent.unwrap_or(SaveIntent::Close),
 3710            window,
 3711            cx,
 3712        ) {
 3713            task.detach_and_log_err(cx)
 3714        }
 3715    }
 3716
 3717    /// Closes the active item across all panes.
 3718    pub fn close_item_in_all_panes(
 3719        &mut self,
 3720        action: &CloseItemInAllPanes,
 3721        window: &mut Window,
 3722        cx: &mut Context<Self>,
 3723    ) {
 3724        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3725            return;
 3726        };
 3727
 3728        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3729        let close_pinned = action.close_pinned;
 3730
 3731        if let Some(project_path) = active_item.project_path(cx) {
 3732            self.close_items_with_project_path(
 3733                &project_path,
 3734                save_intent,
 3735                close_pinned,
 3736                window,
 3737                cx,
 3738            );
 3739        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3740            let item_id = active_item.item_id();
 3741            self.active_pane().update(cx, |pane, cx| {
 3742                pane.close_item_by_id(item_id, save_intent, window, cx)
 3743                    .detach_and_log_err(cx);
 3744            });
 3745        }
 3746    }
 3747
 3748    /// Closes all items with the given project path across all panes.
 3749    pub fn close_items_with_project_path(
 3750        &mut self,
 3751        project_path: &ProjectPath,
 3752        save_intent: SaveIntent,
 3753        close_pinned: bool,
 3754        window: &mut Window,
 3755        cx: &mut Context<Self>,
 3756    ) {
 3757        let panes = self.panes().to_vec();
 3758        for pane in panes {
 3759            pane.update(cx, |pane, cx| {
 3760                pane.close_items_for_project_path(
 3761                    project_path,
 3762                    save_intent,
 3763                    close_pinned,
 3764                    window,
 3765                    cx,
 3766                )
 3767                .detach_and_log_err(cx);
 3768            });
 3769        }
 3770    }
 3771
 3772    fn close_all_internal(
 3773        &mut self,
 3774        retain_active_pane: bool,
 3775        save_intent: SaveIntent,
 3776        window: &mut Window,
 3777        cx: &mut Context<Self>,
 3778    ) -> Option<Task<Result<()>>> {
 3779        let current_pane = self.active_pane();
 3780
 3781        let mut tasks = Vec::new();
 3782
 3783        if retain_active_pane {
 3784            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3785                pane.close_other_items(
 3786                    &CloseOtherItems {
 3787                        save_intent: None,
 3788                        close_pinned: false,
 3789                    },
 3790                    None,
 3791                    window,
 3792                    cx,
 3793                )
 3794            });
 3795
 3796            tasks.push(current_pane_close);
 3797        }
 3798
 3799        for pane in self.panes() {
 3800            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3801                continue;
 3802            }
 3803
 3804            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3805                pane.close_all_items(
 3806                    &CloseAllItems {
 3807                        save_intent: Some(save_intent),
 3808                        close_pinned: false,
 3809                    },
 3810                    window,
 3811                    cx,
 3812                )
 3813            });
 3814
 3815            tasks.push(close_pane_items)
 3816        }
 3817
 3818        if tasks.is_empty() {
 3819            None
 3820        } else {
 3821            Some(cx.spawn_in(window, async move |_, _| {
 3822                for task in tasks {
 3823                    task.await?
 3824                }
 3825                Ok(())
 3826            }))
 3827        }
 3828    }
 3829
 3830    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3831        self.dock_at_position(position).read(cx).is_open()
 3832    }
 3833
 3834    pub fn toggle_dock(
 3835        &mut self,
 3836        dock_side: DockPosition,
 3837        window: &mut Window,
 3838        cx: &mut Context<Self>,
 3839    ) {
 3840        let mut focus_center = false;
 3841        let mut reveal_dock = false;
 3842
 3843        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3844        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3845
 3846        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3847            telemetry::event!(
 3848                "Panel Button Clicked",
 3849                name = panel.persistent_name(),
 3850                toggle_state = !was_visible
 3851            );
 3852        }
 3853        if was_visible {
 3854            self.save_open_dock_positions(cx);
 3855        }
 3856
 3857        let dock = self.dock_at_position(dock_side);
 3858        dock.update(cx, |dock, cx| {
 3859            dock.set_open(!was_visible, window, cx);
 3860
 3861            if dock.active_panel().is_none() {
 3862                let Some(panel_ix) = dock
 3863                    .first_enabled_panel_idx(cx)
 3864                    .log_with_level(log::Level::Info)
 3865                else {
 3866                    return;
 3867                };
 3868                dock.activate_panel(panel_ix, window, cx);
 3869            }
 3870
 3871            if let Some(active_panel) = dock.active_panel() {
 3872                if was_visible {
 3873                    if active_panel
 3874                        .panel_focus_handle(cx)
 3875                        .contains_focused(window, cx)
 3876                    {
 3877                        focus_center = true;
 3878                    }
 3879                } else {
 3880                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3881                    window.focus(focus_handle, cx);
 3882                    reveal_dock = true;
 3883                }
 3884            }
 3885        });
 3886
 3887        if reveal_dock {
 3888            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3889        }
 3890
 3891        if focus_center {
 3892            self.active_pane
 3893                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3894        }
 3895
 3896        cx.notify();
 3897        self.serialize_workspace(window, cx);
 3898    }
 3899
 3900    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3901        self.all_docks().into_iter().find(|&dock| {
 3902            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3903        })
 3904    }
 3905
 3906    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3907        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3908            self.save_open_dock_positions(cx);
 3909            dock.update(cx, |dock, cx| {
 3910                dock.set_open(false, window, cx);
 3911            });
 3912            return true;
 3913        }
 3914        false
 3915    }
 3916
 3917    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3918        self.save_open_dock_positions(cx);
 3919        for dock in self.all_docks() {
 3920            dock.update(cx, |dock, cx| {
 3921                dock.set_open(false, window, cx);
 3922            });
 3923        }
 3924
 3925        cx.focus_self(window);
 3926        cx.notify();
 3927        self.serialize_workspace(window, cx);
 3928    }
 3929
 3930    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 3931        self.all_docks()
 3932            .into_iter()
 3933            .filter_map(|dock| {
 3934                let dock_ref = dock.read(cx);
 3935                if dock_ref.is_open() {
 3936                    Some(dock_ref.position())
 3937                } else {
 3938                    None
 3939                }
 3940            })
 3941            .collect()
 3942    }
 3943
 3944    /// Saves the positions of currently open docks.
 3945    ///
 3946    /// Updates `last_open_dock_positions` with positions of all currently open
 3947    /// docks, to later be restored by the 'Toggle All Docks' action.
 3948    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 3949        let open_dock_positions = self.get_open_dock_positions(cx);
 3950        if !open_dock_positions.is_empty() {
 3951            self.last_open_dock_positions = open_dock_positions;
 3952        }
 3953    }
 3954
 3955    /// Toggles all docks between open and closed states.
 3956    ///
 3957    /// If any docks are open, closes all and remembers their positions. If all
 3958    /// docks are closed, restores the last remembered dock configuration.
 3959    fn toggle_all_docks(
 3960        &mut self,
 3961        _: &ToggleAllDocks,
 3962        window: &mut Window,
 3963        cx: &mut Context<Self>,
 3964    ) {
 3965        let open_dock_positions = self.get_open_dock_positions(cx);
 3966
 3967        if !open_dock_positions.is_empty() {
 3968            self.close_all_docks(window, cx);
 3969        } else if !self.last_open_dock_positions.is_empty() {
 3970            self.restore_last_open_docks(window, cx);
 3971        }
 3972    }
 3973
 3974    /// Reopens docks from the most recently remembered configuration.
 3975    ///
 3976    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 3977    /// and clears the stored positions.
 3978    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3979        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 3980
 3981        for position in positions_to_open {
 3982            let dock = self.dock_at_position(position);
 3983            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 3984        }
 3985
 3986        cx.focus_self(window);
 3987        cx.notify();
 3988        self.serialize_workspace(window, cx);
 3989    }
 3990
 3991    /// Transfer focus to the panel of the given type.
 3992    pub fn focus_panel<T: Panel>(
 3993        &mut self,
 3994        window: &mut Window,
 3995        cx: &mut Context<Self>,
 3996    ) -> Option<Entity<T>> {
 3997        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 3998        panel.to_any().downcast().ok()
 3999    }
 4000
 4001    /// Focus the panel of the given type if it isn't already focused. If it is
 4002    /// already focused, then transfer focus back to the workspace center.
 4003    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 4004    /// panel when transferring focus back to the center.
 4005    pub fn toggle_panel_focus<T: Panel>(
 4006        &mut self,
 4007        window: &mut Window,
 4008        cx: &mut Context<Self>,
 4009    ) -> bool {
 4010        let mut did_focus_panel = false;
 4011        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 4012            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 4013            did_focus_panel
 4014        });
 4015
 4016        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 4017            self.close_panel::<T>(window, cx);
 4018        }
 4019
 4020        telemetry::event!(
 4021            "Panel Button Clicked",
 4022            name = T::persistent_name(),
 4023            toggle_state = did_focus_panel
 4024        );
 4025
 4026        did_focus_panel
 4027    }
 4028
 4029    pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4030        if let Some(item) = self.active_item(cx) {
 4031            item.item_focus_handle(cx).focus(window, cx);
 4032        } else {
 4033            log::error!("Could not find a focus target when switching focus to the center panes",);
 4034        }
 4035    }
 4036
 4037    pub fn activate_panel_for_proto_id(
 4038        &mut self,
 4039        panel_id: PanelId,
 4040        window: &mut Window,
 4041        cx: &mut Context<Self>,
 4042    ) -> Option<Arc<dyn PanelHandle>> {
 4043        let mut panel = None;
 4044        for dock in self.all_docks() {
 4045            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 4046                panel = dock.update(cx, |dock, cx| {
 4047                    dock.activate_panel(panel_index, window, cx);
 4048                    dock.set_open(true, window, cx);
 4049                    dock.active_panel().cloned()
 4050                });
 4051                break;
 4052            }
 4053        }
 4054
 4055        if panel.is_some() {
 4056            cx.notify();
 4057            self.serialize_workspace(window, cx);
 4058        }
 4059
 4060        panel
 4061    }
 4062
 4063    /// Focus or unfocus the given panel type, depending on the given callback.
 4064    fn focus_or_unfocus_panel<T: Panel>(
 4065        &mut self,
 4066        window: &mut Window,
 4067        cx: &mut Context<Self>,
 4068        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 4069    ) -> Option<Arc<dyn PanelHandle>> {
 4070        let mut result_panel = None;
 4071        let mut serialize = false;
 4072        for dock in self.all_docks() {
 4073            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4074                let mut focus_center = false;
 4075                let panel = dock.update(cx, |dock, cx| {
 4076                    dock.activate_panel(panel_index, window, cx);
 4077
 4078                    let panel = dock.active_panel().cloned();
 4079                    if let Some(panel) = panel.as_ref() {
 4080                        if should_focus(&**panel, window, cx) {
 4081                            dock.set_open(true, window, cx);
 4082                            panel.panel_focus_handle(cx).focus(window, cx);
 4083                        } else {
 4084                            focus_center = true;
 4085                        }
 4086                    }
 4087                    panel
 4088                });
 4089
 4090                if focus_center {
 4091                    self.active_pane
 4092                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4093                }
 4094
 4095                result_panel = panel;
 4096                serialize = true;
 4097                break;
 4098            }
 4099        }
 4100
 4101        if serialize {
 4102            self.serialize_workspace(window, cx);
 4103        }
 4104
 4105        cx.notify();
 4106        result_panel
 4107    }
 4108
 4109    /// Open the panel of the given type
 4110    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4111        for dock in self.all_docks() {
 4112            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4113                dock.update(cx, |dock, cx| {
 4114                    dock.activate_panel(panel_index, window, cx);
 4115                    dock.set_open(true, window, cx);
 4116                });
 4117            }
 4118        }
 4119    }
 4120
 4121    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 4122        for dock in self.all_docks().iter() {
 4123            dock.update(cx, |dock, cx| {
 4124                if dock.panel::<T>().is_some() {
 4125                    dock.set_open(false, window, cx)
 4126                }
 4127            })
 4128        }
 4129    }
 4130
 4131    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 4132        self.all_docks()
 4133            .iter()
 4134            .find_map(|dock| dock.read(cx).panel::<T>())
 4135    }
 4136
 4137    fn dismiss_zoomed_items_to_reveal(
 4138        &mut self,
 4139        dock_to_reveal: Option<DockPosition>,
 4140        window: &mut Window,
 4141        cx: &mut Context<Self>,
 4142    ) {
 4143        // If a center pane is zoomed, unzoom it.
 4144        for pane in &self.panes {
 4145            if pane != &self.active_pane || dock_to_reveal.is_some() {
 4146                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4147            }
 4148        }
 4149
 4150        // If another dock is zoomed, hide it.
 4151        let mut focus_center = false;
 4152        for dock in self.all_docks() {
 4153            dock.update(cx, |dock, cx| {
 4154                if Some(dock.position()) != dock_to_reveal
 4155                    && let Some(panel) = dock.active_panel()
 4156                    && panel.is_zoomed(window, cx)
 4157                {
 4158                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 4159                    dock.set_open(false, window, cx);
 4160                }
 4161            });
 4162        }
 4163
 4164        if focus_center {
 4165            self.active_pane
 4166                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4167        }
 4168
 4169        if self.zoomed_position != dock_to_reveal {
 4170            self.zoomed = None;
 4171            self.zoomed_position = None;
 4172            cx.emit(Event::ZoomChanged);
 4173        }
 4174
 4175        cx.notify();
 4176    }
 4177
 4178    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4179        let pane = cx.new(|cx| {
 4180            let mut pane = Pane::new(
 4181                self.weak_handle(),
 4182                self.project.clone(),
 4183                self.pane_history_timestamp.clone(),
 4184                None,
 4185                NewFile.boxed_clone(),
 4186                true,
 4187                window,
 4188                cx,
 4189            );
 4190            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4191            pane
 4192        });
 4193        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4194            .detach();
 4195        self.panes.push(pane.clone());
 4196
 4197        window.focus(&pane.focus_handle(cx), cx);
 4198
 4199        cx.emit(Event::PaneAdded(pane.clone()));
 4200        pane
 4201    }
 4202
 4203    pub fn add_item_to_center(
 4204        &mut self,
 4205        item: Box<dyn ItemHandle>,
 4206        window: &mut Window,
 4207        cx: &mut Context<Self>,
 4208    ) -> bool {
 4209        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4210            if let Some(center_pane) = center_pane.upgrade() {
 4211                center_pane.update(cx, |pane, cx| {
 4212                    pane.add_item(item, true, true, None, window, cx)
 4213                });
 4214                true
 4215            } else {
 4216                false
 4217            }
 4218        } else {
 4219            false
 4220        }
 4221    }
 4222
 4223    pub fn add_item_to_active_pane(
 4224        &mut self,
 4225        item: Box<dyn ItemHandle>,
 4226        destination_index: Option<usize>,
 4227        focus_item: bool,
 4228        window: &mut Window,
 4229        cx: &mut App,
 4230    ) {
 4231        self.add_item(
 4232            self.active_pane.clone(),
 4233            item,
 4234            destination_index,
 4235            false,
 4236            focus_item,
 4237            window,
 4238            cx,
 4239        )
 4240    }
 4241
 4242    pub fn add_item(
 4243        &mut self,
 4244        pane: Entity<Pane>,
 4245        item: Box<dyn ItemHandle>,
 4246        destination_index: Option<usize>,
 4247        activate_pane: bool,
 4248        focus_item: bool,
 4249        window: &mut Window,
 4250        cx: &mut App,
 4251    ) {
 4252        pane.update(cx, |pane, cx| {
 4253            pane.add_item(
 4254                item,
 4255                activate_pane,
 4256                focus_item,
 4257                destination_index,
 4258                window,
 4259                cx,
 4260            )
 4261        });
 4262    }
 4263
 4264    pub fn split_item(
 4265        &mut self,
 4266        split_direction: SplitDirection,
 4267        item: Box<dyn ItemHandle>,
 4268        window: &mut Window,
 4269        cx: &mut Context<Self>,
 4270    ) {
 4271        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4272        self.add_item(new_pane, item, None, true, true, window, cx);
 4273    }
 4274
 4275    pub fn open_abs_path(
 4276        &mut self,
 4277        abs_path: PathBuf,
 4278        options: OpenOptions,
 4279        window: &mut Window,
 4280        cx: &mut Context<Self>,
 4281    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4282        cx.spawn_in(window, async move |workspace, cx| {
 4283            let open_paths_task_result = workspace
 4284                .update_in(cx, |workspace, window, cx| {
 4285                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4286                })
 4287                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4288                .await;
 4289            anyhow::ensure!(
 4290                open_paths_task_result.len() == 1,
 4291                "open abs path {abs_path:?} task returned incorrect number of results"
 4292            );
 4293            match open_paths_task_result
 4294                .into_iter()
 4295                .next()
 4296                .expect("ensured single task result")
 4297            {
 4298                Some(open_result) => {
 4299                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4300                }
 4301                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4302            }
 4303        })
 4304    }
 4305
 4306    pub fn split_abs_path(
 4307        &mut self,
 4308        abs_path: PathBuf,
 4309        visible: bool,
 4310        window: &mut Window,
 4311        cx: &mut Context<Self>,
 4312    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4313        let project_path_task =
 4314            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4315        cx.spawn_in(window, async move |this, cx| {
 4316            let (_, path) = project_path_task.await?;
 4317            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4318                .await
 4319        })
 4320    }
 4321
 4322    pub fn open_path(
 4323        &mut self,
 4324        path: impl Into<ProjectPath>,
 4325        pane: Option<WeakEntity<Pane>>,
 4326        focus_item: bool,
 4327        window: &mut Window,
 4328        cx: &mut App,
 4329    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4330        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4331    }
 4332
 4333    pub fn open_path_preview(
 4334        &mut self,
 4335        path: impl Into<ProjectPath>,
 4336        pane: Option<WeakEntity<Pane>>,
 4337        focus_item: bool,
 4338        allow_preview: bool,
 4339        activate: bool,
 4340        window: &mut Window,
 4341        cx: &mut App,
 4342    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4343        let pane = pane.unwrap_or_else(|| {
 4344            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4345                self.panes
 4346                    .first()
 4347                    .expect("There must be an active pane")
 4348                    .downgrade()
 4349            })
 4350        });
 4351
 4352        let project_path = path.into();
 4353        let task = self.load_path(project_path.clone(), window, cx);
 4354        window.spawn(cx, async move |cx| {
 4355            let (project_entry_id, build_item) = task.await?;
 4356
 4357            pane.update_in(cx, |pane, window, cx| {
 4358                pane.open_item(
 4359                    project_entry_id,
 4360                    project_path,
 4361                    focus_item,
 4362                    allow_preview,
 4363                    activate,
 4364                    None,
 4365                    window,
 4366                    cx,
 4367                    build_item,
 4368                )
 4369            })
 4370        })
 4371    }
 4372
 4373    pub fn split_path(
 4374        &mut self,
 4375        path: impl Into<ProjectPath>,
 4376        window: &mut Window,
 4377        cx: &mut Context<Self>,
 4378    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4379        self.split_path_preview(path, false, None, window, cx)
 4380    }
 4381
 4382    pub fn split_path_preview(
 4383        &mut self,
 4384        path: impl Into<ProjectPath>,
 4385        allow_preview: bool,
 4386        split_direction: Option<SplitDirection>,
 4387        window: &mut Window,
 4388        cx: &mut Context<Self>,
 4389    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4390        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4391            self.panes
 4392                .first()
 4393                .expect("There must be an active pane")
 4394                .downgrade()
 4395        });
 4396
 4397        if let Member::Pane(center_pane) = &self.center.root
 4398            && center_pane.read(cx).items_len() == 0
 4399        {
 4400            return self.open_path(path, Some(pane), true, window, cx);
 4401        }
 4402
 4403        let project_path = path.into();
 4404        let task = self.load_path(project_path.clone(), window, cx);
 4405        cx.spawn_in(window, async move |this, cx| {
 4406            let (project_entry_id, build_item) = task.await?;
 4407            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4408                let pane = pane.upgrade()?;
 4409                let new_pane = this.split_pane(
 4410                    pane,
 4411                    split_direction.unwrap_or(SplitDirection::Right),
 4412                    window,
 4413                    cx,
 4414                );
 4415                new_pane.update(cx, |new_pane, cx| {
 4416                    Some(new_pane.open_item(
 4417                        project_entry_id,
 4418                        project_path,
 4419                        true,
 4420                        allow_preview,
 4421                        true,
 4422                        None,
 4423                        window,
 4424                        cx,
 4425                        build_item,
 4426                    ))
 4427                })
 4428            })
 4429            .map(|option| option.context("pane was dropped"))?
 4430        })
 4431    }
 4432
 4433    fn load_path(
 4434        &mut self,
 4435        path: ProjectPath,
 4436        window: &mut Window,
 4437        cx: &mut App,
 4438    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4439        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4440        registry.open_path(self.project(), &path, window, cx)
 4441    }
 4442
 4443    pub fn find_project_item<T>(
 4444        &self,
 4445        pane: &Entity<Pane>,
 4446        project_item: &Entity<T::Item>,
 4447        cx: &App,
 4448    ) -> Option<Entity<T>>
 4449    where
 4450        T: ProjectItem,
 4451    {
 4452        use project::ProjectItem as _;
 4453        let project_item = project_item.read(cx);
 4454        let entry_id = project_item.entry_id(cx);
 4455        let project_path = project_item.project_path(cx);
 4456
 4457        let mut item = None;
 4458        if let Some(entry_id) = entry_id {
 4459            item = pane.read(cx).item_for_entry(entry_id, cx);
 4460        }
 4461        if item.is_none()
 4462            && let Some(project_path) = project_path
 4463        {
 4464            item = pane.read(cx).item_for_path(project_path, cx);
 4465        }
 4466
 4467        item.and_then(|item| item.downcast::<T>())
 4468    }
 4469
 4470    pub fn is_project_item_open<T>(
 4471        &self,
 4472        pane: &Entity<Pane>,
 4473        project_item: &Entity<T::Item>,
 4474        cx: &App,
 4475    ) -> bool
 4476    where
 4477        T: ProjectItem,
 4478    {
 4479        self.find_project_item::<T>(pane, project_item, cx)
 4480            .is_some()
 4481    }
 4482
 4483    pub fn open_project_item<T>(
 4484        &mut self,
 4485        pane: Entity<Pane>,
 4486        project_item: Entity<T::Item>,
 4487        activate_pane: bool,
 4488        focus_item: bool,
 4489        keep_old_preview: bool,
 4490        allow_new_preview: bool,
 4491        window: &mut Window,
 4492        cx: &mut Context<Self>,
 4493    ) -> Entity<T>
 4494    where
 4495        T: ProjectItem,
 4496    {
 4497        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4498
 4499        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4500            if !keep_old_preview
 4501                && let Some(old_id) = old_item_id
 4502                && old_id != item.item_id()
 4503            {
 4504                // switching to a different item, so unpreview old active item
 4505                pane.update(cx, |pane, _| {
 4506                    pane.unpreview_item_if_preview(old_id);
 4507                });
 4508            }
 4509
 4510            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4511            if !allow_new_preview {
 4512                pane.update(cx, |pane, _| {
 4513                    pane.unpreview_item_if_preview(item.item_id());
 4514                });
 4515            }
 4516            return item;
 4517        }
 4518
 4519        let item = pane.update(cx, |pane, cx| {
 4520            cx.new(|cx| {
 4521                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4522            })
 4523        });
 4524        let mut destination_index = None;
 4525        pane.update(cx, |pane, cx| {
 4526            if !keep_old_preview && let Some(old_id) = old_item_id {
 4527                pane.unpreview_item_if_preview(old_id);
 4528            }
 4529            if allow_new_preview {
 4530                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4531            }
 4532        });
 4533
 4534        self.add_item(
 4535            pane,
 4536            Box::new(item.clone()),
 4537            destination_index,
 4538            activate_pane,
 4539            focus_item,
 4540            window,
 4541            cx,
 4542        );
 4543        item
 4544    }
 4545
 4546    pub fn open_shared_screen(
 4547        &mut self,
 4548        peer_id: PeerId,
 4549        window: &mut Window,
 4550        cx: &mut Context<Self>,
 4551    ) {
 4552        if let Some(shared_screen) =
 4553            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4554        {
 4555            self.active_pane.update(cx, |pane, cx| {
 4556                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4557            });
 4558        }
 4559    }
 4560
 4561    pub fn activate_item(
 4562        &mut self,
 4563        item: &dyn ItemHandle,
 4564        activate_pane: bool,
 4565        focus_item: bool,
 4566        window: &mut Window,
 4567        cx: &mut App,
 4568    ) -> bool {
 4569        let result = self.panes.iter().find_map(|pane| {
 4570            pane.read(cx)
 4571                .index_for_item(item)
 4572                .map(|ix| (pane.clone(), ix))
 4573        });
 4574        if let Some((pane, ix)) = result {
 4575            pane.update(cx, |pane, cx| {
 4576                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4577            });
 4578            true
 4579        } else {
 4580            false
 4581        }
 4582    }
 4583
 4584    fn activate_pane_at_index(
 4585        &mut self,
 4586        action: &ActivatePane,
 4587        window: &mut Window,
 4588        cx: &mut Context<Self>,
 4589    ) {
 4590        let panes = self.center.panes();
 4591        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4592            window.focus(&pane.focus_handle(cx), cx);
 4593        } else {
 4594            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4595                .detach();
 4596        }
 4597    }
 4598
 4599    fn move_item_to_pane_at_index(
 4600        &mut self,
 4601        action: &MoveItemToPane,
 4602        window: &mut Window,
 4603        cx: &mut Context<Self>,
 4604    ) {
 4605        let panes = self.center.panes();
 4606        let destination = match panes.get(action.destination) {
 4607            Some(&destination) => destination.clone(),
 4608            None => {
 4609                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4610                    return;
 4611                }
 4612                let direction = SplitDirection::Right;
 4613                let split_off_pane = self
 4614                    .find_pane_in_direction(direction, cx)
 4615                    .unwrap_or_else(|| self.active_pane.clone());
 4616                let new_pane = self.add_pane(window, cx);
 4617                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4618                new_pane
 4619            }
 4620        };
 4621
 4622        if action.clone {
 4623            if self
 4624                .active_pane
 4625                .read(cx)
 4626                .active_item()
 4627                .is_some_and(|item| item.can_split(cx))
 4628            {
 4629                clone_active_item(
 4630                    self.database_id(),
 4631                    &self.active_pane,
 4632                    &destination,
 4633                    action.focus,
 4634                    window,
 4635                    cx,
 4636                );
 4637                return;
 4638            }
 4639        }
 4640        move_active_item(
 4641            &self.active_pane,
 4642            &destination,
 4643            action.focus,
 4644            true,
 4645            window,
 4646            cx,
 4647        )
 4648    }
 4649
 4650    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4651        let panes = self.center.panes();
 4652        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4653            let next_ix = (ix + 1) % panes.len();
 4654            let next_pane = panes[next_ix].clone();
 4655            window.focus(&next_pane.focus_handle(cx), cx);
 4656        }
 4657    }
 4658
 4659    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4660        let panes = self.center.panes();
 4661        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4662            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4663            let prev_pane = panes[prev_ix].clone();
 4664            window.focus(&prev_pane.focus_handle(cx), cx);
 4665        }
 4666    }
 4667
 4668    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4669        let last_pane = self.center.last_pane();
 4670        window.focus(&last_pane.focus_handle(cx), cx);
 4671    }
 4672
 4673    pub fn activate_pane_in_direction(
 4674        &mut self,
 4675        direction: SplitDirection,
 4676        window: &mut Window,
 4677        cx: &mut App,
 4678    ) {
 4679        use ActivateInDirectionTarget as Target;
 4680        enum Origin {
 4681            Sidebar,
 4682            LeftDock,
 4683            RightDock,
 4684            BottomDock,
 4685            Center,
 4686        }
 4687
 4688        let origin: Origin = if self
 4689            .sidebar_focus_handle
 4690            .as_ref()
 4691            .is_some_and(|h| h.contains_focused(window, cx))
 4692        {
 4693            Origin::Sidebar
 4694        } else {
 4695            [
 4696                (&self.left_dock, Origin::LeftDock),
 4697                (&self.right_dock, Origin::RightDock),
 4698                (&self.bottom_dock, Origin::BottomDock),
 4699            ]
 4700            .into_iter()
 4701            .find_map(|(dock, origin)| {
 4702                if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4703                    Some(origin)
 4704                } else {
 4705                    None
 4706                }
 4707            })
 4708            .unwrap_or(Origin::Center)
 4709        };
 4710
 4711        let get_last_active_pane = || {
 4712            let pane = self
 4713                .last_active_center_pane
 4714                .clone()
 4715                .unwrap_or_else(|| {
 4716                    self.panes
 4717                        .first()
 4718                        .expect("There must be an active pane")
 4719                        .downgrade()
 4720                })
 4721                .upgrade()?;
 4722            (pane.read(cx).items_len() != 0).then_some(pane)
 4723        };
 4724
 4725        let try_dock =
 4726            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4727
 4728        let sidebar_target = self
 4729            .sidebar_focus_handle
 4730            .as_ref()
 4731            .map(|h| Target::Sidebar(h.clone()));
 4732
 4733        let target = match (origin, direction) {
 4734            // From the sidebar, only Right navigates into the workspace.
 4735            (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
 4736                .or_else(|| get_last_active_pane().map(Target::Pane))
 4737                .or_else(|| try_dock(&self.bottom_dock))
 4738                .or_else(|| try_dock(&self.right_dock)),
 4739
 4740            (Origin::Sidebar, _) => None,
 4741
 4742            // We're in the center, so we first try to go to a different pane,
 4743            // otherwise try to go to a dock.
 4744            (Origin::Center, direction) => {
 4745                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4746                    Some(Target::Pane(pane))
 4747                } else {
 4748                    match direction {
 4749                        SplitDirection::Up => None,
 4750                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4751                        SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
 4752                        SplitDirection::Right => try_dock(&self.right_dock),
 4753                    }
 4754                }
 4755            }
 4756
 4757            (Origin::LeftDock, SplitDirection::Right) => {
 4758                if let Some(last_active_pane) = get_last_active_pane() {
 4759                    Some(Target::Pane(last_active_pane))
 4760                } else {
 4761                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4762                }
 4763            }
 4764
 4765            (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
 4766
 4767            (Origin::LeftDock, SplitDirection::Down)
 4768            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4769
 4770            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4771            (Origin::BottomDock, SplitDirection::Left) => {
 4772                try_dock(&self.left_dock).or(sidebar_target)
 4773            }
 4774            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4775
 4776            (Origin::RightDock, SplitDirection::Left) => {
 4777                if let Some(last_active_pane) = get_last_active_pane() {
 4778                    Some(Target::Pane(last_active_pane))
 4779                } else {
 4780                    try_dock(&self.bottom_dock)
 4781                        .or_else(|| try_dock(&self.left_dock))
 4782                        .or(sidebar_target)
 4783                }
 4784            }
 4785
 4786            _ => None,
 4787        };
 4788
 4789        match target {
 4790            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4791                let pane = pane.read(cx);
 4792                if let Some(item) = pane.active_item() {
 4793                    item.item_focus_handle(cx).focus(window, cx);
 4794                } else {
 4795                    log::error!(
 4796                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4797                    );
 4798                }
 4799            }
 4800            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4801                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4802                window.defer(cx, move |window, cx| {
 4803                    let dock = dock.read(cx);
 4804                    if let Some(panel) = dock.active_panel() {
 4805                        panel.panel_focus_handle(cx).focus(window, cx);
 4806                    } else {
 4807                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4808                    }
 4809                })
 4810            }
 4811            Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
 4812                focus_handle.focus(window, cx);
 4813            }
 4814            None => {}
 4815        }
 4816    }
 4817
 4818    pub fn move_item_to_pane_in_direction(
 4819        &mut self,
 4820        action: &MoveItemToPaneInDirection,
 4821        window: &mut Window,
 4822        cx: &mut Context<Self>,
 4823    ) {
 4824        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4825            Some(destination) => destination,
 4826            None => {
 4827                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4828                    return;
 4829                }
 4830                let new_pane = self.add_pane(window, cx);
 4831                self.center
 4832                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4833                new_pane
 4834            }
 4835        };
 4836
 4837        if action.clone {
 4838            if self
 4839                .active_pane
 4840                .read(cx)
 4841                .active_item()
 4842                .is_some_and(|item| item.can_split(cx))
 4843            {
 4844                clone_active_item(
 4845                    self.database_id(),
 4846                    &self.active_pane,
 4847                    &destination,
 4848                    action.focus,
 4849                    window,
 4850                    cx,
 4851                );
 4852                return;
 4853            }
 4854        }
 4855        move_active_item(
 4856            &self.active_pane,
 4857            &destination,
 4858            action.focus,
 4859            true,
 4860            window,
 4861            cx,
 4862        );
 4863    }
 4864
 4865    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4866        self.center.bounding_box_for_pane(pane)
 4867    }
 4868
 4869    pub fn find_pane_in_direction(
 4870        &mut self,
 4871        direction: SplitDirection,
 4872        cx: &App,
 4873    ) -> Option<Entity<Pane>> {
 4874        self.center
 4875            .find_pane_in_direction(&self.active_pane, direction, cx)
 4876            .cloned()
 4877    }
 4878
 4879    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4880        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4881            self.center.swap(&self.active_pane, &to, cx);
 4882            cx.notify();
 4883        }
 4884    }
 4885
 4886    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4887        if self
 4888            .center
 4889            .move_to_border(&self.active_pane, direction, cx)
 4890            .unwrap()
 4891        {
 4892            cx.notify();
 4893        }
 4894    }
 4895
 4896    pub fn resize_pane(
 4897        &mut self,
 4898        axis: gpui::Axis,
 4899        amount: Pixels,
 4900        window: &mut Window,
 4901        cx: &mut Context<Self>,
 4902    ) {
 4903        let docks = self.all_docks();
 4904        let active_dock = docks
 4905            .into_iter()
 4906            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4907
 4908        if let Some(dock_entity) = active_dock {
 4909            let dock = dock_entity.read(cx);
 4910            let Some(panel_size) = self.dock_size(&dock, window, cx) else {
 4911                return;
 4912            };
 4913            match dock.position() {
 4914                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4915                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4916                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4917            }
 4918        } else {
 4919            self.center
 4920                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 4921        }
 4922        cx.notify();
 4923    }
 4924
 4925    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 4926        self.center.reset_pane_sizes(cx);
 4927        cx.notify();
 4928    }
 4929
 4930    fn handle_pane_focused(
 4931        &mut self,
 4932        pane: Entity<Pane>,
 4933        window: &mut Window,
 4934        cx: &mut Context<Self>,
 4935    ) {
 4936        // This is explicitly hoisted out of the following check for pane identity as
 4937        // terminal panel panes are not registered as a center panes.
 4938        self.status_bar.update(cx, |status_bar, cx| {
 4939            status_bar.set_active_pane(&pane, window, cx);
 4940        });
 4941        if self.active_pane != pane {
 4942            self.set_active_pane(&pane, window, cx);
 4943        }
 4944
 4945        if self.last_active_center_pane.is_none() {
 4946            self.last_active_center_pane = Some(pane.downgrade());
 4947        }
 4948
 4949        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 4950        // This prevents the dock from closing when focus events fire during window activation.
 4951        // We also preserve any dock whose active panel itself has focus — this covers
 4952        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 4953        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 4954            let dock_read = dock.read(cx);
 4955            if let Some(panel) = dock_read.active_panel() {
 4956                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 4957                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 4958                {
 4959                    return Some(dock_read.position());
 4960                }
 4961            }
 4962            None
 4963        });
 4964
 4965        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 4966        if pane.read(cx).is_zoomed() {
 4967            self.zoomed = Some(pane.downgrade().into());
 4968        } else {
 4969            self.zoomed = None;
 4970        }
 4971        self.zoomed_position = None;
 4972        cx.emit(Event::ZoomChanged);
 4973        self.update_active_view_for_followers(window, cx);
 4974        pane.update(cx, |pane, _| {
 4975            pane.track_alternate_file_items();
 4976        });
 4977
 4978        cx.notify();
 4979    }
 4980
 4981    fn set_active_pane(
 4982        &mut self,
 4983        pane: &Entity<Pane>,
 4984        window: &mut Window,
 4985        cx: &mut Context<Self>,
 4986    ) {
 4987        self.active_pane = pane.clone();
 4988        self.active_item_path_changed(true, window, cx);
 4989        self.last_active_center_pane = Some(pane.downgrade());
 4990    }
 4991
 4992    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4993        self.update_active_view_for_followers(window, cx);
 4994    }
 4995
 4996    fn handle_pane_event(
 4997        &mut self,
 4998        pane: &Entity<Pane>,
 4999        event: &pane::Event,
 5000        window: &mut Window,
 5001        cx: &mut Context<Self>,
 5002    ) {
 5003        let mut serialize_workspace = true;
 5004        match event {
 5005            pane::Event::AddItem { item } => {
 5006                item.added_to_pane(self, pane.clone(), window, cx);
 5007                cx.emit(Event::ItemAdded {
 5008                    item: item.boxed_clone(),
 5009                });
 5010            }
 5011            pane::Event::Split { direction, mode } => {
 5012                match mode {
 5013                    SplitMode::ClonePane => {
 5014                        self.split_and_clone(pane.clone(), *direction, window, cx)
 5015                            .detach();
 5016                    }
 5017                    SplitMode::EmptyPane => {
 5018                        self.split_pane(pane.clone(), *direction, window, cx);
 5019                    }
 5020                    SplitMode::MovePane => {
 5021                        self.split_and_move(pane.clone(), *direction, window, cx);
 5022                    }
 5023                };
 5024            }
 5025            pane::Event::JoinIntoNext => {
 5026                self.join_pane_into_next(pane.clone(), window, cx);
 5027            }
 5028            pane::Event::JoinAll => {
 5029                self.join_all_panes(window, cx);
 5030            }
 5031            pane::Event::Remove { focus_on_pane } => {
 5032                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 5033            }
 5034            pane::Event::ActivateItem {
 5035                local,
 5036                focus_changed,
 5037            } => {
 5038                window.invalidate_character_coordinates();
 5039
 5040                pane.update(cx, |pane, _| {
 5041                    pane.track_alternate_file_items();
 5042                });
 5043                if *local {
 5044                    self.unfollow_in_pane(pane, window, cx);
 5045                }
 5046                serialize_workspace = *focus_changed || pane != self.active_pane();
 5047                if pane == self.active_pane() {
 5048                    self.active_item_path_changed(*focus_changed, window, cx);
 5049                    self.update_active_view_for_followers(window, cx);
 5050                } else if *local {
 5051                    self.set_active_pane(pane, window, cx);
 5052                }
 5053            }
 5054            pane::Event::UserSavedItem { item, save_intent } => {
 5055                cx.emit(Event::UserSavedItem {
 5056                    pane: pane.downgrade(),
 5057                    item: item.boxed_clone(),
 5058                    save_intent: *save_intent,
 5059                });
 5060                serialize_workspace = false;
 5061            }
 5062            pane::Event::ChangeItemTitle => {
 5063                if *pane == self.active_pane {
 5064                    self.active_item_path_changed(false, window, cx);
 5065                }
 5066                serialize_workspace = false;
 5067            }
 5068            pane::Event::RemovedItem { item } => {
 5069                cx.emit(Event::ActiveItemChanged);
 5070                self.update_window_edited(window, cx);
 5071                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 5072                    && entry.get().entity_id() == pane.entity_id()
 5073                {
 5074                    entry.remove();
 5075                }
 5076                cx.emit(Event::ItemRemoved {
 5077                    item_id: item.item_id(),
 5078                });
 5079            }
 5080            pane::Event::Focus => {
 5081                window.invalidate_character_coordinates();
 5082                self.handle_pane_focused(pane.clone(), window, cx);
 5083            }
 5084            pane::Event::ZoomIn => {
 5085                if *pane == self.active_pane {
 5086                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 5087                    if pane.read(cx).has_focus(window, cx) {
 5088                        self.zoomed = Some(pane.downgrade().into());
 5089                        self.zoomed_position = None;
 5090                        cx.emit(Event::ZoomChanged);
 5091                    }
 5092                    cx.notify();
 5093                }
 5094            }
 5095            pane::Event::ZoomOut => {
 5096                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 5097                if self.zoomed_position.is_none() {
 5098                    self.zoomed = None;
 5099                    cx.emit(Event::ZoomChanged);
 5100                }
 5101                cx.notify();
 5102            }
 5103            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 5104        }
 5105
 5106        if serialize_workspace {
 5107            self.serialize_workspace(window, cx);
 5108        }
 5109    }
 5110
 5111    pub fn unfollow_in_pane(
 5112        &mut self,
 5113        pane: &Entity<Pane>,
 5114        window: &mut Window,
 5115        cx: &mut Context<Workspace>,
 5116    ) -> Option<CollaboratorId> {
 5117        let leader_id = self.leader_for_pane(pane)?;
 5118        self.unfollow(leader_id, window, cx);
 5119        Some(leader_id)
 5120    }
 5121
 5122    pub fn split_pane(
 5123        &mut self,
 5124        pane_to_split: Entity<Pane>,
 5125        split_direction: SplitDirection,
 5126        window: &mut Window,
 5127        cx: &mut Context<Self>,
 5128    ) -> Entity<Pane> {
 5129        let new_pane = self.add_pane(window, cx);
 5130        self.center
 5131            .split(&pane_to_split, &new_pane, split_direction, cx);
 5132        cx.notify();
 5133        new_pane
 5134    }
 5135
 5136    pub fn split_and_move(
 5137        &mut self,
 5138        pane: Entity<Pane>,
 5139        direction: SplitDirection,
 5140        window: &mut Window,
 5141        cx: &mut Context<Self>,
 5142    ) {
 5143        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 5144            return;
 5145        };
 5146        let new_pane = self.add_pane(window, cx);
 5147        new_pane.update(cx, |pane, cx| {
 5148            pane.add_item(item, true, true, None, window, cx)
 5149        });
 5150        self.center.split(&pane, &new_pane, direction, cx);
 5151        cx.notify();
 5152    }
 5153
 5154    pub fn split_and_clone(
 5155        &mut self,
 5156        pane: Entity<Pane>,
 5157        direction: SplitDirection,
 5158        window: &mut Window,
 5159        cx: &mut Context<Self>,
 5160    ) -> Task<Option<Entity<Pane>>> {
 5161        let Some(item) = pane.read(cx).active_item() else {
 5162            return Task::ready(None);
 5163        };
 5164        if !item.can_split(cx) {
 5165            return Task::ready(None);
 5166        }
 5167        let task = item.clone_on_split(self.database_id(), window, cx);
 5168        cx.spawn_in(window, async move |this, cx| {
 5169            if let Some(clone) = task.await {
 5170                this.update_in(cx, |this, window, cx| {
 5171                    let new_pane = this.add_pane(window, cx);
 5172                    let nav_history = pane.read(cx).fork_nav_history();
 5173                    new_pane.update(cx, |pane, cx| {
 5174                        pane.set_nav_history(nav_history, cx);
 5175                        pane.add_item(clone, true, true, None, window, cx)
 5176                    });
 5177                    this.center.split(&pane, &new_pane, direction, cx);
 5178                    cx.notify();
 5179                    new_pane
 5180                })
 5181                .ok()
 5182            } else {
 5183                None
 5184            }
 5185        })
 5186    }
 5187
 5188    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5189        let active_item = self.active_pane.read(cx).active_item();
 5190        for pane in &self.panes {
 5191            join_pane_into_active(&self.active_pane, pane, window, cx);
 5192        }
 5193        if let Some(active_item) = active_item {
 5194            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5195        }
 5196        cx.notify();
 5197    }
 5198
 5199    pub fn join_pane_into_next(
 5200        &mut self,
 5201        pane: Entity<Pane>,
 5202        window: &mut Window,
 5203        cx: &mut Context<Self>,
 5204    ) {
 5205        let next_pane = self
 5206            .find_pane_in_direction(SplitDirection::Right, cx)
 5207            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5208            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5209            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5210        let Some(next_pane) = next_pane else {
 5211            return;
 5212        };
 5213        move_all_items(&pane, &next_pane, window, cx);
 5214        cx.notify();
 5215    }
 5216
 5217    fn remove_pane(
 5218        &mut self,
 5219        pane: Entity<Pane>,
 5220        focus_on: Option<Entity<Pane>>,
 5221        window: &mut Window,
 5222        cx: &mut Context<Self>,
 5223    ) {
 5224        if self.center.remove(&pane, cx).unwrap() {
 5225            self.force_remove_pane(&pane, &focus_on, window, cx);
 5226            self.unfollow_in_pane(&pane, window, cx);
 5227            self.last_leaders_by_pane.remove(&pane.downgrade());
 5228            for removed_item in pane.read(cx).items() {
 5229                self.panes_by_item.remove(&removed_item.item_id());
 5230            }
 5231
 5232            cx.notify();
 5233        } else {
 5234            self.active_item_path_changed(true, window, cx);
 5235        }
 5236        cx.emit(Event::PaneRemoved);
 5237    }
 5238
 5239    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5240        &mut self.panes
 5241    }
 5242
 5243    pub fn panes(&self) -> &[Entity<Pane>] {
 5244        &self.panes
 5245    }
 5246
 5247    pub fn active_pane(&self) -> &Entity<Pane> {
 5248        &self.active_pane
 5249    }
 5250
 5251    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5252        for dock in self.all_docks() {
 5253            if dock.focus_handle(cx).contains_focused(window, cx)
 5254                && let Some(pane) = dock
 5255                    .read(cx)
 5256                    .active_panel()
 5257                    .and_then(|panel| panel.pane(cx))
 5258            {
 5259                return pane;
 5260            }
 5261        }
 5262        self.active_pane().clone()
 5263    }
 5264
 5265    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5266        self.find_pane_in_direction(SplitDirection::Right, cx)
 5267            .unwrap_or_else(|| {
 5268                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5269            })
 5270    }
 5271
 5272    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5273        self.pane_for_item_id(handle.item_id())
 5274    }
 5275
 5276    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5277        let weak_pane = self.panes_by_item.get(&item_id)?;
 5278        weak_pane.upgrade()
 5279    }
 5280
 5281    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5282        self.panes
 5283            .iter()
 5284            .find(|pane| pane.entity_id() == entity_id)
 5285            .cloned()
 5286    }
 5287
 5288    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5289        self.follower_states.retain(|leader_id, state| {
 5290            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5291                for item in state.items_by_leader_view_id.values() {
 5292                    item.view.set_leader_id(None, window, cx);
 5293                }
 5294                false
 5295            } else {
 5296                true
 5297            }
 5298        });
 5299        cx.notify();
 5300    }
 5301
 5302    pub fn start_following(
 5303        &mut self,
 5304        leader_id: impl Into<CollaboratorId>,
 5305        window: &mut Window,
 5306        cx: &mut Context<Self>,
 5307    ) -> Option<Task<Result<()>>> {
 5308        let leader_id = leader_id.into();
 5309        let pane = self.active_pane().clone();
 5310
 5311        self.last_leaders_by_pane
 5312            .insert(pane.downgrade(), leader_id);
 5313        self.unfollow(leader_id, window, cx);
 5314        self.unfollow_in_pane(&pane, window, cx);
 5315        self.follower_states.insert(
 5316            leader_id,
 5317            FollowerState {
 5318                center_pane: pane.clone(),
 5319                dock_pane: None,
 5320                active_view_id: None,
 5321                items_by_leader_view_id: Default::default(),
 5322            },
 5323        );
 5324        cx.notify();
 5325
 5326        match leader_id {
 5327            CollaboratorId::PeerId(leader_peer_id) => {
 5328                let room_id = self.active_call()?.room_id(cx)?;
 5329                let project_id = self.project.read(cx).remote_id();
 5330                let request = self.app_state.client.request(proto::Follow {
 5331                    room_id,
 5332                    project_id,
 5333                    leader_id: Some(leader_peer_id),
 5334                });
 5335
 5336                Some(cx.spawn_in(window, async move |this, cx| {
 5337                    let response = request.await?;
 5338                    this.update(cx, |this, _| {
 5339                        let state = this
 5340                            .follower_states
 5341                            .get_mut(&leader_id)
 5342                            .context("following interrupted")?;
 5343                        state.active_view_id = response
 5344                            .active_view
 5345                            .as_ref()
 5346                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5347                        anyhow::Ok(())
 5348                    })??;
 5349                    if let Some(view) = response.active_view {
 5350                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5351                    }
 5352                    this.update_in(cx, |this, window, cx| {
 5353                        this.leader_updated(leader_id, window, cx)
 5354                    })?;
 5355                    Ok(())
 5356                }))
 5357            }
 5358            CollaboratorId::Agent => {
 5359                self.leader_updated(leader_id, window, cx)?;
 5360                Some(Task::ready(Ok(())))
 5361            }
 5362        }
 5363    }
 5364
 5365    pub fn follow_next_collaborator(
 5366        &mut self,
 5367        _: &FollowNextCollaborator,
 5368        window: &mut Window,
 5369        cx: &mut Context<Self>,
 5370    ) {
 5371        let collaborators = self.project.read(cx).collaborators();
 5372        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5373            let mut collaborators = collaborators.keys().copied();
 5374            for peer_id in collaborators.by_ref() {
 5375                if CollaboratorId::PeerId(peer_id) == leader_id {
 5376                    break;
 5377                }
 5378            }
 5379            collaborators.next().map(CollaboratorId::PeerId)
 5380        } else if let Some(last_leader_id) =
 5381            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5382        {
 5383            match last_leader_id {
 5384                CollaboratorId::PeerId(peer_id) => {
 5385                    if collaborators.contains_key(peer_id) {
 5386                        Some(*last_leader_id)
 5387                    } else {
 5388                        None
 5389                    }
 5390                }
 5391                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5392            }
 5393        } else {
 5394            None
 5395        };
 5396
 5397        let pane = self.active_pane.clone();
 5398        let Some(leader_id) = next_leader_id.or_else(|| {
 5399            Some(CollaboratorId::PeerId(
 5400                collaborators.keys().copied().next()?,
 5401            ))
 5402        }) else {
 5403            return;
 5404        };
 5405        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5406            return;
 5407        }
 5408        if let Some(task) = self.start_following(leader_id, window, cx) {
 5409            task.detach_and_log_err(cx)
 5410        }
 5411    }
 5412
 5413    pub fn follow(
 5414        &mut self,
 5415        leader_id: impl Into<CollaboratorId>,
 5416        window: &mut Window,
 5417        cx: &mut Context<Self>,
 5418    ) {
 5419        let leader_id = leader_id.into();
 5420
 5421        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5422            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5423                return;
 5424            };
 5425            let Some(remote_participant) =
 5426                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5427            else {
 5428                return;
 5429            };
 5430
 5431            let project = self.project.read(cx);
 5432
 5433            let other_project_id = match remote_participant.location {
 5434                ParticipantLocation::External => None,
 5435                ParticipantLocation::UnsharedProject => None,
 5436                ParticipantLocation::SharedProject { project_id } => {
 5437                    if Some(project_id) == project.remote_id() {
 5438                        None
 5439                    } else {
 5440                        Some(project_id)
 5441                    }
 5442                }
 5443            };
 5444
 5445            // if they are active in another project, follow there.
 5446            if let Some(project_id) = other_project_id {
 5447                let app_state = self.app_state.clone();
 5448                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5449                    .detach_and_log_err(cx);
 5450            }
 5451        }
 5452
 5453        // if you're already following, find the right pane and focus it.
 5454        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5455            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5456
 5457            return;
 5458        }
 5459
 5460        // Otherwise, follow.
 5461        if let Some(task) = self.start_following(leader_id, window, cx) {
 5462            task.detach_and_log_err(cx)
 5463        }
 5464    }
 5465
 5466    pub fn unfollow(
 5467        &mut self,
 5468        leader_id: impl Into<CollaboratorId>,
 5469        window: &mut Window,
 5470        cx: &mut Context<Self>,
 5471    ) -> Option<()> {
 5472        cx.notify();
 5473
 5474        let leader_id = leader_id.into();
 5475        let state = self.follower_states.remove(&leader_id)?;
 5476        for (_, item) in state.items_by_leader_view_id {
 5477            item.view.set_leader_id(None, window, cx);
 5478        }
 5479
 5480        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5481            let project_id = self.project.read(cx).remote_id();
 5482            let room_id = self.active_call()?.room_id(cx)?;
 5483            self.app_state
 5484                .client
 5485                .send(proto::Unfollow {
 5486                    room_id,
 5487                    project_id,
 5488                    leader_id: Some(leader_peer_id),
 5489                })
 5490                .log_err();
 5491        }
 5492
 5493        Some(())
 5494    }
 5495
 5496    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5497        self.follower_states.contains_key(&id.into())
 5498    }
 5499
 5500    fn active_item_path_changed(
 5501        &mut self,
 5502        focus_changed: bool,
 5503        window: &mut Window,
 5504        cx: &mut Context<Self>,
 5505    ) {
 5506        cx.emit(Event::ActiveItemChanged);
 5507        let active_entry = self.active_project_path(cx);
 5508        self.project.update(cx, |project, cx| {
 5509            project.set_active_path(active_entry.clone(), cx)
 5510        });
 5511
 5512        if focus_changed && let Some(project_path) = &active_entry {
 5513            let git_store_entity = self.project.read(cx).git_store().clone();
 5514            git_store_entity.update(cx, |git_store, cx| {
 5515                git_store.set_active_repo_for_path(project_path, cx);
 5516            });
 5517        }
 5518
 5519        self.update_window_title(window, cx);
 5520    }
 5521
 5522    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5523        let project = self.project().read(cx);
 5524        let mut title = String::new();
 5525
 5526        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5527            let name = {
 5528                let settings_location = SettingsLocation {
 5529                    worktree_id: worktree.read(cx).id(),
 5530                    path: RelPath::empty(),
 5531                };
 5532
 5533                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5534                match &settings.project_name {
 5535                    Some(name) => name.as_str(),
 5536                    None => worktree.read(cx).root_name_str(),
 5537                }
 5538            };
 5539            if i > 0 {
 5540                title.push_str(", ");
 5541            }
 5542            title.push_str(name);
 5543        }
 5544
 5545        if title.is_empty() {
 5546            title = "empty project".to_string();
 5547        }
 5548
 5549        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5550            let filename = path.path.file_name().or_else(|| {
 5551                Some(
 5552                    project
 5553                        .worktree_for_id(path.worktree_id, cx)?
 5554                        .read(cx)
 5555                        .root_name_str(),
 5556                )
 5557            });
 5558
 5559            if let Some(filename) = filename {
 5560                title.push_str("");
 5561                title.push_str(filename.as_ref());
 5562            }
 5563        }
 5564
 5565        if project.is_via_collab() {
 5566            title.push_str("");
 5567        } else if project.is_shared() {
 5568            title.push_str("");
 5569        }
 5570
 5571        if let Some(last_title) = self.last_window_title.as_ref()
 5572            && &title == last_title
 5573        {
 5574            return;
 5575        }
 5576        window.set_window_title(&title);
 5577        SystemWindowTabController::update_tab_title(
 5578            cx,
 5579            window.window_handle().window_id(),
 5580            SharedString::from(&title),
 5581        );
 5582        self.last_window_title = Some(title);
 5583    }
 5584
 5585    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5586        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5587        if is_edited != self.window_edited {
 5588            self.window_edited = is_edited;
 5589            window.set_window_edited(self.window_edited)
 5590        }
 5591    }
 5592
 5593    fn update_item_dirty_state(
 5594        &mut self,
 5595        item: &dyn ItemHandle,
 5596        window: &mut Window,
 5597        cx: &mut App,
 5598    ) {
 5599        let is_dirty = item.is_dirty(cx);
 5600        let item_id = item.item_id();
 5601        let was_dirty = self.dirty_items.contains_key(&item_id);
 5602        if is_dirty == was_dirty {
 5603            return;
 5604        }
 5605        if was_dirty {
 5606            self.dirty_items.remove(&item_id);
 5607            self.update_window_edited(window, cx);
 5608            return;
 5609        }
 5610
 5611        let workspace = self.weak_handle();
 5612        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5613            return;
 5614        };
 5615        let on_release_callback = Box::new(move |cx: &mut App| {
 5616            window_handle
 5617                .update(cx, |_, window, cx| {
 5618                    workspace
 5619                        .update(cx, |workspace, cx| {
 5620                            workspace.dirty_items.remove(&item_id);
 5621                            workspace.update_window_edited(window, cx)
 5622                        })
 5623                        .ok();
 5624                })
 5625                .ok();
 5626        });
 5627
 5628        let s = item.on_release(cx, on_release_callback);
 5629        self.dirty_items.insert(item_id, s);
 5630        self.update_window_edited(window, cx);
 5631    }
 5632
 5633    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5634        if self.notifications.is_empty() {
 5635            None
 5636        } else {
 5637            Some(
 5638                div()
 5639                    .absolute()
 5640                    .right_3()
 5641                    .bottom_3()
 5642                    .w_112()
 5643                    .h_full()
 5644                    .flex()
 5645                    .flex_col()
 5646                    .justify_end()
 5647                    .gap_2()
 5648                    .children(
 5649                        self.notifications
 5650                            .iter()
 5651                            .map(|(_, notification)| notification.clone().into_any()),
 5652                    ),
 5653            )
 5654        }
 5655    }
 5656
 5657    // RPC handlers
 5658
 5659    fn active_view_for_follower(
 5660        &self,
 5661        follower_project_id: Option<u64>,
 5662        window: &mut Window,
 5663        cx: &mut Context<Self>,
 5664    ) -> Option<proto::View> {
 5665        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5666        let item = item?;
 5667        let leader_id = self
 5668            .pane_for(&*item)
 5669            .and_then(|pane| self.leader_for_pane(&pane));
 5670        let leader_peer_id = match leader_id {
 5671            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5672            Some(CollaboratorId::Agent) | None => None,
 5673        };
 5674
 5675        let item_handle = item.to_followable_item_handle(cx)?;
 5676        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5677        let variant = item_handle.to_state_proto(window, cx)?;
 5678
 5679        if item_handle.is_project_item(window, cx)
 5680            && (follower_project_id.is_none()
 5681                || follower_project_id != self.project.read(cx).remote_id())
 5682        {
 5683            return None;
 5684        }
 5685
 5686        Some(proto::View {
 5687            id: id.to_proto(),
 5688            leader_id: leader_peer_id,
 5689            variant: Some(variant),
 5690            panel_id: panel_id.map(|id| id as i32),
 5691        })
 5692    }
 5693
 5694    fn handle_follow(
 5695        &mut self,
 5696        follower_project_id: Option<u64>,
 5697        window: &mut Window,
 5698        cx: &mut Context<Self>,
 5699    ) -> proto::FollowResponse {
 5700        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5701
 5702        cx.notify();
 5703        proto::FollowResponse {
 5704            views: active_view.iter().cloned().collect(),
 5705            active_view,
 5706        }
 5707    }
 5708
 5709    fn handle_update_followers(
 5710        &mut self,
 5711        leader_id: PeerId,
 5712        message: proto::UpdateFollowers,
 5713        _window: &mut Window,
 5714        _cx: &mut Context<Self>,
 5715    ) {
 5716        self.leader_updates_tx
 5717            .unbounded_send((leader_id, message))
 5718            .ok();
 5719    }
 5720
 5721    async fn process_leader_update(
 5722        this: &WeakEntity<Self>,
 5723        leader_id: PeerId,
 5724        update: proto::UpdateFollowers,
 5725        cx: &mut AsyncWindowContext,
 5726    ) -> Result<()> {
 5727        match update.variant.context("invalid update")? {
 5728            proto::update_followers::Variant::CreateView(view) => {
 5729                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5730                let should_add_view = this.update(cx, |this, _| {
 5731                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5732                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5733                    } else {
 5734                        anyhow::Ok(false)
 5735                    }
 5736                })??;
 5737
 5738                if should_add_view {
 5739                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5740                }
 5741            }
 5742            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5743                let should_add_view = this.update(cx, |this, _| {
 5744                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5745                        state.active_view_id = update_active_view
 5746                            .view
 5747                            .as_ref()
 5748                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5749
 5750                        if state.active_view_id.is_some_and(|view_id| {
 5751                            !state.items_by_leader_view_id.contains_key(&view_id)
 5752                        }) {
 5753                            anyhow::Ok(true)
 5754                        } else {
 5755                            anyhow::Ok(false)
 5756                        }
 5757                    } else {
 5758                        anyhow::Ok(false)
 5759                    }
 5760                })??;
 5761
 5762                if should_add_view && let Some(view) = update_active_view.view {
 5763                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5764                }
 5765            }
 5766            proto::update_followers::Variant::UpdateView(update_view) => {
 5767                let variant = update_view.variant.context("missing update view variant")?;
 5768                let id = update_view.id.context("missing update view id")?;
 5769                let mut tasks = Vec::new();
 5770                this.update_in(cx, |this, window, cx| {
 5771                    let project = this.project.clone();
 5772                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5773                        let view_id = ViewId::from_proto(id.clone())?;
 5774                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5775                            tasks.push(item.view.apply_update_proto(
 5776                                &project,
 5777                                variant.clone(),
 5778                                window,
 5779                                cx,
 5780                            ));
 5781                        }
 5782                    }
 5783                    anyhow::Ok(())
 5784                })??;
 5785                try_join_all(tasks).await.log_err();
 5786            }
 5787        }
 5788        this.update_in(cx, |this, window, cx| {
 5789            this.leader_updated(leader_id, window, cx)
 5790        })?;
 5791        Ok(())
 5792    }
 5793
 5794    async fn add_view_from_leader(
 5795        this: WeakEntity<Self>,
 5796        leader_id: PeerId,
 5797        view: &proto::View,
 5798        cx: &mut AsyncWindowContext,
 5799    ) -> Result<()> {
 5800        let this = this.upgrade().context("workspace dropped")?;
 5801
 5802        let Some(id) = view.id.clone() else {
 5803            anyhow::bail!("no id for view");
 5804        };
 5805        let id = ViewId::from_proto(id)?;
 5806        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5807
 5808        let pane = this.update(cx, |this, _cx| {
 5809            let state = this
 5810                .follower_states
 5811                .get(&leader_id.into())
 5812                .context("stopped following")?;
 5813            anyhow::Ok(state.pane().clone())
 5814        })?;
 5815        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5816            let client = this.read(cx).client().clone();
 5817            pane.items().find_map(|item| {
 5818                let item = item.to_followable_item_handle(cx)?;
 5819                if item.remote_id(&client, window, cx) == Some(id) {
 5820                    Some(item)
 5821                } else {
 5822                    None
 5823                }
 5824            })
 5825        })?;
 5826        let item = if let Some(existing_item) = existing_item {
 5827            existing_item
 5828        } else {
 5829            let variant = view.variant.clone();
 5830            anyhow::ensure!(variant.is_some(), "missing view variant");
 5831
 5832            let task = cx.update(|window, cx| {
 5833                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5834            })?;
 5835
 5836            let Some(task) = task else {
 5837                anyhow::bail!(
 5838                    "failed to construct view from leader (maybe from a different version of zed?)"
 5839                );
 5840            };
 5841
 5842            let mut new_item = task.await?;
 5843            pane.update_in(cx, |pane, window, cx| {
 5844                let mut item_to_remove = None;
 5845                for (ix, item) in pane.items().enumerate() {
 5846                    if let Some(item) = item.to_followable_item_handle(cx) {
 5847                        match new_item.dedup(item.as_ref(), window, cx) {
 5848                            Some(item::Dedup::KeepExisting) => {
 5849                                new_item =
 5850                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5851                                break;
 5852                            }
 5853                            Some(item::Dedup::ReplaceExisting) => {
 5854                                item_to_remove = Some((ix, item.item_id()));
 5855                                break;
 5856                            }
 5857                            None => {}
 5858                        }
 5859                    }
 5860                }
 5861
 5862                if let Some((ix, id)) = item_to_remove {
 5863                    pane.remove_item(id, false, false, window, cx);
 5864                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5865                }
 5866            })?;
 5867
 5868            new_item
 5869        };
 5870
 5871        this.update_in(cx, |this, window, cx| {
 5872            let state = this.follower_states.get_mut(&leader_id.into())?;
 5873            item.set_leader_id(Some(leader_id.into()), window, cx);
 5874            state.items_by_leader_view_id.insert(
 5875                id,
 5876                FollowerView {
 5877                    view: item,
 5878                    location: panel_id,
 5879                },
 5880            );
 5881
 5882            Some(())
 5883        })
 5884        .context("no follower state")?;
 5885
 5886        Ok(())
 5887    }
 5888
 5889    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5890        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5891            return;
 5892        };
 5893
 5894        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5895            let buffer_entity_id = agent_location.buffer.entity_id();
 5896            let view_id = ViewId {
 5897                creator: CollaboratorId::Agent,
 5898                id: buffer_entity_id.as_u64(),
 5899            };
 5900            follower_state.active_view_id = Some(view_id);
 5901
 5902            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5903                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5904                hash_map::Entry::Vacant(entry) => {
 5905                    let existing_view =
 5906                        follower_state
 5907                            .center_pane
 5908                            .read(cx)
 5909                            .items()
 5910                            .find_map(|item| {
 5911                                let item = item.to_followable_item_handle(cx)?;
 5912                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5913                                    && item.project_item_model_ids(cx).as_slice()
 5914                                        == [buffer_entity_id]
 5915                                {
 5916                                    Some(item)
 5917                                } else {
 5918                                    None
 5919                                }
 5920                            });
 5921                    let view = existing_view.or_else(|| {
 5922                        agent_location.buffer.upgrade().and_then(|buffer| {
 5923                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 5924                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 5925                            })?
 5926                            .to_followable_item_handle(cx)
 5927                        })
 5928                    });
 5929
 5930                    view.map(|view| {
 5931                        entry.insert(FollowerView {
 5932                            view,
 5933                            location: None,
 5934                        })
 5935                    })
 5936                }
 5937            };
 5938
 5939            if let Some(item) = item {
 5940                item.view
 5941                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 5942                item.view
 5943                    .update_agent_location(agent_location.position, window, cx);
 5944            }
 5945        } else {
 5946            follower_state.active_view_id = None;
 5947        }
 5948
 5949        self.leader_updated(CollaboratorId::Agent, window, cx);
 5950    }
 5951
 5952    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 5953        let mut is_project_item = true;
 5954        let mut update = proto::UpdateActiveView::default();
 5955        if window.is_window_active() {
 5956            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 5957
 5958            if let Some(item) = active_item
 5959                && item.item_focus_handle(cx).contains_focused(window, cx)
 5960            {
 5961                let leader_id = self
 5962                    .pane_for(&*item)
 5963                    .and_then(|pane| self.leader_for_pane(&pane));
 5964                let leader_peer_id = match leader_id {
 5965                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5966                    Some(CollaboratorId::Agent) | None => None,
 5967                };
 5968
 5969                if let Some(item) = item.to_followable_item_handle(cx) {
 5970                    let id = item
 5971                        .remote_id(&self.app_state.client, window, cx)
 5972                        .map(|id| id.to_proto());
 5973
 5974                    if let Some(id) = id
 5975                        && let Some(variant) = item.to_state_proto(window, cx)
 5976                    {
 5977                        let view = Some(proto::View {
 5978                            id,
 5979                            leader_id: leader_peer_id,
 5980                            variant: Some(variant),
 5981                            panel_id: panel_id.map(|id| id as i32),
 5982                        });
 5983
 5984                        is_project_item = item.is_project_item(window, cx);
 5985                        update = proto::UpdateActiveView { view };
 5986                    };
 5987                }
 5988            }
 5989        }
 5990
 5991        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 5992        if active_view_id != self.last_active_view_id.as_ref() {
 5993            self.last_active_view_id = active_view_id.cloned();
 5994            self.update_followers(
 5995                is_project_item,
 5996                proto::update_followers::Variant::UpdateActiveView(update),
 5997                window,
 5998                cx,
 5999            );
 6000        }
 6001    }
 6002
 6003    fn active_item_for_followers(
 6004        &self,
 6005        window: &mut Window,
 6006        cx: &mut App,
 6007    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 6008        let mut active_item = None;
 6009        let mut panel_id = None;
 6010        for dock in self.all_docks() {
 6011            if dock.focus_handle(cx).contains_focused(window, cx)
 6012                && let Some(panel) = dock.read(cx).active_panel()
 6013                && let Some(pane) = panel.pane(cx)
 6014                && let Some(item) = pane.read(cx).active_item()
 6015            {
 6016                active_item = Some(item);
 6017                panel_id = panel.remote_id();
 6018                break;
 6019            }
 6020        }
 6021
 6022        if active_item.is_none() {
 6023            active_item = self.active_pane().read(cx).active_item();
 6024        }
 6025        (active_item, panel_id)
 6026    }
 6027
 6028    fn update_followers(
 6029        &self,
 6030        project_only: bool,
 6031        update: proto::update_followers::Variant,
 6032        _: &mut Window,
 6033        cx: &mut App,
 6034    ) -> Option<()> {
 6035        // If this update only applies to for followers in the current project,
 6036        // then skip it unless this project is shared. If it applies to all
 6037        // followers, regardless of project, then set `project_id` to none,
 6038        // indicating that it goes to all followers.
 6039        let project_id = if project_only {
 6040            Some(self.project.read(cx).remote_id()?)
 6041        } else {
 6042            None
 6043        };
 6044        self.app_state().workspace_store.update(cx, |store, cx| {
 6045            store.update_followers(project_id, update, cx)
 6046        })
 6047    }
 6048
 6049    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 6050        self.follower_states.iter().find_map(|(leader_id, state)| {
 6051            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 6052                Some(*leader_id)
 6053            } else {
 6054                None
 6055            }
 6056        })
 6057    }
 6058
 6059    fn leader_updated(
 6060        &mut self,
 6061        leader_id: impl Into<CollaboratorId>,
 6062        window: &mut Window,
 6063        cx: &mut Context<Self>,
 6064    ) -> Option<Box<dyn ItemHandle>> {
 6065        cx.notify();
 6066
 6067        let leader_id = leader_id.into();
 6068        let (panel_id, item) = match leader_id {
 6069            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 6070            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 6071        };
 6072
 6073        let state = self.follower_states.get(&leader_id)?;
 6074        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 6075        let pane;
 6076        if let Some(panel_id) = panel_id {
 6077            pane = self
 6078                .activate_panel_for_proto_id(panel_id, window, cx)?
 6079                .pane(cx)?;
 6080            let state = self.follower_states.get_mut(&leader_id)?;
 6081            state.dock_pane = Some(pane.clone());
 6082        } else {
 6083            pane = state.center_pane.clone();
 6084            let state = self.follower_states.get_mut(&leader_id)?;
 6085            if let Some(dock_pane) = state.dock_pane.take() {
 6086                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 6087            }
 6088        }
 6089
 6090        pane.update(cx, |pane, cx| {
 6091            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 6092            if let Some(index) = pane.index_for_item(item.as_ref()) {
 6093                pane.activate_item(index, false, false, window, cx);
 6094            } else {
 6095                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 6096            }
 6097
 6098            if focus_active_item {
 6099                pane.focus_active_item(window, cx)
 6100            }
 6101        });
 6102
 6103        Some(item)
 6104    }
 6105
 6106    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 6107        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 6108        let active_view_id = state.active_view_id?;
 6109        Some(
 6110            state
 6111                .items_by_leader_view_id
 6112                .get(&active_view_id)?
 6113                .view
 6114                .boxed_clone(),
 6115        )
 6116    }
 6117
 6118    fn active_item_for_peer(
 6119        &self,
 6120        peer_id: PeerId,
 6121        window: &mut Window,
 6122        cx: &mut Context<Self>,
 6123    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 6124        let call = self.active_call()?;
 6125        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 6126        let leader_in_this_app;
 6127        let leader_in_this_project;
 6128        match participant.location {
 6129            ParticipantLocation::SharedProject { project_id } => {
 6130                leader_in_this_app = true;
 6131                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 6132            }
 6133            ParticipantLocation::UnsharedProject => {
 6134                leader_in_this_app = true;
 6135                leader_in_this_project = false;
 6136            }
 6137            ParticipantLocation::External => {
 6138                leader_in_this_app = false;
 6139                leader_in_this_project = false;
 6140            }
 6141        };
 6142        let state = self.follower_states.get(&peer_id.into())?;
 6143        let mut item_to_activate = None;
 6144        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 6145            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 6146                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 6147            {
 6148                item_to_activate = Some((item.location, item.view.boxed_clone()));
 6149            }
 6150        } else if let Some(shared_screen) =
 6151            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 6152        {
 6153            item_to_activate = Some((None, Box::new(shared_screen)));
 6154        }
 6155        item_to_activate
 6156    }
 6157
 6158    fn shared_screen_for_peer(
 6159        &self,
 6160        peer_id: PeerId,
 6161        pane: &Entity<Pane>,
 6162        window: &mut Window,
 6163        cx: &mut App,
 6164    ) -> Option<Entity<SharedScreen>> {
 6165        self.active_call()?
 6166            .create_shared_screen(peer_id, pane, window, cx)
 6167    }
 6168
 6169    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6170        if window.is_window_active() {
 6171            self.update_active_view_for_followers(window, cx);
 6172
 6173            if let Some(database_id) = self.database_id {
 6174                let db = WorkspaceDb::global(cx);
 6175                cx.background_spawn(async move { db.update_timestamp(database_id).await })
 6176                    .detach();
 6177            }
 6178        } else {
 6179            for pane in &self.panes {
 6180                pane.update(cx, |pane, cx| {
 6181                    if let Some(item) = pane.active_item() {
 6182                        item.workspace_deactivated(window, cx);
 6183                    }
 6184                    for item in pane.items() {
 6185                        if matches!(
 6186                            item.workspace_settings(cx).autosave,
 6187                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6188                        ) {
 6189                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6190                                .detach_and_log_err(cx);
 6191                        }
 6192                    }
 6193                });
 6194            }
 6195        }
 6196    }
 6197
 6198    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6199        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6200    }
 6201
 6202    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6203        self.active_call.as_ref().map(|(call, _)| call.clone())
 6204    }
 6205
 6206    fn on_active_call_event(
 6207        &mut self,
 6208        event: &ActiveCallEvent,
 6209        window: &mut Window,
 6210        cx: &mut Context<Self>,
 6211    ) {
 6212        match event {
 6213            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6214            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6215                self.leader_updated(participant_id, window, cx);
 6216            }
 6217        }
 6218    }
 6219
 6220    pub fn database_id(&self) -> Option<WorkspaceId> {
 6221        self.database_id
 6222    }
 6223
 6224    #[cfg(any(test, feature = "test-support"))]
 6225    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6226        self.database_id = Some(id);
 6227    }
 6228
 6229    pub fn session_id(&self) -> Option<String> {
 6230        self.session_id.clone()
 6231    }
 6232
 6233    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6234        let Some(display) = window.display(cx) else {
 6235            return Task::ready(());
 6236        };
 6237        let Ok(display_uuid) = display.uuid() else {
 6238            return Task::ready(());
 6239        };
 6240
 6241        let window_bounds = window.inner_window_bounds();
 6242        let database_id = self.database_id;
 6243        let has_paths = !self.root_paths(cx).is_empty();
 6244        let db = WorkspaceDb::global(cx);
 6245        let kvp = db::kvp::KeyValueStore::global(cx);
 6246
 6247        cx.background_executor().spawn(async move {
 6248            if !has_paths {
 6249                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6250                    .await
 6251                    .log_err();
 6252            }
 6253            if let Some(database_id) = database_id {
 6254                db.set_window_open_status(
 6255                    database_id,
 6256                    SerializedWindowBounds(window_bounds),
 6257                    display_uuid,
 6258                )
 6259                .await
 6260                .log_err();
 6261            } else {
 6262                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6263                    .await
 6264                    .log_err();
 6265            }
 6266        })
 6267    }
 6268
 6269    /// Bypass the 200ms serialization throttle and write workspace state to
 6270    /// the DB immediately. Returns a task the caller can await to ensure the
 6271    /// write completes. Used by the quit handler so the most recent state
 6272    /// isn't lost to a pending throttle timer when the process exits.
 6273    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6274        self._schedule_serialize_workspace.take();
 6275        self._serialize_workspace_task.take();
 6276        self.bounds_save_task_queued.take();
 6277
 6278        let bounds_task = self.save_window_bounds(window, cx);
 6279        let serialize_task = self.serialize_workspace_internal(window, cx);
 6280        cx.spawn(async move |_| {
 6281            bounds_task.await;
 6282            serialize_task.await;
 6283        })
 6284    }
 6285
 6286    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6287        let project = self.project().read(cx);
 6288        project
 6289            .visible_worktrees(cx)
 6290            .map(|worktree| worktree.read(cx).abs_path())
 6291            .collect::<Vec<_>>()
 6292    }
 6293
 6294    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6295        match member {
 6296            Member::Axis(PaneAxis { members, .. }) => {
 6297                for child in members.iter() {
 6298                    self.remove_panes(child.clone(), window, cx)
 6299                }
 6300            }
 6301            Member::Pane(pane) => {
 6302                self.force_remove_pane(&pane, &None, window, cx);
 6303            }
 6304        }
 6305    }
 6306
 6307    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6308        self.session_id.take();
 6309        self.serialize_workspace_internal(window, cx)
 6310    }
 6311
 6312    fn force_remove_pane(
 6313        &mut self,
 6314        pane: &Entity<Pane>,
 6315        focus_on: &Option<Entity<Pane>>,
 6316        window: &mut Window,
 6317        cx: &mut Context<Workspace>,
 6318    ) {
 6319        self.panes.retain(|p| p != pane);
 6320        if let Some(focus_on) = focus_on {
 6321            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6322        } else if self.active_pane() == pane {
 6323            self.panes
 6324                .last()
 6325                .unwrap()
 6326                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6327        }
 6328        if self.last_active_center_pane == Some(pane.downgrade()) {
 6329            self.last_active_center_pane = None;
 6330        }
 6331        cx.notify();
 6332    }
 6333
 6334    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6335        if self._schedule_serialize_workspace.is_none() {
 6336            self._schedule_serialize_workspace =
 6337                Some(cx.spawn_in(window, async move |this, cx| {
 6338                    cx.background_executor()
 6339                        .timer(SERIALIZATION_THROTTLE_TIME)
 6340                        .await;
 6341                    this.update_in(cx, |this, window, cx| {
 6342                        this._serialize_workspace_task =
 6343                            Some(this.serialize_workspace_internal(window, cx));
 6344                        this._schedule_serialize_workspace.take();
 6345                    })
 6346                    .log_err();
 6347                }));
 6348        }
 6349    }
 6350
 6351    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6352        let Some(database_id) = self.database_id() else {
 6353            return Task::ready(());
 6354        };
 6355
 6356        fn serialize_pane_handle(
 6357            pane_handle: &Entity<Pane>,
 6358            window: &mut Window,
 6359            cx: &mut App,
 6360        ) -> SerializedPane {
 6361            let (items, active, pinned_count) = {
 6362                let pane = pane_handle.read(cx);
 6363                let active_item_id = pane.active_item().map(|item| item.item_id());
 6364                (
 6365                    pane.items()
 6366                        .filter_map(|handle| {
 6367                            let handle = handle.to_serializable_item_handle(cx)?;
 6368
 6369                            Some(SerializedItem {
 6370                                kind: Arc::from(handle.serialized_item_kind()),
 6371                                item_id: handle.item_id().as_u64(),
 6372                                active: Some(handle.item_id()) == active_item_id,
 6373                                preview: pane.is_active_preview_item(handle.item_id()),
 6374                            })
 6375                        })
 6376                        .collect::<Vec<_>>(),
 6377                    pane.has_focus(window, cx),
 6378                    pane.pinned_count(),
 6379                )
 6380            };
 6381
 6382            SerializedPane::new(items, active, pinned_count)
 6383        }
 6384
 6385        fn build_serialized_pane_group(
 6386            pane_group: &Member,
 6387            window: &mut Window,
 6388            cx: &mut App,
 6389        ) -> SerializedPaneGroup {
 6390            match pane_group {
 6391                Member::Axis(PaneAxis {
 6392                    axis,
 6393                    members,
 6394                    flexes,
 6395                    bounding_boxes: _,
 6396                }) => SerializedPaneGroup::Group {
 6397                    axis: SerializedAxis(*axis),
 6398                    children: members
 6399                        .iter()
 6400                        .map(|member| build_serialized_pane_group(member, window, cx))
 6401                        .collect::<Vec<_>>(),
 6402                    flexes: Some(flexes.lock().clone()),
 6403                },
 6404                Member::Pane(pane_handle) => {
 6405                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6406                }
 6407            }
 6408        }
 6409
 6410        fn build_serialized_docks(
 6411            this: &Workspace,
 6412            window: &mut Window,
 6413            cx: &mut App,
 6414        ) -> DockStructure {
 6415            this.capture_dock_state(window, cx)
 6416        }
 6417
 6418        match self.workspace_location(cx) {
 6419            WorkspaceLocation::Location(location, paths) => {
 6420                let breakpoints = self.project.update(cx, |project, cx| {
 6421                    project
 6422                        .breakpoint_store()
 6423                        .read(cx)
 6424                        .all_source_breakpoints(cx)
 6425                });
 6426                let user_toolchains = self
 6427                    .project
 6428                    .read(cx)
 6429                    .user_toolchains(cx)
 6430                    .unwrap_or_default();
 6431
 6432                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6433                let docks = build_serialized_docks(self, window, cx);
 6434                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6435
 6436                let serialized_workspace = SerializedWorkspace {
 6437                    id: database_id,
 6438                    location,
 6439                    paths,
 6440                    center_group,
 6441                    window_bounds,
 6442                    display: Default::default(),
 6443                    docks,
 6444                    centered_layout: self.centered_layout,
 6445                    session_id: self.session_id.clone(),
 6446                    breakpoints,
 6447                    window_id: Some(window.window_handle().window_id().as_u64()),
 6448                    user_toolchains,
 6449                };
 6450
 6451                let db = WorkspaceDb::global(cx);
 6452                window.spawn(cx, async move |_| {
 6453                    db.save_workspace(serialized_workspace).await;
 6454                })
 6455            }
 6456            WorkspaceLocation::DetachFromSession => {
 6457                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6458                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6459                // Save dock state for empty local workspaces
 6460                let docks = build_serialized_docks(self, window, cx);
 6461                let db = WorkspaceDb::global(cx);
 6462                let kvp = db::kvp::KeyValueStore::global(cx);
 6463                window.spawn(cx, async move |_| {
 6464                    db.set_window_open_status(
 6465                        database_id,
 6466                        window_bounds,
 6467                        display.unwrap_or_default(),
 6468                    )
 6469                    .await
 6470                    .log_err();
 6471                    db.set_session_id(database_id, None).await.log_err();
 6472                    persistence::write_default_dock_state(&kvp, docks)
 6473                        .await
 6474                        .log_err();
 6475                })
 6476            }
 6477            WorkspaceLocation::None => {
 6478                // Save dock state for empty non-local workspaces
 6479                let docks = build_serialized_docks(self, window, cx);
 6480                let kvp = db::kvp::KeyValueStore::global(cx);
 6481                window.spawn(cx, async move |_| {
 6482                    persistence::write_default_dock_state(&kvp, docks)
 6483                        .await
 6484                        .log_err();
 6485                })
 6486            }
 6487        }
 6488    }
 6489
 6490    fn has_any_items_open(&self, cx: &App) -> bool {
 6491        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6492    }
 6493
 6494    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6495        let paths = PathList::new(&self.root_paths(cx));
 6496        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6497            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6498        } else if self.project.read(cx).is_local() {
 6499            if !paths.is_empty() || self.has_any_items_open(cx) {
 6500                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6501            } else {
 6502                WorkspaceLocation::DetachFromSession
 6503            }
 6504        } else {
 6505            WorkspaceLocation::None
 6506        }
 6507    }
 6508
 6509    fn update_history(&self, cx: &mut App) {
 6510        let Some(id) = self.database_id() else {
 6511            return;
 6512        };
 6513        if !self.project.read(cx).is_local() {
 6514            return;
 6515        }
 6516        if let Some(manager) = HistoryManager::global(cx) {
 6517            let paths = PathList::new(&self.root_paths(cx));
 6518            manager.update(cx, |this, cx| {
 6519                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6520            });
 6521        }
 6522    }
 6523
 6524    async fn serialize_items(
 6525        this: &WeakEntity<Self>,
 6526        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6527        cx: &mut AsyncWindowContext,
 6528    ) -> Result<()> {
 6529        const CHUNK_SIZE: usize = 200;
 6530
 6531        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6532
 6533        while let Some(items_received) = serializable_items.next().await {
 6534            let unique_items =
 6535                items_received
 6536                    .into_iter()
 6537                    .fold(HashMap::default(), |mut acc, item| {
 6538                        acc.entry(item.item_id()).or_insert(item);
 6539                        acc
 6540                    });
 6541
 6542            // We use into_iter() here so that the references to the items are moved into
 6543            // the tasks and not kept alive while we're sleeping.
 6544            for (_, item) in unique_items.into_iter() {
 6545                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6546                    item.serialize(workspace, false, window, cx)
 6547                }) {
 6548                    cx.background_spawn(async move { task.await.log_err() })
 6549                        .detach();
 6550                }
 6551            }
 6552
 6553            cx.background_executor()
 6554                .timer(SERIALIZATION_THROTTLE_TIME)
 6555                .await;
 6556        }
 6557
 6558        Ok(())
 6559    }
 6560
 6561    pub(crate) fn enqueue_item_serialization(
 6562        &mut self,
 6563        item: Box<dyn SerializableItemHandle>,
 6564    ) -> Result<()> {
 6565        self.serializable_items_tx
 6566            .unbounded_send(item)
 6567            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6568    }
 6569
 6570    pub(crate) fn load_workspace(
 6571        serialized_workspace: SerializedWorkspace,
 6572        paths_to_open: Vec<Option<ProjectPath>>,
 6573        window: &mut Window,
 6574        cx: &mut Context<Workspace>,
 6575    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6576        cx.spawn_in(window, async move |workspace, cx| {
 6577            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6578
 6579            let mut center_group = None;
 6580            let mut center_items = None;
 6581
 6582            // Traverse the splits tree and add to things
 6583            if let Some((group, active_pane, items)) = serialized_workspace
 6584                .center_group
 6585                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6586                .await
 6587            {
 6588                center_items = Some(items);
 6589                center_group = Some((group, active_pane))
 6590            }
 6591
 6592            let mut items_by_project_path = HashMap::default();
 6593            let mut item_ids_by_kind = HashMap::default();
 6594            let mut all_deserialized_items = Vec::default();
 6595            cx.update(|_, cx| {
 6596                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6597                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6598                        item_ids_by_kind
 6599                            .entry(serializable_item_handle.serialized_item_kind())
 6600                            .or_insert(Vec::new())
 6601                            .push(item.item_id().as_u64() as ItemId);
 6602                    }
 6603
 6604                    if let Some(project_path) = item.project_path(cx) {
 6605                        items_by_project_path.insert(project_path, item.clone());
 6606                    }
 6607                    all_deserialized_items.push(item);
 6608                }
 6609            })?;
 6610
 6611            let opened_items = paths_to_open
 6612                .into_iter()
 6613                .map(|path_to_open| {
 6614                    path_to_open
 6615                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6616                })
 6617                .collect::<Vec<_>>();
 6618
 6619            // Remove old panes from workspace panes list
 6620            workspace.update_in(cx, |workspace, window, cx| {
 6621                if let Some((center_group, active_pane)) = center_group {
 6622                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6623
 6624                    // Swap workspace center group
 6625                    workspace.center = PaneGroup::with_root(center_group);
 6626                    workspace.center.set_is_center(true);
 6627                    workspace.center.mark_positions(cx);
 6628
 6629                    if let Some(active_pane) = active_pane {
 6630                        workspace.set_active_pane(&active_pane, window, cx);
 6631                        cx.focus_self(window);
 6632                    } else {
 6633                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6634                    }
 6635                }
 6636
 6637                let docks = serialized_workspace.docks;
 6638
 6639                for (dock, serialized_dock) in [
 6640                    (&mut workspace.right_dock, docks.right),
 6641                    (&mut workspace.left_dock, docks.left),
 6642                    (&mut workspace.bottom_dock, docks.bottom),
 6643                ]
 6644                .iter_mut()
 6645                {
 6646                    dock.update(cx, |dock, cx| {
 6647                        dock.serialized_dock = Some(serialized_dock.clone());
 6648                        dock.restore_state(window, cx);
 6649                    });
 6650                }
 6651
 6652                cx.notify();
 6653            })?;
 6654
 6655            let _ = project
 6656                .update(cx, |project, cx| {
 6657                    project
 6658                        .breakpoint_store()
 6659                        .update(cx, |breakpoint_store, cx| {
 6660                            breakpoint_store
 6661                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6662                        })
 6663                })
 6664                .await;
 6665
 6666            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6667            // after loading the items, we might have different items and in order to avoid
 6668            // the database filling up, we delete items that haven't been loaded now.
 6669            //
 6670            // The items that have been loaded, have been saved after they've been added to the workspace.
 6671            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6672                item_ids_by_kind
 6673                    .into_iter()
 6674                    .map(|(item_kind, loaded_items)| {
 6675                        SerializableItemRegistry::cleanup(
 6676                            item_kind,
 6677                            serialized_workspace.id,
 6678                            loaded_items,
 6679                            window,
 6680                            cx,
 6681                        )
 6682                        .log_err()
 6683                    })
 6684                    .collect::<Vec<_>>()
 6685            })?;
 6686
 6687            futures::future::join_all(clean_up_tasks).await;
 6688
 6689            workspace
 6690                .update_in(cx, |workspace, window, cx| {
 6691                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6692                    workspace.serialize_workspace_internal(window, cx).detach();
 6693
 6694                    // Ensure that we mark the window as edited if we did load dirty items
 6695                    workspace.update_window_edited(window, cx);
 6696                })
 6697                .ok();
 6698
 6699            Ok(opened_items)
 6700        })
 6701    }
 6702
 6703    pub fn key_context(&self, cx: &App) -> KeyContext {
 6704        let mut context = KeyContext::new_with_defaults();
 6705        context.add("Workspace");
 6706        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6707        if let Some(status) = self
 6708            .debugger_provider
 6709            .as_ref()
 6710            .and_then(|provider| provider.active_thread_state(cx))
 6711        {
 6712            match status {
 6713                ThreadStatus::Running | ThreadStatus::Stepping => {
 6714                    context.add("debugger_running");
 6715                }
 6716                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6717                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6718            }
 6719        }
 6720
 6721        if self.left_dock.read(cx).is_open() {
 6722            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6723                context.set("left_dock", active_panel.panel_key());
 6724            }
 6725        }
 6726
 6727        if self.right_dock.read(cx).is_open() {
 6728            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6729                context.set("right_dock", active_panel.panel_key());
 6730            }
 6731        }
 6732
 6733        if self.bottom_dock.read(cx).is_open() {
 6734            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6735                context.set("bottom_dock", active_panel.panel_key());
 6736            }
 6737        }
 6738
 6739        context
 6740    }
 6741
 6742    /// Multiworkspace uses this to add workspace action handling to itself
 6743    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6744        self.add_workspace_actions_listeners(div, window, cx)
 6745            .on_action(cx.listener(
 6746                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6747                    for action in &action_sequence.0 {
 6748                        window.dispatch_action(action.boxed_clone(), cx);
 6749                    }
 6750                },
 6751            ))
 6752            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6753            .on_action(cx.listener(Self::close_all_items_and_panes))
 6754            .on_action(cx.listener(Self::close_item_in_all_panes))
 6755            .on_action(cx.listener(Self::save_all))
 6756            .on_action(cx.listener(Self::send_keystrokes))
 6757            .on_action(cx.listener(Self::add_folder_to_project))
 6758            .on_action(cx.listener(Self::follow_next_collaborator))
 6759            .on_action(cx.listener(Self::activate_pane_at_index))
 6760            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6761            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6762            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6763            .on_action(cx.listener(Self::toggle_theme_mode))
 6764            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6765                let pane = workspace.active_pane().clone();
 6766                workspace.unfollow_in_pane(&pane, window, cx);
 6767            }))
 6768            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6769                workspace
 6770                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6771                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6772            }))
 6773            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6774                workspace
 6775                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6776                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6777            }))
 6778            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6779                workspace
 6780                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6781                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6782            }))
 6783            .on_action(
 6784                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6785                    workspace.activate_previous_pane(window, cx)
 6786                }),
 6787            )
 6788            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6789                workspace.activate_next_pane(window, cx)
 6790            }))
 6791            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6792                workspace.activate_last_pane(window, cx)
 6793            }))
 6794            .on_action(
 6795                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6796                    workspace.activate_next_window(cx)
 6797                }),
 6798            )
 6799            .on_action(
 6800                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6801                    workspace.activate_previous_window(cx)
 6802                }),
 6803            )
 6804            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6805                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6806            }))
 6807            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6808                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6809            }))
 6810            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6811                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6812            }))
 6813            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6814                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6815            }))
 6816            .on_action(cx.listener(
 6817                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6818                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6819                },
 6820            ))
 6821            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6822                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6823            }))
 6824            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6825                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6826            }))
 6827            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6828                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6829            }))
 6830            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6831                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6832            }))
 6833            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6834                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6835                    SplitDirection::Down,
 6836                    SplitDirection::Up,
 6837                    SplitDirection::Right,
 6838                    SplitDirection::Left,
 6839                ];
 6840                for dir in DIRECTION_PRIORITY {
 6841                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6842                        workspace.swap_pane_in_direction(dir, cx);
 6843                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6844                        break;
 6845                    }
 6846                }
 6847            }))
 6848            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6849                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6850            }))
 6851            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6852                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6853            }))
 6854            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6855                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6856            }))
 6857            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6858                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6859            }))
 6860            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6861                this.toggle_dock(DockPosition::Left, window, cx);
 6862            }))
 6863            .on_action(cx.listener(
 6864                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6865                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6866                },
 6867            ))
 6868            .on_action(cx.listener(
 6869                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6870                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6871                },
 6872            ))
 6873            .on_action(cx.listener(
 6874                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6875                    if !workspace.close_active_dock(window, cx) {
 6876                        cx.propagate();
 6877                    }
 6878                },
 6879            ))
 6880            .on_action(
 6881                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6882                    workspace.close_all_docks(window, cx);
 6883                }),
 6884            )
 6885            .on_action(cx.listener(Self::toggle_all_docks))
 6886            .on_action(cx.listener(
 6887                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6888                    workspace.clear_all_notifications(cx);
 6889                },
 6890            ))
 6891            .on_action(cx.listener(
 6892                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6893                    workspace.clear_navigation_history(window, cx);
 6894                },
 6895            ))
 6896            .on_action(cx.listener(
 6897                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6898                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6899                        workspace.suppress_notification(&notification_id, cx);
 6900                    }
 6901                },
 6902            ))
 6903            .on_action(cx.listener(
 6904                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6905                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6906                },
 6907            ))
 6908            .on_action(
 6909                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6910                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6911                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6912                            trusted_worktrees.clear_trusted_paths()
 6913                        });
 6914                        let db = WorkspaceDb::global(cx);
 6915                        cx.spawn(async move |_, cx| {
 6916                            if db.clear_trusted_worktrees().await.log_err().is_some() {
 6917                                cx.update(|cx| reload(cx));
 6918                            }
 6919                        })
 6920                        .detach();
 6921                    }
 6922                }),
 6923            )
 6924            .on_action(cx.listener(
 6925                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 6926                    workspace.reopen_closed_item(window, cx).detach();
 6927                },
 6928            ))
 6929            .on_action(cx.listener(
 6930                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 6931                    for dock in workspace.all_docks() {
 6932                        if dock.focus_handle(cx).contains_focused(window, cx) {
 6933                            let panel = dock.read(cx).active_panel().cloned();
 6934                            if let Some(panel) = panel {
 6935                                dock.update(cx, |dock, cx| {
 6936                                    dock.set_panel_size_state(
 6937                                        panel.as_ref(),
 6938                                        dock::PanelSizeState::default(),
 6939                                        cx,
 6940                                    );
 6941                                });
 6942                            }
 6943                            return;
 6944                        }
 6945                    }
 6946                },
 6947            ))
 6948            .on_action(cx.listener(
 6949                |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
 6950                    for dock in workspace.all_docks() {
 6951                        let panel = dock.read(cx).visible_panel().cloned();
 6952                        if let Some(panel) = panel {
 6953                            dock.update(cx, |dock, cx| {
 6954                                dock.set_panel_size_state(
 6955                                    panel.as_ref(),
 6956                                    dock::PanelSizeState::default(),
 6957                                    cx,
 6958                                );
 6959                            });
 6960                        }
 6961                    }
 6962                },
 6963            ))
 6964            .on_action(cx.listener(
 6965                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 6966                    adjust_active_dock_size_by_px(
 6967                        px_with_ui_font_fallback(act.px, cx),
 6968                        workspace,
 6969                        window,
 6970                        cx,
 6971                    );
 6972                },
 6973            ))
 6974            .on_action(cx.listener(
 6975                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 6976                    adjust_active_dock_size_by_px(
 6977                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6978                        workspace,
 6979                        window,
 6980                        cx,
 6981                    );
 6982                },
 6983            ))
 6984            .on_action(cx.listener(
 6985                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 6986                    adjust_open_docks_size_by_px(
 6987                        px_with_ui_font_fallback(act.px, cx),
 6988                        workspace,
 6989                        window,
 6990                        cx,
 6991                    );
 6992                },
 6993            ))
 6994            .on_action(cx.listener(
 6995                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 6996                    adjust_open_docks_size_by_px(
 6997                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6998                        workspace,
 6999                        window,
 7000                        cx,
 7001                    );
 7002                },
 7003            ))
 7004            .on_action(cx.listener(Workspace::toggle_centered_layout))
 7005            .on_action(cx.listener(
 7006                |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
 7007                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7008                        let dock = active_dock.read(cx);
 7009                        if let Some(active_panel) = dock.active_panel() {
 7010                            if active_panel.pane(cx).is_none() {
 7011                                let mut recent_pane: Option<Entity<Pane>> = None;
 7012                                let mut recent_timestamp = 0;
 7013                                for pane_handle in workspace.panes() {
 7014                                    let pane = pane_handle.read(cx);
 7015                                    for entry in pane.activation_history() {
 7016                                        if entry.timestamp > recent_timestamp {
 7017                                            recent_timestamp = entry.timestamp;
 7018                                            recent_pane = Some(pane_handle.clone());
 7019                                        }
 7020                                    }
 7021                                }
 7022
 7023                                if let Some(pane) = recent_pane {
 7024                                    pane.update(cx, |pane, cx| {
 7025                                        let current_index = pane.active_item_index();
 7026                                        let items_len = pane.items_len();
 7027                                        if items_len > 0 {
 7028                                            let next_index = if current_index + 1 < items_len {
 7029                                                current_index + 1
 7030                                            } else {
 7031                                                0
 7032                                            };
 7033                                            pane.activate_item(
 7034                                                next_index, false, false, window, cx,
 7035                                            );
 7036                                        }
 7037                                    });
 7038                                    return;
 7039                                }
 7040                            }
 7041                        }
 7042                    }
 7043                    cx.propagate();
 7044                },
 7045            ))
 7046            .on_action(cx.listener(
 7047                |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
 7048                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7049                        let dock = active_dock.read(cx);
 7050                        if let Some(active_panel) = dock.active_panel() {
 7051                            if active_panel.pane(cx).is_none() {
 7052                                let mut recent_pane: Option<Entity<Pane>> = None;
 7053                                let mut recent_timestamp = 0;
 7054                                for pane_handle in workspace.panes() {
 7055                                    let pane = pane_handle.read(cx);
 7056                                    for entry in pane.activation_history() {
 7057                                        if entry.timestamp > recent_timestamp {
 7058                                            recent_timestamp = entry.timestamp;
 7059                                            recent_pane = Some(pane_handle.clone());
 7060                                        }
 7061                                    }
 7062                                }
 7063
 7064                                if let Some(pane) = recent_pane {
 7065                                    pane.update(cx, |pane, cx| {
 7066                                        let current_index = pane.active_item_index();
 7067                                        let items_len = pane.items_len();
 7068                                        if items_len > 0 {
 7069                                            let prev_index = if current_index > 0 {
 7070                                                current_index - 1
 7071                                            } else {
 7072                                                items_len.saturating_sub(1)
 7073                                            };
 7074                                            pane.activate_item(
 7075                                                prev_index, false, false, window, cx,
 7076                                            );
 7077                                        }
 7078                                    });
 7079                                    return;
 7080                                }
 7081                            }
 7082                        }
 7083                    }
 7084                    cx.propagate();
 7085                },
 7086            ))
 7087            .on_action(cx.listener(
 7088                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 7089                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7090                        let dock = active_dock.read(cx);
 7091                        if let Some(active_panel) = dock.active_panel() {
 7092                            if active_panel.pane(cx).is_none() {
 7093                                let active_pane = workspace.active_pane().clone();
 7094                                active_pane.update(cx, |pane, cx| {
 7095                                    pane.close_active_item(action, window, cx)
 7096                                        .detach_and_log_err(cx);
 7097                                });
 7098                                return;
 7099                            }
 7100                        }
 7101                    }
 7102                    cx.propagate();
 7103                },
 7104            ))
 7105            .on_action(
 7106                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 7107                    let pane = workspace.active_pane().clone();
 7108                    if let Some(item) = pane.read(cx).active_item() {
 7109                        item.toggle_read_only(window, cx);
 7110                    }
 7111                }),
 7112            )
 7113            .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
 7114                workspace.focus_center_pane(window, cx);
 7115            }))
 7116            .on_action(cx.listener(Workspace::cancel))
 7117    }
 7118
 7119    #[cfg(any(test, feature = "test-support"))]
 7120    pub fn set_random_database_id(&mut self) {
 7121        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 7122    }
 7123
 7124    #[cfg(any(test, feature = "test-support"))]
 7125    pub(crate) fn test_new(
 7126        project: Entity<Project>,
 7127        window: &mut Window,
 7128        cx: &mut Context<Self>,
 7129    ) -> Self {
 7130        use node_runtime::NodeRuntime;
 7131        use session::Session;
 7132
 7133        let client = project.read(cx).client();
 7134        let user_store = project.read(cx).user_store();
 7135        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 7136        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 7137        window.activate_window();
 7138        let app_state = Arc::new(AppState {
 7139            languages: project.read(cx).languages().clone(),
 7140            workspace_store,
 7141            client,
 7142            user_store,
 7143            fs: project.read(cx).fs().clone(),
 7144            build_window_options: |_, _| Default::default(),
 7145            node_runtime: NodeRuntime::unavailable(),
 7146            session,
 7147        });
 7148        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 7149        workspace
 7150            .active_pane
 7151            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 7152        workspace
 7153    }
 7154
 7155    pub fn register_action<A: Action>(
 7156        &mut self,
 7157        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 7158    ) -> &mut Self {
 7159        let callback = Arc::new(callback);
 7160
 7161        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 7162            let callback = callback.clone();
 7163            div.on_action(cx.listener(move |workspace, event, window, cx| {
 7164                (callback)(workspace, event, window, cx)
 7165            }))
 7166        }));
 7167        self
 7168    }
 7169    pub fn register_action_renderer(
 7170        &mut self,
 7171        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 7172    ) -> &mut Self {
 7173        self.workspace_actions.push(Box::new(callback));
 7174        self
 7175    }
 7176
 7177    fn add_workspace_actions_listeners(
 7178        &self,
 7179        mut div: Div,
 7180        window: &mut Window,
 7181        cx: &mut Context<Self>,
 7182    ) -> Div {
 7183        for action in self.workspace_actions.iter() {
 7184            div = (action)(div, self, window, cx)
 7185        }
 7186        div
 7187    }
 7188
 7189    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 7190        self.modal_layer.read(cx).has_active_modal()
 7191    }
 7192
 7193    pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
 7194        self.modal_layer
 7195            .read(cx)
 7196            .is_active_modal_command_palette(cx)
 7197    }
 7198
 7199    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7200        self.modal_layer.read(cx).active_modal()
 7201    }
 7202
 7203    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7204    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7205    /// If no modal is active, the new modal will be shown.
 7206    ///
 7207    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7208    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7209    /// will not be shown.
 7210    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7211    where
 7212        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7213    {
 7214        self.modal_layer.update(cx, |modal_layer, cx| {
 7215            modal_layer.toggle_modal(window, cx, build)
 7216        })
 7217    }
 7218
 7219    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7220        self.modal_layer
 7221            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7222    }
 7223
 7224    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7225        self.toast_layer
 7226            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7227    }
 7228
 7229    pub fn toggle_centered_layout(
 7230        &mut self,
 7231        _: &ToggleCenteredLayout,
 7232        _: &mut Window,
 7233        cx: &mut Context<Self>,
 7234    ) {
 7235        self.centered_layout = !self.centered_layout;
 7236        if let Some(database_id) = self.database_id() {
 7237            let db = WorkspaceDb::global(cx);
 7238            let centered_layout = self.centered_layout;
 7239            cx.background_spawn(async move {
 7240                db.set_centered_layout(database_id, centered_layout).await
 7241            })
 7242            .detach_and_log_err(cx);
 7243        }
 7244        cx.notify();
 7245    }
 7246
 7247    fn adjust_padding(padding: Option<f32>) -> f32 {
 7248        padding
 7249            .unwrap_or(CenteredPaddingSettings::default().0)
 7250            .clamp(
 7251                CenteredPaddingSettings::MIN_PADDING,
 7252                CenteredPaddingSettings::MAX_PADDING,
 7253            )
 7254    }
 7255
 7256    fn render_dock(
 7257        &self,
 7258        position: DockPosition,
 7259        dock: &Entity<Dock>,
 7260        window: &mut Window,
 7261        cx: &mut App,
 7262    ) -> Option<Div> {
 7263        if self.zoomed_position == Some(position) {
 7264            return None;
 7265        }
 7266
 7267        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7268            let pane = panel.pane(cx)?;
 7269            let follower_states = &self.follower_states;
 7270            leader_border_for_pane(follower_states, &pane, window, cx)
 7271        });
 7272
 7273        let mut container = div()
 7274            .flex()
 7275            .overflow_hidden()
 7276            .flex_none()
 7277            .child(dock.clone())
 7278            .children(leader_border);
 7279
 7280        // Apply sizing only when the dock is open. When closed the dock is still
 7281        // included in the element tree so its focus handle remains mounted — without
 7282        // this, toggle_panel_focus cannot focus the panel when the dock is closed.
 7283        let dock = dock.read(cx);
 7284        if let Some(panel) = dock.visible_panel() {
 7285            let size_state = dock.stored_panel_size_state(panel.as_ref());
 7286            if position.axis() == Axis::Horizontal {
 7287                if let Some(ratio) = size_state
 7288                    .and_then(|state| state.flexible_size_ratio)
 7289                    .or_else(|| self.default_flexible_dock_ratio(position))
 7290                    && panel.supports_flexible_size(window, cx)
 7291                {
 7292                    let ratio = ratio.clamp(0.001, 0.999);
 7293                    let grow = ratio / (1.0 - ratio);
 7294                    let style = container.style();
 7295                    style.flex_grow = Some(grow);
 7296                    style.flex_shrink = Some(1.0);
 7297                    style.flex_basis = Some(relative(0.).into());
 7298                } else {
 7299                    let size = size_state
 7300                        .and_then(|state| state.size)
 7301                        .unwrap_or_else(|| panel.default_size(window, cx));
 7302                    container = container.w(size);
 7303                }
 7304            } else {
 7305                let size = size_state
 7306                    .and_then(|state| state.size)
 7307                    .unwrap_or_else(|| panel.default_size(window, cx));
 7308                container = container.h(size);
 7309            }
 7310        }
 7311
 7312        Some(container)
 7313    }
 7314
 7315    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7316        window
 7317            .root::<MultiWorkspace>()
 7318            .flatten()
 7319            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7320    }
 7321
 7322    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7323        self.zoomed.as_ref()
 7324    }
 7325
 7326    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7327        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7328            return;
 7329        };
 7330        let windows = cx.windows();
 7331        let next_window =
 7332            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7333                || {
 7334                    windows
 7335                        .iter()
 7336                        .cycle()
 7337                        .skip_while(|window| window.window_id() != current_window_id)
 7338                        .nth(1)
 7339                },
 7340            );
 7341
 7342        if let Some(window) = next_window {
 7343            window
 7344                .update(cx, |_, window, _| window.activate_window())
 7345                .ok();
 7346        }
 7347    }
 7348
 7349    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7350        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7351            return;
 7352        };
 7353        let windows = cx.windows();
 7354        let prev_window =
 7355            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7356                || {
 7357                    windows
 7358                        .iter()
 7359                        .rev()
 7360                        .cycle()
 7361                        .skip_while(|window| window.window_id() != current_window_id)
 7362                        .nth(1)
 7363                },
 7364            );
 7365
 7366        if let Some(window) = prev_window {
 7367            window
 7368                .update(cx, |_, window, _| window.activate_window())
 7369                .ok();
 7370        }
 7371    }
 7372
 7373    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7374        if cx.stop_active_drag(window) {
 7375        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7376            dismiss_app_notification(&notification_id, cx);
 7377        } else {
 7378            cx.propagate();
 7379        }
 7380    }
 7381
 7382    fn resize_dock(
 7383        &mut self,
 7384        dock_pos: DockPosition,
 7385        new_size: Pixels,
 7386        window: &mut Window,
 7387        cx: &mut Context<Self>,
 7388    ) {
 7389        match dock_pos {
 7390            DockPosition::Left => self.resize_left_dock(new_size, window, cx),
 7391            DockPosition::Right => self.resize_right_dock(new_size, window, cx),
 7392            DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
 7393        }
 7394    }
 7395
 7396    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7397        let workspace_width = self.bounds.size.width;
 7398        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7399
 7400        self.right_dock.read_with(cx, |right_dock, cx| {
 7401            let right_dock_size = right_dock
 7402                .stored_active_panel_size(window, cx)
 7403                .unwrap_or(Pixels::ZERO);
 7404            if right_dock_size + size > workspace_width {
 7405                size = workspace_width - right_dock_size
 7406            }
 7407        });
 7408
 7409        let ratio = self.flexible_dock_ratio_for_size(DockPosition::Left, size, window, cx);
 7410        self.left_dock.update(cx, |left_dock, cx| {
 7411            if WorkspaceSettings::get_global(cx)
 7412                .resize_all_panels_in_dock
 7413                .contains(&DockPosition::Left)
 7414            {
 7415                left_dock.resize_all_panels(Some(size), ratio, window, cx);
 7416            } else {
 7417                left_dock.resize_active_panel(Some(size), ratio, window, cx);
 7418            }
 7419        });
 7420    }
 7421
 7422    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7423        let workspace_width = self.bounds.size.width;
 7424        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7425        self.left_dock.read_with(cx, |left_dock, cx| {
 7426            let left_dock_size = left_dock
 7427                .stored_active_panel_size(window, cx)
 7428                .unwrap_or(Pixels::ZERO);
 7429            if left_dock_size + size > workspace_width {
 7430                size = workspace_width - left_dock_size
 7431            }
 7432        });
 7433        let ratio = self.flexible_dock_ratio_for_size(DockPosition::Right, size, window, cx);
 7434        self.right_dock.update(cx, |right_dock, cx| {
 7435            if WorkspaceSettings::get_global(cx)
 7436                .resize_all_panels_in_dock
 7437                .contains(&DockPosition::Right)
 7438            {
 7439                right_dock.resize_all_panels(Some(size), ratio, window, cx);
 7440            } else {
 7441                right_dock.resize_active_panel(Some(size), ratio, window, cx);
 7442            }
 7443        });
 7444    }
 7445
 7446    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7447        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7448        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7449            if WorkspaceSettings::get_global(cx)
 7450                .resize_all_panels_in_dock
 7451                .contains(&DockPosition::Bottom)
 7452            {
 7453                bottom_dock.resize_all_panels(Some(size), None, window, cx);
 7454            } else {
 7455                bottom_dock.resize_active_panel(Some(size), None, window, cx);
 7456            }
 7457        });
 7458    }
 7459
 7460    fn toggle_edit_predictions_all_files(
 7461        &mut self,
 7462        _: &ToggleEditPrediction,
 7463        _window: &mut Window,
 7464        cx: &mut Context<Self>,
 7465    ) {
 7466        let fs = self.project().read(cx).fs().clone();
 7467        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7468        update_settings_file(fs, cx, move |file, _| {
 7469            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7470        });
 7471    }
 7472
 7473    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7474        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7475        let next_mode = match current_mode {
 7476            Some(theme::ThemeAppearanceMode::Light) => theme::ThemeAppearanceMode::Dark,
 7477            Some(theme::ThemeAppearanceMode::Dark) => theme::ThemeAppearanceMode::Light,
 7478            Some(theme::ThemeAppearanceMode::System) | None => match cx.theme().appearance() {
 7479                theme::Appearance::Light => theme::ThemeAppearanceMode::Dark,
 7480                theme::Appearance::Dark => theme::ThemeAppearanceMode::Light,
 7481            },
 7482        };
 7483
 7484        let fs = self.project().read(cx).fs().clone();
 7485        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7486            theme::set_mode(settings, next_mode);
 7487        });
 7488    }
 7489
 7490    pub fn show_worktree_trust_security_modal(
 7491        &mut self,
 7492        toggle: bool,
 7493        window: &mut Window,
 7494        cx: &mut Context<Self>,
 7495    ) {
 7496        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7497            if toggle {
 7498                security_modal.update(cx, |security_modal, cx| {
 7499                    security_modal.dismiss(cx);
 7500                })
 7501            } else {
 7502                security_modal.update(cx, |security_modal, cx| {
 7503                    security_modal.refresh_restricted_paths(cx);
 7504                });
 7505            }
 7506        } else {
 7507            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7508                .map(|trusted_worktrees| {
 7509                    trusted_worktrees
 7510                        .read(cx)
 7511                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7512                })
 7513                .unwrap_or(false);
 7514            if has_restricted_worktrees {
 7515                let project = self.project().read(cx);
 7516                let remote_host = project
 7517                    .remote_connection_options(cx)
 7518                    .map(RemoteHostLocation::from);
 7519                let worktree_store = project.worktree_store().downgrade();
 7520                self.toggle_modal(window, cx, |_, cx| {
 7521                    SecurityModal::new(worktree_store, remote_host, cx)
 7522                });
 7523            }
 7524        }
 7525    }
 7526}
 7527
 7528pub trait AnyActiveCall {
 7529    fn entity(&self) -> AnyEntity;
 7530    fn is_in_room(&self, _: &App) -> bool;
 7531    fn room_id(&self, _: &App) -> Option<u64>;
 7532    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7533    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7534    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7535    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7536    fn is_sharing_project(&self, _: &App) -> bool;
 7537    fn has_remote_participants(&self, _: &App) -> bool;
 7538    fn local_participant_is_guest(&self, _: &App) -> bool;
 7539    fn client(&self, _: &App) -> Arc<Client>;
 7540    fn share_on_join(&self, _: &App) -> bool;
 7541    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7542    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7543    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7544    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7545    fn join_project(
 7546        &self,
 7547        _: u64,
 7548        _: Arc<LanguageRegistry>,
 7549        _: Arc<dyn Fs>,
 7550        _: &mut App,
 7551    ) -> Task<Result<Entity<Project>>>;
 7552    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7553    fn subscribe(
 7554        &self,
 7555        _: &mut Window,
 7556        _: &mut Context<Workspace>,
 7557        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7558    ) -> Subscription;
 7559    fn create_shared_screen(
 7560        &self,
 7561        _: PeerId,
 7562        _: &Entity<Pane>,
 7563        _: &mut Window,
 7564        _: &mut App,
 7565    ) -> Option<Entity<SharedScreen>>;
 7566}
 7567
 7568#[derive(Clone)]
 7569pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7570impl Global for GlobalAnyActiveCall {}
 7571
 7572impl GlobalAnyActiveCall {
 7573    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7574        cx.try_global()
 7575    }
 7576
 7577    pub(crate) fn global(cx: &App) -> &Self {
 7578        cx.global()
 7579    }
 7580}
 7581
 7582pub fn merge_conflict_notification_id() -> NotificationId {
 7583    struct MergeConflictNotification;
 7584    NotificationId::unique::<MergeConflictNotification>()
 7585}
 7586
 7587/// Workspace-local view of a remote participant's location.
 7588#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7589pub enum ParticipantLocation {
 7590    SharedProject { project_id: u64 },
 7591    UnsharedProject,
 7592    External,
 7593}
 7594
 7595impl ParticipantLocation {
 7596    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7597        match location
 7598            .and_then(|l| l.variant)
 7599            .context("participant location was not provided")?
 7600        {
 7601            proto::participant_location::Variant::SharedProject(project) => {
 7602                Ok(Self::SharedProject {
 7603                    project_id: project.id,
 7604                })
 7605            }
 7606            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7607            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7608        }
 7609    }
 7610}
 7611/// Workspace-local view of a remote collaborator's state.
 7612/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7613#[derive(Clone)]
 7614pub struct RemoteCollaborator {
 7615    pub user: Arc<User>,
 7616    pub peer_id: PeerId,
 7617    pub location: ParticipantLocation,
 7618    pub participant_index: ParticipantIndex,
 7619}
 7620
 7621pub enum ActiveCallEvent {
 7622    ParticipantLocationChanged { participant_id: PeerId },
 7623    RemoteVideoTracksChanged { participant_id: PeerId },
 7624}
 7625
 7626fn leader_border_for_pane(
 7627    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7628    pane: &Entity<Pane>,
 7629    _: &Window,
 7630    cx: &App,
 7631) -> Option<Div> {
 7632    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7633        if state.pane() == pane {
 7634            Some((*leader_id, state))
 7635        } else {
 7636            None
 7637        }
 7638    })?;
 7639
 7640    let mut leader_color = match leader_id {
 7641        CollaboratorId::PeerId(leader_peer_id) => {
 7642            let leader = GlobalAnyActiveCall::try_global(cx)?
 7643                .0
 7644                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7645
 7646            cx.theme()
 7647                .players()
 7648                .color_for_participant(leader.participant_index.0)
 7649                .cursor
 7650        }
 7651        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7652    };
 7653    leader_color.fade_out(0.3);
 7654    Some(
 7655        div()
 7656            .absolute()
 7657            .size_full()
 7658            .left_0()
 7659            .top_0()
 7660            .border_2()
 7661            .border_color(leader_color),
 7662    )
 7663}
 7664
 7665fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7666    ZED_WINDOW_POSITION
 7667        .zip(*ZED_WINDOW_SIZE)
 7668        .map(|(position, size)| Bounds {
 7669            origin: position,
 7670            size,
 7671        })
 7672}
 7673
 7674fn open_items(
 7675    serialized_workspace: Option<SerializedWorkspace>,
 7676    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7677    window: &mut Window,
 7678    cx: &mut Context<Workspace>,
 7679) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7680    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7681        Workspace::load_workspace(
 7682            serialized_workspace,
 7683            project_paths_to_open
 7684                .iter()
 7685                .map(|(_, project_path)| project_path)
 7686                .cloned()
 7687                .collect(),
 7688            window,
 7689            cx,
 7690        )
 7691    });
 7692
 7693    cx.spawn_in(window, async move |workspace, cx| {
 7694        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7695
 7696        if let Some(restored_items) = restored_items {
 7697            let restored_items = restored_items.await?;
 7698
 7699            let restored_project_paths = restored_items
 7700                .iter()
 7701                .filter_map(|item| {
 7702                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7703                        .ok()
 7704                        .flatten()
 7705                })
 7706                .collect::<HashSet<_>>();
 7707
 7708            for restored_item in restored_items {
 7709                opened_items.push(restored_item.map(Ok));
 7710            }
 7711
 7712            project_paths_to_open
 7713                .iter_mut()
 7714                .for_each(|(_, project_path)| {
 7715                    if let Some(project_path_to_open) = project_path
 7716                        && restored_project_paths.contains(project_path_to_open)
 7717                    {
 7718                        *project_path = None;
 7719                    }
 7720                });
 7721        } else {
 7722            for _ in 0..project_paths_to_open.len() {
 7723                opened_items.push(None);
 7724            }
 7725        }
 7726        assert!(opened_items.len() == project_paths_to_open.len());
 7727
 7728        let tasks =
 7729            project_paths_to_open
 7730                .into_iter()
 7731                .enumerate()
 7732                .map(|(ix, (abs_path, project_path))| {
 7733                    let workspace = workspace.clone();
 7734                    cx.spawn(async move |cx| {
 7735                        let file_project_path = project_path?;
 7736                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7737                            workspace.project().update(cx, |project, cx| {
 7738                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7739                            })
 7740                        });
 7741
 7742                        // We only want to open file paths here. If one of the items
 7743                        // here is a directory, it was already opened further above
 7744                        // with a `find_or_create_worktree`.
 7745                        if let Ok(task) = abs_path_task
 7746                            && task.await.is_none_or(|p| p.is_file())
 7747                        {
 7748                            return Some((
 7749                                ix,
 7750                                workspace
 7751                                    .update_in(cx, |workspace, window, cx| {
 7752                                        workspace.open_path(
 7753                                            file_project_path,
 7754                                            None,
 7755                                            true,
 7756                                            window,
 7757                                            cx,
 7758                                        )
 7759                                    })
 7760                                    .log_err()?
 7761                                    .await,
 7762                            ));
 7763                        }
 7764                        None
 7765                    })
 7766                });
 7767
 7768        let tasks = tasks.collect::<Vec<_>>();
 7769
 7770        let tasks = futures::future::join_all(tasks);
 7771        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7772            opened_items[ix] = Some(path_open_result);
 7773        }
 7774
 7775        Ok(opened_items)
 7776    })
 7777}
 7778
 7779#[derive(Clone)]
 7780enum ActivateInDirectionTarget {
 7781    Pane(Entity<Pane>),
 7782    Dock(Entity<Dock>),
 7783    Sidebar(FocusHandle),
 7784}
 7785
 7786fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7787    window
 7788        .update(cx, |multi_workspace, _, cx| {
 7789            let workspace = multi_workspace.workspace().clone();
 7790            workspace.update(cx, |workspace, cx| {
 7791                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7792                    struct DatabaseFailedNotification;
 7793
 7794                    workspace.show_notification(
 7795                        NotificationId::unique::<DatabaseFailedNotification>(),
 7796                        cx,
 7797                        |cx| {
 7798                            cx.new(|cx| {
 7799                                MessageNotification::new("Failed to load the database file.", cx)
 7800                                    .primary_message("File an Issue")
 7801                                    .primary_icon(IconName::Plus)
 7802                                    .primary_on_click(|window, cx| {
 7803                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7804                                    })
 7805                            })
 7806                        },
 7807                    );
 7808                }
 7809            });
 7810        })
 7811        .log_err();
 7812}
 7813
 7814fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7815    if val == 0 {
 7816        ThemeSettings::get_global(cx).ui_font_size(cx)
 7817    } else {
 7818        px(val as f32)
 7819    }
 7820}
 7821
 7822fn adjust_active_dock_size_by_px(
 7823    px: Pixels,
 7824    workspace: &mut Workspace,
 7825    window: &mut Window,
 7826    cx: &mut Context<Workspace>,
 7827) {
 7828    let Some(active_dock) = workspace
 7829        .all_docks()
 7830        .into_iter()
 7831        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7832    else {
 7833        return;
 7834    };
 7835    let dock = active_dock.read(cx);
 7836    let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
 7837        return;
 7838    };
 7839    workspace.resize_dock(dock.position(), panel_size + px, window, cx);
 7840}
 7841
 7842fn adjust_open_docks_size_by_px(
 7843    px: Pixels,
 7844    workspace: &mut Workspace,
 7845    window: &mut Window,
 7846    cx: &mut Context<Workspace>,
 7847) {
 7848    let docks = workspace
 7849        .all_docks()
 7850        .into_iter()
 7851        .filter_map(|dock_entity| {
 7852            let dock = dock_entity.read(cx);
 7853            if dock.is_open() {
 7854                let dock_pos = dock.position();
 7855                let panel_size = workspace.dock_size(&dock, window, cx)?;
 7856                Some((dock_pos, panel_size + px))
 7857            } else {
 7858                None
 7859            }
 7860        })
 7861        .collect::<Vec<_>>();
 7862
 7863    for (position, new_size) in docks {
 7864        workspace.resize_dock(position, new_size, window, cx);
 7865    }
 7866}
 7867
 7868impl Focusable for Workspace {
 7869    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7870        self.active_pane.focus_handle(cx)
 7871    }
 7872}
 7873
 7874#[derive(Clone)]
 7875struct DraggedDock(DockPosition);
 7876
 7877impl Render for DraggedDock {
 7878    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7879        gpui::Empty
 7880    }
 7881}
 7882
 7883impl Render for Workspace {
 7884    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 7885        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 7886        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 7887            log::info!("Rendered first frame");
 7888        }
 7889
 7890        let centered_layout = self.centered_layout
 7891            && self.center.panes().len() == 1
 7892            && self.active_item(cx).is_some();
 7893        let render_padding = |size| {
 7894            (size > 0.0).then(|| {
 7895                div()
 7896                    .h_full()
 7897                    .w(relative(size))
 7898                    .bg(cx.theme().colors().editor_background)
 7899                    .border_color(cx.theme().colors().pane_group_border)
 7900            })
 7901        };
 7902        let paddings = if centered_layout {
 7903            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 7904            (
 7905                render_padding(Self::adjust_padding(
 7906                    settings.left_padding.map(|padding| padding.0),
 7907                )),
 7908                render_padding(Self::adjust_padding(
 7909                    settings.right_padding.map(|padding| padding.0),
 7910                )),
 7911            )
 7912        } else {
 7913            (None, None)
 7914        };
 7915        let ui_font = theme::setup_ui_font(window, cx);
 7916
 7917        let theme = cx.theme().clone();
 7918        let colors = theme.colors();
 7919        let notification_entities = self
 7920            .notifications
 7921            .iter()
 7922            .map(|(_, notification)| notification.entity_id())
 7923            .collect::<Vec<_>>();
 7924        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 7925
 7926        div()
 7927            .relative()
 7928            .size_full()
 7929            .flex()
 7930            .flex_col()
 7931            .font(ui_font)
 7932            .gap_0()
 7933                .justify_start()
 7934                .items_start()
 7935                .text_color(colors.text)
 7936                .overflow_hidden()
 7937                .children(self.titlebar_item.clone())
 7938                .on_modifiers_changed(move |_, _, cx| {
 7939                    for &id in &notification_entities {
 7940                        cx.notify(id);
 7941                    }
 7942                })
 7943                .child(
 7944                    div()
 7945                        .size_full()
 7946                        .relative()
 7947                        .flex_1()
 7948                        .flex()
 7949                        .flex_col()
 7950                        .child(
 7951                            div()
 7952                                .id("workspace")
 7953                                .bg(colors.background)
 7954                                .relative()
 7955                                .flex_1()
 7956                                .w_full()
 7957                                .flex()
 7958                                .flex_col()
 7959                                .overflow_hidden()
 7960                                .border_t_1()
 7961                                .border_b_1()
 7962                                .border_color(colors.border)
 7963                                .child({
 7964                                    let this = cx.entity();
 7965                                    canvas(
 7966                                        move |bounds, window, cx| {
 7967                                            this.update(cx, |this, cx| {
 7968                                                let bounds_changed = this.bounds != bounds;
 7969                                                this.bounds = bounds;
 7970
 7971                                                if bounds_changed {
 7972                                                    this.left_dock.update(cx, |dock, cx| {
 7973                                                        dock.clamp_panel_size(
 7974                                                            bounds.size.width,
 7975                                                            window,
 7976                                                            cx,
 7977                                                        )
 7978                                                    });
 7979
 7980                                                    this.right_dock.update(cx, |dock, cx| {
 7981                                                        dock.clamp_panel_size(
 7982                                                            bounds.size.width,
 7983                                                            window,
 7984                                                            cx,
 7985                                                        )
 7986                                                    });
 7987
 7988                                                    this.bottom_dock.update(cx, |dock, cx| {
 7989                                                        dock.clamp_panel_size(
 7990                                                            bounds.size.height,
 7991                                                            window,
 7992                                                            cx,
 7993                                                        )
 7994                                                    });
 7995                                                }
 7996                                            })
 7997                                        },
 7998                                        |_, _, _, _| {},
 7999                                    )
 8000                                    .absolute()
 8001                                    .size_full()
 8002                                })
 8003                                .when(self.zoomed.is_none(), |this| {
 8004                                    this.on_drag_move(cx.listener(
 8005                                        move |workspace,
 8006                                              e: &DragMoveEvent<DraggedDock>,
 8007                                              window,
 8008                                              cx| {
 8009                                            if workspace.previous_dock_drag_coordinates
 8010                                                != Some(e.event.position)
 8011                                            {
 8012                                                workspace.previous_dock_drag_coordinates =
 8013                                                    Some(e.event.position);
 8014
 8015                                                match e.drag(cx).0 {
 8016                                                    DockPosition::Left => {
 8017                                                        workspace.resize_left_dock(
 8018                                                            e.event.position.x
 8019                                                                - workspace.bounds.left(),
 8020                                                            window,
 8021                                                            cx,
 8022                                                        );
 8023                                                    }
 8024                                                    DockPosition::Right => {
 8025                                                        workspace.resize_right_dock(
 8026                                                            workspace.bounds.right()
 8027                                                                - e.event.position.x,
 8028                                                            window,
 8029                                                            cx,
 8030                                                        );
 8031                                                    }
 8032                                                    DockPosition::Bottom => {
 8033                                                        workspace.resize_bottom_dock(
 8034                                                            workspace.bounds.bottom()
 8035                                                                - e.event.position.y,
 8036                                                            window,
 8037                                                            cx,
 8038                                                        );
 8039                                                    }
 8040                                                };
 8041                                                workspace.serialize_workspace(window, cx);
 8042                                            }
 8043                                        },
 8044                                    ))
 8045
 8046                                })
 8047                                .child({
 8048                                    match bottom_dock_layout {
 8049                                        BottomDockLayout::Full => div()
 8050                                            .flex()
 8051                                            .flex_col()
 8052                                            .h_full()
 8053                                            .child(
 8054                                                div()
 8055                                                    .flex()
 8056                                                    .flex_row()
 8057                                                    .flex_1()
 8058                                                    .overflow_hidden()
 8059                                                    .children(self.render_dock(
 8060                                                        DockPosition::Left,
 8061                                                        &self.left_dock,
 8062                                                        window,
 8063                                                        cx,
 8064                                                    ))
 8065
 8066                                                    .child(
 8067                                                        div()
 8068                                                            .flex()
 8069                                                            .flex_col()
 8070                                                            .flex_1()
 8071                                                            .overflow_hidden()
 8072                                                            .child(
 8073                                                                h_flex()
 8074                                                                    .flex_1()
 8075                                                                    .when_some(
 8076                                                                        paddings.0,
 8077                                                                        |this, p| {
 8078                                                                            this.child(
 8079                                                                                p.border_r_1(),
 8080                                                                            )
 8081                                                                        },
 8082                                                                    )
 8083                                                                    .child(self.center.render(
 8084                                                                        self.zoomed.as_ref(),
 8085                                                                        &PaneRenderContext {
 8086                                                                            follower_states:
 8087                                                                                &self.follower_states,
 8088                                                                            active_call: self.active_call(),
 8089                                                                            active_pane: &self.active_pane,
 8090                                                                            app_state: &self.app_state,
 8091                                                                            project: &self.project,
 8092                                                                            workspace: &self.weak_self,
 8093                                                                        },
 8094                                                                        window,
 8095                                                                        cx,
 8096                                                                    ))
 8097                                                                    .when_some(
 8098                                                                        paddings.1,
 8099                                                                        |this, p| {
 8100                                                                            this.child(
 8101                                                                                p.border_l_1(),
 8102                                                                            )
 8103                                                                        },
 8104                                                                    ),
 8105                                                            ),
 8106                                                    )
 8107
 8108                                                    .children(self.render_dock(
 8109                                                        DockPosition::Right,
 8110                                                        &self.right_dock,
 8111                                                        window,
 8112                                                        cx,
 8113                                                    )),
 8114                                            )
 8115                                            .child(div().w_full().children(self.render_dock(
 8116                                                DockPosition::Bottom,
 8117                                                &self.bottom_dock,
 8118                                                window,
 8119                                                cx
 8120                                            ))),
 8121
 8122                                        BottomDockLayout::LeftAligned => div()
 8123                                            .flex()
 8124                                            .flex_row()
 8125                                            .h_full()
 8126                                            .child(
 8127                                                div()
 8128                                                    .flex()
 8129                                                    .flex_col()
 8130                                                    .flex_1()
 8131                                                    .h_full()
 8132                                                    .child(
 8133                                                        div()
 8134                                                            .flex()
 8135                                                            .flex_row()
 8136                                                            .flex_1()
 8137                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 8138
 8139                                                            .child(
 8140                                                                div()
 8141                                                                    .flex()
 8142                                                                    .flex_col()
 8143                                                                    .flex_1()
 8144                                                                    .overflow_hidden()
 8145                                                                    .child(
 8146                                                                        h_flex()
 8147                                                                            .flex_1()
 8148                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8149                                                                            .child(self.center.render(
 8150                                                                                self.zoomed.as_ref(),
 8151                                                                                &PaneRenderContext {
 8152                                                                                    follower_states:
 8153                                                                                        &self.follower_states,
 8154                                                                                    active_call: self.active_call(),
 8155                                                                                    active_pane: &self.active_pane,
 8156                                                                                    app_state: &self.app_state,
 8157                                                                                    project: &self.project,
 8158                                                                                    workspace: &self.weak_self,
 8159                                                                                },
 8160                                                                                window,
 8161                                                                                cx,
 8162                                                                            ))
 8163                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8164                                                                    )
 8165                                                            )
 8166
 8167                                                    )
 8168                                                    .child(
 8169                                                        div()
 8170                                                            .w_full()
 8171                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8172                                                    ),
 8173                                            )
 8174                                            .children(self.render_dock(
 8175                                                DockPosition::Right,
 8176                                                &self.right_dock,
 8177                                                window,
 8178                                                cx,
 8179                                            )),
 8180                                        BottomDockLayout::RightAligned => div()
 8181                                            .flex()
 8182                                            .flex_row()
 8183                                            .h_full()
 8184                                            .children(self.render_dock(
 8185                                                DockPosition::Left,
 8186                                                &self.left_dock,
 8187                                                window,
 8188                                                cx,
 8189                                            ))
 8190
 8191                                            .child(
 8192                                                div()
 8193                                                    .flex()
 8194                                                    .flex_col()
 8195                                                    .flex_1()
 8196                                                    .h_full()
 8197                                                    .child(
 8198                                                        div()
 8199                                                            .flex()
 8200                                                            .flex_row()
 8201                                                            .flex_1()
 8202                                                            .child(
 8203                                                                div()
 8204                                                                    .flex()
 8205                                                                    .flex_col()
 8206                                                                    .flex_1()
 8207                                                                    .overflow_hidden()
 8208                                                                    .child(
 8209                                                                        h_flex()
 8210                                                                            .flex_1()
 8211                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8212                                                                            .child(self.center.render(
 8213                                                                                self.zoomed.as_ref(),
 8214                                                                                &PaneRenderContext {
 8215                                                                                    follower_states:
 8216                                                                                        &self.follower_states,
 8217                                                                                    active_call: self.active_call(),
 8218                                                                                    active_pane: &self.active_pane,
 8219                                                                                    app_state: &self.app_state,
 8220                                                                                    project: &self.project,
 8221                                                                                    workspace: &self.weak_self,
 8222                                                                                },
 8223                                                                                window,
 8224                                                                                cx,
 8225                                                                            ))
 8226                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8227                                                                    )
 8228                                                            )
 8229
 8230                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 8231                                                    )
 8232                                                    .child(
 8233                                                        div()
 8234                                                            .w_full()
 8235                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8236                                                    ),
 8237                                            ),
 8238                                        BottomDockLayout::Contained => div()
 8239                                            .flex()
 8240                                            .flex_row()
 8241                                            .h_full()
 8242                                            .children(self.render_dock(
 8243                                                DockPosition::Left,
 8244                                                &self.left_dock,
 8245                                                window,
 8246                                                cx,
 8247                                            ))
 8248
 8249                                            .child(
 8250                                                div()
 8251                                                    .flex()
 8252                                                    .flex_col()
 8253                                                    .flex_1()
 8254                                                    .overflow_hidden()
 8255                                                    .child(
 8256                                                        h_flex()
 8257                                                            .flex_1()
 8258                                                            .when_some(paddings.0, |this, p| {
 8259                                                                this.child(p.border_r_1())
 8260                                                            })
 8261                                                            .child(self.center.render(
 8262                                                                self.zoomed.as_ref(),
 8263                                                                &PaneRenderContext {
 8264                                                                    follower_states:
 8265                                                                        &self.follower_states,
 8266                                                                    active_call: self.active_call(),
 8267                                                                    active_pane: &self.active_pane,
 8268                                                                    app_state: &self.app_state,
 8269                                                                    project: &self.project,
 8270                                                                    workspace: &self.weak_self,
 8271                                                                },
 8272                                                                window,
 8273                                                                cx,
 8274                                                            ))
 8275                                                            .when_some(paddings.1, |this, p| {
 8276                                                                this.child(p.border_l_1())
 8277                                                            }),
 8278                                                    )
 8279                                                    .children(self.render_dock(
 8280                                                        DockPosition::Bottom,
 8281                                                        &self.bottom_dock,
 8282                                                        window,
 8283                                                        cx,
 8284                                                    )),
 8285                                            )
 8286
 8287                                            .children(self.render_dock(
 8288                                                DockPosition::Right,
 8289                                                &self.right_dock,
 8290                                                window,
 8291                                                cx,
 8292                                            )),
 8293                                    }
 8294                                })
 8295                                .children(self.zoomed.as_ref().and_then(|view| {
 8296                                    let zoomed_view = view.upgrade()?;
 8297                                    let div = div()
 8298                                        .occlude()
 8299                                        .absolute()
 8300                                        .overflow_hidden()
 8301                                        .border_color(colors.border)
 8302                                        .bg(colors.background)
 8303                                        .child(zoomed_view)
 8304                                        .inset_0()
 8305                                        .shadow_lg();
 8306
 8307                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8308                                       return Some(div);
 8309                                    }
 8310
 8311                                    Some(match self.zoomed_position {
 8312                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8313                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8314                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8315                                        None => {
 8316                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8317                                        }
 8318                                    })
 8319                                }))
 8320                                .children(self.render_notifications(window, cx)),
 8321                        )
 8322                        .when(self.status_bar_visible(cx), |parent| {
 8323                            parent.child(self.status_bar.clone())
 8324                        })
 8325                        .child(self.toast_layer.clone()),
 8326                )
 8327    }
 8328}
 8329
 8330impl WorkspaceStore {
 8331    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8332        Self {
 8333            workspaces: Default::default(),
 8334            _subscriptions: vec![
 8335                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8336                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8337            ],
 8338            client,
 8339        }
 8340    }
 8341
 8342    pub fn update_followers(
 8343        &self,
 8344        project_id: Option<u64>,
 8345        update: proto::update_followers::Variant,
 8346        cx: &App,
 8347    ) -> Option<()> {
 8348        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8349        let room_id = active_call.0.room_id(cx)?;
 8350        self.client
 8351            .send(proto::UpdateFollowers {
 8352                room_id,
 8353                project_id,
 8354                variant: Some(update),
 8355            })
 8356            .log_err()
 8357    }
 8358
 8359    pub async fn handle_follow(
 8360        this: Entity<Self>,
 8361        envelope: TypedEnvelope<proto::Follow>,
 8362        mut cx: AsyncApp,
 8363    ) -> Result<proto::FollowResponse> {
 8364        this.update(&mut cx, |this, cx| {
 8365            let follower = Follower {
 8366                project_id: envelope.payload.project_id,
 8367                peer_id: envelope.original_sender_id()?,
 8368            };
 8369
 8370            let mut response = proto::FollowResponse::default();
 8371
 8372            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8373                let Some(workspace) = weak_workspace.upgrade() else {
 8374                    return false;
 8375                };
 8376                window_handle
 8377                    .update(cx, |_, window, cx| {
 8378                        workspace.update(cx, |workspace, cx| {
 8379                            let handler_response =
 8380                                workspace.handle_follow(follower.project_id, window, cx);
 8381                            if let Some(active_view) = handler_response.active_view
 8382                                && workspace.project.read(cx).remote_id() == follower.project_id
 8383                            {
 8384                                response.active_view = Some(active_view)
 8385                            }
 8386                        });
 8387                    })
 8388                    .is_ok()
 8389            });
 8390
 8391            Ok(response)
 8392        })
 8393    }
 8394
 8395    async fn handle_update_followers(
 8396        this: Entity<Self>,
 8397        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8398        mut cx: AsyncApp,
 8399    ) -> Result<()> {
 8400        let leader_id = envelope.original_sender_id()?;
 8401        let update = envelope.payload;
 8402
 8403        this.update(&mut cx, |this, cx| {
 8404            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8405                let Some(workspace) = weak_workspace.upgrade() else {
 8406                    return false;
 8407                };
 8408                window_handle
 8409                    .update(cx, |_, window, cx| {
 8410                        workspace.update(cx, |workspace, cx| {
 8411                            let project_id = workspace.project.read(cx).remote_id();
 8412                            if update.project_id != project_id && update.project_id.is_some() {
 8413                                return;
 8414                            }
 8415                            workspace.handle_update_followers(
 8416                                leader_id,
 8417                                update.clone(),
 8418                                window,
 8419                                cx,
 8420                            );
 8421                        });
 8422                    })
 8423                    .is_ok()
 8424            });
 8425            Ok(())
 8426        })
 8427    }
 8428
 8429    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8430        self.workspaces.iter().map(|(_, weak)| weak)
 8431    }
 8432
 8433    pub fn workspaces_with_windows(
 8434        &self,
 8435    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8436        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8437    }
 8438}
 8439
 8440impl ViewId {
 8441    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8442        Ok(Self {
 8443            creator: message
 8444                .creator
 8445                .map(CollaboratorId::PeerId)
 8446                .context("creator is missing")?,
 8447            id: message.id,
 8448        })
 8449    }
 8450
 8451    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8452        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8453            Some(proto::ViewId {
 8454                creator: Some(peer_id),
 8455                id: self.id,
 8456            })
 8457        } else {
 8458            None
 8459        }
 8460    }
 8461}
 8462
 8463impl FollowerState {
 8464    fn pane(&self) -> &Entity<Pane> {
 8465        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8466    }
 8467}
 8468
 8469pub trait WorkspaceHandle {
 8470    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8471}
 8472
 8473impl WorkspaceHandle for Entity<Workspace> {
 8474    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8475        self.read(cx)
 8476            .worktrees(cx)
 8477            .flat_map(|worktree| {
 8478                let worktree_id = worktree.read(cx).id();
 8479                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8480                    worktree_id,
 8481                    path: f.path.clone(),
 8482                })
 8483            })
 8484            .collect::<Vec<_>>()
 8485    }
 8486}
 8487
 8488pub async fn last_opened_workspace_location(
 8489    db: &WorkspaceDb,
 8490    fs: &dyn fs::Fs,
 8491) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8492    db.last_workspace(fs)
 8493        .await
 8494        .log_err()
 8495        .flatten()
 8496        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8497}
 8498
 8499pub async fn last_session_workspace_locations(
 8500    db: &WorkspaceDb,
 8501    last_session_id: &str,
 8502    last_session_window_stack: Option<Vec<WindowId>>,
 8503    fs: &dyn fs::Fs,
 8504) -> Option<Vec<SessionWorkspace>> {
 8505    db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8506        .await
 8507        .log_err()
 8508}
 8509
 8510pub struct MultiWorkspaceRestoreResult {
 8511    pub window_handle: WindowHandle<MultiWorkspace>,
 8512    pub errors: Vec<anyhow::Error>,
 8513}
 8514
 8515pub async fn restore_multiworkspace(
 8516    multi_workspace: SerializedMultiWorkspace,
 8517    app_state: Arc<AppState>,
 8518    cx: &mut AsyncApp,
 8519) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8520    let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
 8521    let mut group_iter = workspaces.into_iter();
 8522    let first = group_iter
 8523        .next()
 8524        .context("window group must not be empty")?;
 8525
 8526    let window_handle = if first.paths.is_empty() {
 8527        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8528            .await?
 8529    } else {
 8530        let OpenResult { window, .. } = cx
 8531            .update(|cx| {
 8532                Workspace::new_local(
 8533                    first.paths.paths().to_vec(),
 8534                    app_state.clone(),
 8535                    None,
 8536                    None,
 8537                    None,
 8538                    true,
 8539                    cx,
 8540                )
 8541            })
 8542            .await?;
 8543        window
 8544    };
 8545
 8546    let mut errors = Vec::new();
 8547
 8548    for session_workspace in group_iter {
 8549        let error = if session_workspace.paths.is_empty() {
 8550            cx.update(|cx| {
 8551                open_workspace_by_id(
 8552                    session_workspace.workspace_id,
 8553                    app_state.clone(),
 8554                    Some(window_handle),
 8555                    cx,
 8556                )
 8557            })
 8558            .await
 8559            .err()
 8560        } else {
 8561            cx.update(|cx| {
 8562                Workspace::new_local(
 8563                    session_workspace.paths.paths().to_vec(),
 8564                    app_state.clone(),
 8565                    Some(window_handle),
 8566                    None,
 8567                    None,
 8568                    false,
 8569                    cx,
 8570                )
 8571            })
 8572            .await
 8573            .err()
 8574        };
 8575
 8576        if let Some(error) = error {
 8577            errors.push(error);
 8578        }
 8579    }
 8580
 8581    if let Some(target_id) = state.active_workspace_id {
 8582        window_handle
 8583            .update(cx, |multi_workspace, window, cx| {
 8584                let target_index = multi_workspace
 8585                    .workspaces()
 8586                    .iter()
 8587                    .position(|ws| ws.read(cx).database_id() == Some(target_id));
 8588                if let Some(index) = target_index {
 8589                    multi_workspace.activate_index(index, window, cx);
 8590                } else if !multi_workspace.workspaces().is_empty() {
 8591                    multi_workspace.activate_index(0, window, cx);
 8592                }
 8593            })
 8594            .ok();
 8595    } else {
 8596        window_handle
 8597            .update(cx, |multi_workspace, window, cx| {
 8598                if !multi_workspace.workspaces().is_empty() {
 8599                    multi_workspace.activate_index(0, window, cx);
 8600                }
 8601            })
 8602            .ok();
 8603    }
 8604
 8605    if state.sidebar_open {
 8606        window_handle
 8607            .update(cx, |multi_workspace, _, cx| {
 8608                multi_workspace.open_sidebar(cx);
 8609            })
 8610            .ok();
 8611    }
 8612
 8613    if !state.collapsed_sidebar_groups.is_empty() {
 8614        let collapsed_groups = state.collapsed_sidebar_groups;
 8615        window_handle
 8616            .update(cx, |multi_workspace, _, cx| {
 8617                multi_workspace.set_sidebar_collapsed_groups(collapsed_groups, cx);
 8618            })
 8619            .ok();
 8620    }
 8621
 8622    window_handle
 8623        .update(cx, |_, window, _cx| {
 8624            window.activate_window();
 8625        })
 8626        .ok();
 8627
 8628    Ok(MultiWorkspaceRestoreResult {
 8629        window_handle,
 8630        errors,
 8631    })
 8632}
 8633
 8634actions!(
 8635    collab,
 8636    [
 8637        /// Opens the channel notes for the current call.
 8638        ///
 8639        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8640        /// channel in the collab panel.
 8641        ///
 8642        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8643        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8644        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8645        OpenChannelNotes,
 8646        /// Mutes your microphone.
 8647        Mute,
 8648        /// Deafens yourself (mute both microphone and speakers).
 8649        Deafen,
 8650        /// Leaves the current call.
 8651        LeaveCall,
 8652        /// Shares the current project with collaborators.
 8653        ShareProject,
 8654        /// Shares your screen with collaborators.
 8655        ScreenShare,
 8656        /// Copies the current room name and session id for debugging purposes.
 8657        CopyRoomId,
 8658    ]
 8659);
 8660
 8661/// Opens the channel notes for a specific channel by its ID.
 8662#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8663#[action(namespace = collab)]
 8664#[serde(deny_unknown_fields)]
 8665pub struct OpenChannelNotesById {
 8666    pub channel_id: u64,
 8667}
 8668
 8669actions!(
 8670    zed,
 8671    [
 8672        /// Opens the Zed log file.
 8673        OpenLog,
 8674        /// Reveals the Zed log file in the system file manager.
 8675        RevealLogInFileManager
 8676    ]
 8677);
 8678
 8679async fn join_channel_internal(
 8680    channel_id: ChannelId,
 8681    app_state: &Arc<AppState>,
 8682    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8683    requesting_workspace: Option<WeakEntity<Workspace>>,
 8684    active_call: &dyn AnyActiveCall,
 8685    cx: &mut AsyncApp,
 8686) -> Result<bool> {
 8687    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8688        if !active_call.is_in_room(cx) {
 8689            return (false, false);
 8690        }
 8691
 8692        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8693        let should_prompt = active_call.is_sharing_project(cx)
 8694            && active_call.has_remote_participants(cx)
 8695            && !already_in_channel;
 8696        (should_prompt, already_in_channel)
 8697    });
 8698
 8699    if already_in_channel {
 8700        let task = cx.update(|cx| {
 8701            if let Some((project, host)) = active_call.most_active_project(cx) {
 8702                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8703            } else {
 8704                None
 8705            }
 8706        });
 8707        if let Some(task) = task {
 8708            task.await?;
 8709        }
 8710        return anyhow::Ok(true);
 8711    }
 8712
 8713    if should_prompt {
 8714        if let Some(multi_workspace) = requesting_window {
 8715            let answer = multi_workspace
 8716                .update(cx, |_, window, cx| {
 8717                    window.prompt(
 8718                        PromptLevel::Warning,
 8719                        "Do you want to switch channels?",
 8720                        Some("Leaving this call will unshare your current project."),
 8721                        &["Yes, Join Channel", "Cancel"],
 8722                        cx,
 8723                    )
 8724                })?
 8725                .await;
 8726
 8727            if answer == Ok(1) {
 8728                return Ok(false);
 8729            }
 8730        } else {
 8731            return Ok(false);
 8732        }
 8733    }
 8734
 8735    let client = cx.update(|cx| active_call.client(cx));
 8736
 8737    let mut client_status = client.status();
 8738
 8739    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8740    'outer: loop {
 8741        let Some(status) = client_status.recv().await else {
 8742            anyhow::bail!("error connecting");
 8743        };
 8744
 8745        match status {
 8746            Status::Connecting
 8747            | Status::Authenticating
 8748            | Status::Authenticated
 8749            | Status::Reconnecting
 8750            | Status::Reauthenticating
 8751            | Status::Reauthenticated => continue,
 8752            Status::Connected { .. } => break 'outer,
 8753            Status::SignedOut | Status::AuthenticationError => {
 8754                return Err(ErrorCode::SignedOut.into());
 8755            }
 8756            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8757            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8758                return Err(ErrorCode::Disconnected.into());
 8759            }
 8760        }
 8761    }
 8762
 8763    let joined = cx
 8764        .update(|cx| active_call.join_channel(channel_id, cx))
 8765        .await?;
 8766
 8767    if !joined {
 8768        return anyhow::Ok(true);
 8769    }
 8770
 8771    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8772
 8773    let task = cx.update(|cx| {
 8774        if let Some((project, host)) = active_call.most_active_project(cx) {
 8775            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8776        }
 8777
 8778        // If you are the first to join a channel, see if you should share your project.
 8779        if !active_call.has_remote_participants(cx)
 8780            && !active_call.local_participant_is_guest(cx)
 8781            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8782        {
 8783            let project = workspace.update(cx, |workspace, cx| {
 8784                let project = workspace.project.read(cx);
 8785
 8786                if !active_call.share_on_join(cx) {
 8787                    return None;
 8788                }
 8789
 8790                if (project.is_local() || project.is_via_remote_server())
 8791                    && project.visible_worktrees(cx).any(|tree| {
 8792                        tree.read(cx)
 8793                            .root_entry()
 8794                            .is_some_and(|entry| entry.is_dir())
 8795                    })
 8796                {
 8797                    Some(workspace.project.clone())
 8798                } else {
 8799                    None
 8800                }
 8801            });
 8802            if let Some(project) = project {
 8803                let share_task = active_call.share_project(project, cx);
 8804                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8805                    share_task.await?;
 8806                    Ok(())
 8807                }));
 8808            }
 8809        }
 8810
 8811        None
 8812    });
 8813    if let Some(task) = task {
 8814        task.await?;
 8815        return anyhow::Ok(true);
 8816    }
 8817    anyhow::Ok(false)
 8818}
 8819
 8820pub fn join_channel(
 8821    channel_id: ChannelId,
 8822    app_state: Arc<AppState>,
 8823    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8824    requesting_workspace: Option<WeakEntity<Workspace>>,
 8825    cx: &mut App,
 8826) -> Task<Result<()>> {
 8827    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8828    cx.spawn(async move |cx| {
 8829        let result = join_channel_internal(
 8830            channel_id,
 8831            &app_state,
 8832            requesting_window,
 8833            requesting_workspace,
 8834            &*active_call.0,
 8835            cx,
 8836        )
 8837        .await;
 8838
 8839        // join channel succeeded, and opened a window
 8840        if matches!(result, Ok(true)) {
 8841            return anyhow::Ok(());
 8842        }
 8843
 8844        // find an existing workspace to focus and show call controls
 8845        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8846        if active_window.is_none() {
 8847            // no open workspaces, make one to show the error in (blergh)
 8848            let OpenResult {
 8849                window: window_handle,
 8850                ..
 8851            } = cx
 8852                .update(|cx| {
 8853                    Workspace::new_local(
 8854                        vec![],
 8855                        app_state.clone(),
 8856                        requesting_window,
 8857                        None,
 8858                        None,
 8859                        true,
 8860                        cx,
 8861                    )
 8862                })
 8863                .await?;
 8864
 8865            window_handle
 8866                .update(cx, |_, window, _cx| {
 8867                    window.activate_window();
 8868                })
 8869                .ok();
 8870
 8871            if result.is_ok() {
 8872                cx.update(|cx| {
 8873                    cx.dispatch_action(&OpenChannelNotes);
 8874                });
 8875            }
 8876
 8877            active_window = Some(window_handle);
 8878        }
 8879
 8880        if let Err(err) = result {
 8881            log::error!("failed to join channel: {}", err);
 8882            if let Some(active_window) = active_window {
 8883                active_window
 8884                    .update(cx, |_, window, cx| {
 8885                        let detail: SharedString = match err.error_code() {
 8886                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 8887                            ErrorCode::UpgradeRequired => concat!(
 8888                                "Your are running an unsupported version of Zed. ",
 8889                                "Please update to continue."
 8890                            )
 8891                            .into(),
 8892                            ErrorCode::NoSuchChannel => concat!(
 8893                                "No matching channel was found. ",
 8894                                "Please check the link and try again."
 8895                            )
 8896                            .into(),
 8897                            ErrorCode::Forbidden => concat!(
 8898                                "This channel is private, and you do not have access. ",
 8899                                "Please ask someone to add you and try again."
 8900                            )
 8901                            .into(),
 8902                            ErrorCode::Disconnected => {
 8903                                "Please check your internet connection and try again.".into()
 8904                            }
 8905                            _ => format!("{}\n\nPlease try again.", err).into(),
 8906                        };
 8907                        window.prompt(
 8908                            PromptLevel::Critical,
 8909                            "Failed to join channel",
 8910                            Some(&detail),
 8911                            &["Ok"],
 8912                            cx,
 8913                        )
 8914                    })?
 8915                    .await
 8916                    .ok();
 8917            }
 8918        }
 8919
 8920        // return ok, we showed the error to the user.
 8921        anyhow::Ok(())
 8922    })
 8923}
 8924
 8925pub async fn get_any_active_multi_workspace(
 8926    app_state: Arc<AppState>,
 8927    mut cx: AsyncApp,
 8928) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8929    // find an existing workspace to focus and show call controls
 8930    let active_window = activate_any_workspace_window(&mut cx);
 8931    if active_window.is_none() {
 8932        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
 8933            .await?;
 8934    }
 8935    activate_any_workspace_window(&mut cx).context("could not open zed")
 8936}
 8937
 8938fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 8939    cx.update(|cx| {
 8940        if let Some(workspace_window) = cx
 8941            .active_window()
 8942            .and_then(|window| window.downcast::<MultiWorkspace>())
 8943        {
 8944            return Some(workspace_window);
 8945        }
 8946
 8947        for window in cx.windows() {
 8948            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 8949                workspace_window
 8950                    .update(cx, |_, window, _| window.activate_window())
 8951                    .ok();
 8952                return Some(workspace_window);
 8953            }
 8954        }
 8955        None
 8956    })
 8957}
 8958
 8959pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 8960    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 8961}
 8962
 8963pub fn workspace_windows_for_location(
 8964    serialized_location: &SerializedWorkspaceLocation,
 8965    cx: &App,
 8966) -> Vec<WindowHandle<MultiWorkspace>> {
 8967    cx.windows()
 8968        .into_iter()
 8969        .filter_map(|window| window.downcast::<MultiWorkspace>())
 8970        .filter(|multi_workspace| {
 8971            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 8972                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 8973                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 8974                }
 8975                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 8976                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 8977                    a.distro_name == b.distro_name
 8978                }
 8979                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 8980                    a.container_id == b.container_id
 8981                }
 8982                #[cfg(any(test, feature = "test-support"))]
 8983                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 8984                    a.id == b.id
 8985                }
 8986                _ => false,
 8987            };
 8988
 8989            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 8990                multi_workspace.workspaces().iter().any(|workspace| {
 8991                    match workspace.read(cx).workspace_location(cx) {
 8992                        WorkspaceLocation::Location(location, _) => {
 8993                            match (&location, serialized_location) {
 8994                                (
 8995                                    SerializedWorkspaceLocation::Local,
 8996                                    SerializedWorkspaceLocation::Local,
 8997                                ) => true,
 8998                                (
 8999                                    SerializedWorkspaceLocation::Remote(a),
 9000                                    SerializedWorkspaceLocation::Remote(b),
 9001                                ) => same_host(a, b),
 9002                                _ => false,
 9003                            }
 9004                        }
 9005                        _ => false,
 9006                    }
 9007                })
 9008            })
 9009        })
 9010        .collect()
 9011}
 9012
 9013pub async fn find_existing_workspace(
 9014    abs_paths: &[PathBuf],
 9015    open_options: &OpenOptions,
 9016    location: &SerializedWorkspaceLocation,
 9017    cx: &mut AsyncApp,
 9018) -> (
 9019    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 9020    OpenVisible,
 9021) {
 9022    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 9023    let mut open_visible = OpenVisible::All;
 9024    let mut best_match = None;
 9025
 9026    if open_options.open_new_workspace != Some(true) {
 9027        cx.update(|cx| {
 9028            for window in workspace_windows_for_location(location, cx) {
 9029                if let Ok(multi_workspace) = window.read(cx) {
 9030                    for workspace in multi_workspace.workspaces() {
 9031                        let project = workspace.read(cx).project.read(cx);
 9032                        let m = project.visibility_for_paths(
 9033                            abs_paths,
 9034                            open_options.open_new_workspace == None,
 9035                            cx,
 9036                        );
 9037                        if m > best_match {
 9038                            existing = Some((window, workspace.clone()));
 9039                            best_match = m;
 9040                        } else if best_match.is_none()
 9041                            && open_options.open_new_workspace == Some(false)
 9042                        {
 9043                            existing = Some((window, workspace.clone()))
 9044                        }
 9045                    }
 9046                }
 9047            }
 9048        });
 9049
 9050        let all_paths_are_files = existing
 9051            .as_ref()
 9052            .and_then(|(_, target_workspace)| {
 9053                cx.update(|cx| {
 9054                    let workspace = target_workspace.read(cx);
 9055                    let project = workspace.project.read(cx);
 9056                    let path_style = workspace.path_style(cx);
 9057                    Some(!abs_paths.iter().any(|path| {
 9058                        let path = util::paths::SanitizedPath::new(path);
 9059                        project.worktrees(cx).any(|worktree| {
 9060                            let worktree = worktree.read(cx);
 9061                            let abs_path = worktree.abs_path();
 9062                            path_style
 9063                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 9064                                .and_then(|rel| worktree.entry_for_path(&rel))
 9065                                .is_some_and(|e| e.is_dir())
 9066                        })
 9067                    }))
 9068                })
 9069            })
 9070            .unwrap_or(false);
 9071
 9072        if open_options.open_new_workspace.is_none()
 9073            && existing.is_some()
 9074            && open_options.wait
 9075            && all_paths_are_files
 9076        {
 9077            cx.update(|cx| {
 9078                let windows = workspace_windows_for_location(location, cx);
 9079                let window = cx
 9080                    .active_window()
 9081                    .and_then(|window| window.downcast::<MultiWorkspace>())
 9082                    .filter(|window| windows.contains(window))
 9083                    .or_else(|| windows.into_iter().next());
 9084                if let Some(window) = window {
 9085                    if let Ok(multi_workspace) = window.read(cx) {
 9086                        let active_workspace = multi_workspace.workspace().clone();
 9087                        existing = Some((window, active_workspace));
 9088                        open_visible = OpenVisible::None;
 9089                    }
 9090                }
 9091            });
 9092        }
 9093    }
 9094    (existing, open_visible)
 9095}
 9096
 9097#[derive(Default, Clone)]
 9098pub struct OpenOptions {
 9099    pub visible: Option<OpenVisible>,
 9100    pub focus: Option<bool>,
 9101    pub open_new_workspace: Option<bool>,
 9102    pub wait: bool,
 9103    pub replace_window: Option<WindowHandle<MultiWorkspace>>,
 9104    pub env: Option<HashMap<String, String>>,
 9105}
 9106
 9107/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 9108/// or [`Workspace::open_workspace_for_paths`].
 9109pub struct OpenResult {
 9110    pub window: WindowHandle<MultiWorkspace>,
 9111    pub workspace: Entity<Workspace>,
 9112    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 9113}
 9114
 9115/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 9116pub fn open_workspace_by_id(
 9117    workspace_id: WorkspaceId,
 9118    app_state: Arc<AppState>,
 9119    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9120    cx: &mut App,
 9121) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 9122    let project_handle = Project::local(
 9123        app_state.client.clone(),
 9124        app_state.node_runtime.clone(),
 9125        app_state.user_store.clone(),
 9126        app_state.languages.clone(),
 9127        app_state.fs.clone(),
 9128        None,
 9129        project::LocalProjectFlags {
 9130            init_worktree_trust: true,
 9131            ..project::LocalProjectFlags::default()
 9132        },
 9133        cx,
 9134    );
 9135
 9136    let db = WorkspaceDb::global(cx);
 9137    let kvp = db::kvp::KeyValueStore::global(cx);
 9138    cx.spawn(async move |cx| {
 9139        let serialized_workspace = db
 9140            .workspace_for_id(workspace_id)
 9141            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 9142
 9143        let centered_layout = serialized_workspace.centered_layout;
 9144
 9145        let (window, workspace) = if let Some(window) = requesting_window {
 9146            let workspace = window.update(cx, |multi_workspace, window, cx| {
 9147                let workspace = cx.new(|cx| {
 9148                    let mut workspace = Workspace::new(
 9149                        Some(workspace_id),
 9150                        project_handle.clone(),
 9151                        app_state.clone(),
 9152                        window,
 9153                        cx,
 9154                    );
 9155                    workspace.centered_layout = centered_layout;
 9156                    workspace
 9157                });
 9158                multi_workspace.add_workspace(workspace.clone(), cx);
 9159                workspace
 9160            })?;
 9161            (window, workspace)
 9162        } else {
 9163            let window_bounds_override = window_bounds_env_override();
 9164
 9165            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 9166                (Some(WindowBounds::Windowed(bounds)), None)
 9167            } else if let Some(display) = serialized_workspace.display
 9168                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 9169            {
 9170                (Some(bounds.0), Some(display))
 9171            } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
 9172                (Some(bounds), Some(display))
 9173            } else {
 9174                (None, None)
 9175            };
 9176
 9177            let options = cx.update(|cx| {
 9178                let mut options = (app_state.build_window_options)(display, cx);
 9179                options.window_bounds = window_bounds;
 9180                options
 9181            });
 9182
 9183            let window = cx.open_window(options, {
 9184                let app_state = app_state.clone();
 9185                let project_handle = project_handle.clone();
 9186                move |window, cx| {
 9187                    let workspace = cx.new(|cx| {
 9188                        let mut workspace = Workspace::new(
 9189                            Some(workspace_id),
 9190                            project_handle,
 9191                            app_state,
 9192                            window,
 9193                            cx,
 9194                        );
 9195                        workspace.centered_layout = centered_layout;
 9196                        workspace
 9197                    });
 9198                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9199                }
 9200            })?;
 9201
 9202            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 9203                multi_workspace.workspace().clone()
 9204            })?;
 9205
 9206            (window, workspace)
 9207        };
 9208
 9209        notify_if_database_failed(window, cx);
 9210
 9211        // Restore items from the serialized workspace
 9212        window
 9213            .update(cx, |_, window, cx| {
 9214                workspace.update(cx, |_workspace, cx| {
 9215                    open_items(Some(serialized_workspace), vec![], window, cx)
 9216                })
 9217            })?
 9218            .await?;
 9219
 9220        window.update(cx, |_, window, cx| {
 9221            workspace.update(cx, |workspace, cx| {
 9222                workspace.serialize_workspace(window, cx);
 9223            });
 9224        })?;
 9225
 9226        Ok(window)
 9227    })
 9228}
 9229
 9230#[allow(clippy::type_complexity)]
 9231pub fn open_paths(
 9232    abs_paths: &[PathBuf],
 9233    app_state: Arc<AppState>,
 9234    open_options: OpenOptions,
 9235    cx: &mut App,
 9236) -> Task<anyhow::Result<OpenResult>> {
 9237    let abs_paths = abs_paths.to_vec();
 9238    #[cfg(target_os = "windows")]
 9239    let wsl_path = abs_paths
 9240        .iter()
 9241        .find_map(|p| util::paths::WslPath::from_path(p));
 9242
 9243    cx.spawn(async move |cx| {
 9244        let (mut existing, mut open_visible) = find_existing_workspace(
 9245            &abs_paths,
 9246            &open_options,
 9247            &SerializedWorkspaceLocation::Local,
 9248            cx,
 9249        )
 9250        .await;
 9251
 9252        // Fallback: if no workspace contains the paths and all paths are files,
 9253        // prefer an existing local workspace window (active window first).
 9254        if open_options.open_new_workspace.is_none() && existing.is_none() {
 9255            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 9256            let all_metadatas = futures::future::join_all(all_paths)
 9257                .await
 9258                .into_iter()
 9259                .filter_map(|result| result.ok().flatten())
 9260                .collect::<Vec<_>>();
 9261
 9262            if all_metadatas.iter().all(|file| !file.is_dir) {
 9263                cx.update(|cx| {
 9264                    let windows = workspace_windows_for_location(
 9265                        &SerializedWorkspaceLocation::Local,
 9266                        cx,
 9267                    );
 9268                    let window = cx
 9269                        .active_window()
 9270                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9271                        .filter(|window| windows.contains(window))
 9272                        .or_else(|| windows.into_iter().next());
 9273                    if let Some(window) = window {
 9274                        if let Ok(multi_workspace) = window.read(cx) {
 9275                            let active_workspace = multi_workspace.workspace().clone();
 9276                            existing = Some((window, active_workspace));
 9277                            open_visible = OpenVisible::None;
 9278                        }
 9279                    }
 9280                });
 9281            }
 9282        }
 9283
 9284        let result = if let Some((existing, target_workspace)) = existing {
 9285            let open_task = existing
 9286                .update(cx, |multi_workspace, window, cx| {
 9287                    window.activate_window();
 9288                    multi_workspace.activate(target_workspace.clone(), cx);
 9289                    target_workspace.update(cx, |workspace, cx| {
 9290                        workspace.open_paths(
 9291                            abs_paths,
 9292                            OpenOptions {
 9293                                visible: Some(open_visible),
 9294                                ..Default::default()
 9295                            },
 9296                            None,
 9297                            window,
 9298                            cx,
 9299                        )
 9300                    })
 9301                })?
 9302                .await;
 9303
 9304            _ = existing.update(cx, |multi_workspace, _, cx| {
 9305                let workspace = multi_workspace.workspace().clone();
 9306                workspace.update(cx, |workspace, cx| {
 9307                    for item in open_task.iter().flatten() {
 9308                        if let Err(e) = item {
 9309                            workspace.show_error(&e, cx);
 9310                        }
 9311                    }
 9312                });
 9313            });
 9314
 9315            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9316        } else {
 9317            let result = cx
 9318                .update(move |cx| {
 9319                    Workspace::new_local(
 9320                        abs_paths,
 9321                        app_state.clone(),
 9322                        open_options.replace_window,
 9323                        open_options.env,
 9324                        None,
 9325                        true,
 9326                        cx,
 9327                    )
 9328                })
 9329                .await;
 9330
 9331            if let Ok(ref result) = result {
 9332                result.window
 9333                    .update(cx, |_, window, _cx| {
 9334                        window.activate_window();
 9335                    })
 9336                    .log_err();
 9337            }
 9338
 9339            result
 9340        };
 9341
 9342        #[cfg(target_os = "windows")]
 9343        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9344            && let Ok(ref result) = result
 9345        {
 9346            result.window
 9347                .update(cx, move |multi_workspace, _window, cx| {
 9348                    struct OpenInWsl;
 9349                    let workspace = multi_workspace.workspace().clone();
 9350                    workspace.update(cx, |workspace, cx| {
 9351                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9352                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9353                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9354                            cx.new(move |cx| {
 9355                                MessageNotification::new(msg, cx)
 9356                                    .primary_message("Open in WSL")
 9357                                    .primary_icon(IconName::FolderOpen)
 9358                                    .primary_on_click(move |window, cx| {
 9359                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9360                                                distro: remote::WslConnectionOptions {
 9361                                                        distro_name: distro.clone(),
 9362                                                    user: None,
 9363                                                },
 9364                                                paths: vec![path.clone().into()],
 9365                                            }), cx)
 9366                                    })
 9367                            })
 9368                        });
 9369                    });
 9370                })
 9371                .unwrap();
 9372        };
 9373        result
 9374    })
 9375}
 9376
 9377pub fn open_new(
 9378    open_options: OpenOptions,
 9379    app_state: Arc<AppState>,
 9380    cx: &mut App,
 9381    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9382) -> Task<anyhow::Result<()>> {
 9383    let task = Workspace::new_local(
 9384        Vec::new(),
 9385        app_state,
 9386        open_options.replace_window,
 9387        open_options.env,
 9388        Some(Box::new(init)),
 9389        true,
 9390        cx,
 9391    );
 9392    cx.spawn(async move |cx| {
 9393        let OpenResult { window, .. } = task.await?;
 9394        window
 9395            .update(cx, |_, window, _cx| {
 9396                window.activate_window();
 9397            })
 9398            .ok();
 9399        Ok(())
 9400    })
 9401}
 9402
 9403pub fn create_and_open_local_file(
 9404    path: &'static Path,
 9405    window: &mut Window,
 9406    cx: &mut Context<Workspace>,
 9407    default_content: impl 'static + Send + FnOnce() -> Rope,
 9408) -> Task<Result<Box<dyn ItemHandle>>> {
 9409    cx.spawn_in(window, async move |workspace, cx| {
 9410        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9411        if !fs.is_file(path).await {
 9412            fs.create_file(path, Default::default()).await?;
 9413            fs.save(path, &default_content(), Default::default())
 9414                .await?;
 9415        }
 9416
 9417        workspace
 9418            .update_in(cx, |workspace, window, cx| {
 9419                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9420                    let path = workspace
 9421                        .project
 9422                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9423                    cx.spawn_in(window, async move |workspace, cx| {
 9424                        let path = path.await?;
 9425
 9426                        let path = fs.canonicalize(&path).await.unwrap_or(path);
 9427
 9428                        let mut items = workspace
 9429                            .update_in(cx, |workspace, window, cx| {
 9430                                workspace.open_paths(
 9431                                    vec![path.to_path_buf()],
 9432                                    OpenOptions {
 9433                                        visible: Some(OpenVisible::None),
 9434                                        ..Default::default()
 9435                                    },
 9436                                    None,
 9437                                    window,
 9438                                    cx,
 9439                                )
 9440                            })?
 9441                            .await;
 9442                        let item = items.pop().flatten();
 9443                        item.with_context(|| format!("path {path:?} is not a file"))?
 9444                    })
 9445                })
 9446            })?
 9447            .await?
 9448            .await
 9449    })
 9450}
 9451
 9452pub fn open_remote_project_with_new_connection(
 9453    window: WindowHandle<MultiWorkspace>,
 9454    remote_connection: Arc<dyn RemoteConnection>,
 9455    cancel_rx: oneshot::Receiver<()>,
 9456    delegate: Arc<dyn RemoteClientDelegate>,
 9457    app_state: Arc<AppState>,
 9458    paths: Vec<PathBuf>,
 9459    cx: &mut App,
 9460) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9461    cx.spawn(async move |cx| {
 9462        let (workspace_id, serialized_workspace) =
 9463            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9464                .await?;
 9465
 9466        let session = match cx
 9467            .update(|cx| {
 9468                remote::RemoteClient::new(
 9469                    ConnectionIdentifier::Workspace(workspace_id.0),
 9470                    remote_connection,
 9471                    cancel_rx,
 9472                    delegate,
 9473                    cx,
 9474                )
 9475            })
 9476            .await?
 9477        {
 9478            Some(result) => result,
 9479            None => return Ok(Vec::new()),
 9480        };
 9481
 9482        let project = cx.update(|cx| {
 9483            project::Project::remote(
 9484                session,
 9485                app_state.client.clone(),
 9486                app_state.node_runtime.clone(),
 9487                app_state.user_store.clone(),
 9488                app_state.languages.clone(),
 9489                app_state.fs.clone(),
 9490                true,
 9491                cx,
 9492            )
 9493        });
 9494
 9495        open_remote_project_inner(
 9496            project,
 9497            paths,
 9498            workspace_id,
 9499            serialized_workspace,
 9500            app_state,
 9501            window,
 9502            cx,
 9503        )
 9504        .await
 9505    })
 9506}
 9507
 9508pub fn open_remote_project_with_existing_connection(
 9509    connection_options: RemoteConnectionOptions,
 9510    project: Entity<Project>,
 9511    paths: Vec<PathBuf>,
 9512    app_state: Arc<AppState>,
 9513    window: WindowHandle<MultiWorkspace>,
 9514    cx: &mut AsyncApp,
 9515) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9516    cx.spawn(async move |cx| {
 9517        let (workspace_id, serialized_workspace) =
 9518            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9519
 9520        open_remote_project_inner(
 9521            project,
 9522            paths,
 9523            workspace_id,
 9524            serialized_workspace,
 9525            app_state,
 9526            window,
 9527            cx,
 9528        )
 9529        .await
 9530    })
 9531}
 9532
 9533async fn open_remote_project_inner(
 9534    project: Entity<Project>,
 9535    paths: Vec<PathBuf>,
 9536    workspace_id: WorkspaceId,
 9537    serialized_workspace: Option<SerializedWorkspace>,
 9538    app_state: Arc<AppState>,
 9539    window: WindowHandle<MultiWorkspace>,
 9540    cx: &mut AsyncApp,
 9541) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9542    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9543    let toolchains = db.toolchains(workspace_id).await?;
 9544    for (toolchain, worktree_path, path) in toolchains {
 9545        project
 9546            .update(cx, |this, cx| {
 9547                let Some(worktree_id) =
 9548                    this.find_worktree(&worktree_path, cx)
 9549                        .and_then(|(worktree, rel_path)| {
 9550                            if rel_path.is_empty() {
 9551                                Some(worktree.read(cx).id())
 9552                            } else {
 9553                                None
 9554                            }
 9555                        })
 9556                else {
 9557                    return Task::ready(None);
 9558                };
 9559
 9560                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9561            })
 9562            .await;
 9563    }
 9564    let mut project_paths_to_open = vec![];
 9565    let mut project_path_errors = vec![];
 9566
 9567    for path in paths {
 9568        let result = cx
 9569            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9570            .await;
 9571        match result {
 9572            Ok((_, project_path)) => {
 9573                project_paths_to_open.push((path.clone(), Some(project_path)));
 9574            }
 9575            Err(error) => {
 9576                project_path_errors.push(error);
 9577            }
 9578        };
 9579    }
 9580
 9581    if project_paths_to_open.is_empty() {
 9582        return Err(project_path_errors.pop().context("no paths given")?);
 9583    }
 9584
 9585    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9586        telemetry::event!("SSH Project Opened");
 9587
 9588        let new_workspace = cx.new(|cx| {
 9589            let mut workspace =
 9590                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9591            workspace.update_history(cx);
 9592
 9593            if let Some(ref serialized) = serialized_workspace {
 9594                workspace.centered_layout = serialized.centered_layout;
 9595            }
 9596
 9597            workspace
 9598        });
 9599
 9600        multi_workspace.activate(new_workspace.clone(), cx);
 9601        new_workspace
 9602    })?;
 9603
 9604    let items = window
 9605        .update(cx, |_, window, cx| {
 9606            window.activate_window();
 9607            workspace.update(cx, |_workspace, cx| {
 9608                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9609            })
 9610        })?
 9611        .await?;
 9612
 9613    workspace.update(cx, |workspace, cx| {
 9614        for error in project_path_errors {
 9615            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9616                if let Some(path) = error.error_tag("path") {
 9617                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9618                }
 9619            } else {
 9620                workspace.show_error(&error, cx)
 9621            }
 9622        }
 9623    });
 9624
 9625    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9626}
 9627
 9628fn deserialize_remote_project(
 9629    connection_options: RemoteConnectionOptions,
 9630    paths: Vec<PathBuf>,
 9631    cx: &AsyncApp,
 9632) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9633    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9634    cx.background_spawn(async move {
 9635        let remote_connection_id = db
 9636            .get_or_create_remote_connection(connection_options)
 9637            .await?;
 9638
 9639        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
 9640
 9641        let workspace_id = if let Some(workspace_id) =
 9642            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9643        {
 9644            workspace_id
 9645        } else {
 9646            db.next_id().await?
 9647        };
 9648
 9649        Ok((workspace_id, serialized_workspace))
 9650    })
 9651}
 9652
 9653pub fn join_in_room_project(
 9654    project_id: u64,
 9655    follow_user_id: u64,
 9656    app_state: Arc<AppState>,
 9657    cx: &mut App,
 9658) -> Task<Result<()>> {
 9659    let windows = cx.windows();
 9660    cx.spawn(async move |cx| {
 9661        let existing_window_and_workspace: Option<(
 9662            WindowHandle<MultiWorkspace>,
 9663            Entity<Workspace>,
 9664        )> = windows.into_iter().find_map(|window_handle| {
 9665            window_handle
 9666                .downcast::<MultiWorkspace>()
 9667                .and_then(|window_handle| {
 9668                    window_handle
 9669                        .update(cx, |multi_workspace, _window, cx| {
 9670                            for workspace in multi_workspace.workspaces() {
 9671                                if workspace.read(cx).project().read(cx).remote_id()
 9672                                    == Some(project_id)
 9673                                {
 9674                                    return Some((window_handle, workspace.clone()));
 9675                                }
 9676                            }
 9677                            None
 9678                        })
 9679                        .unwrap_or(None)
 9680                })
 9681        });
 9682
 9683        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9684            existing_window_and_workspace
 9685        {
 9686            existing_window
 9687                .update(cx, |multi_workspace, _, cx| {
 9688                    multi_workspace.activate(target_workspace, cx);
 9689                })
 9690                .ok();
 9691            existing_window
 9692        } else {
 9693            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9694            let project = cx
 9695                .update(|cx| {
 9696                    active_call.0.join_project(
 9697                        project_id,
 9698                        app_state.languages.clone(),
 9699                        app_state.fs.clone(),
 9700                        cx,
 9701                    )
 9702                })
 9703                .await?;
 9704
 9705            let window_bounds_override = window_bounds_env_override();
 9706            cx.update(|cx| {
 9707                let mut options = (app_state.build_window_options)(None, cx);
 9708                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9709                cx.open_window(options, |window, cx| {
 9710                    let workspace = cx.new(|cx| {
 9711                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9712                    });
 9713                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9714                })
 9715            })?
 9716        };
 9717
 9718        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9719            cx.activate(true);
 9720            window.activate_window();
 9721
 9722            // We set the active workspace above, so this is the correct workspace.
 9723            let workspace = multi_workspace.workspace().clone();
 9724            workspace.update(cx, |workspace, cx| {
 9725                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9726                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9727                    .or_else(|| {
 9728                        // If we couldn't follow the given user, follow the host instead.
 9729                        let collaborator = workspace
 9730                            .project()
 9731                            .read(cx)
 9732                            .collaborators()
 9733                            .values()
 9734                            .find(|collaborator| collaborator.is_host)?;
 9735                        Some(collaborator.peer_id)
 9736                    });
 9737
 9738                if let Some(follow_peer_id) = follow_peer_id {
 9739                    workspace.follow(follow_peer_id, window, cx);
 9740                }
 9741            });
 9742        })?;
 9743
 9744        anyhow::Ok(())
 9745    })
 9746}
 9747
 9748pub fn reload(cx: &mut App) {
 9749    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9750    let mut workspace_windows = cx
 9751        .windows()
 9752        .into_iter()
 9753        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9754        .collect::<Vec<_>>();
 9755
 9756    // If multiple windows have unsaved changes, and need a save prompt,
 9757    // prompt in the active window before switching to a different window.
 9758    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9759
 9760    let mut prompt = None;
 9761    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9762        prompt = window
 9763            .update(cx, |_, window, cx| {
 9764                window.prompt(
 9765                    PromptLevel::Info,
 9766                    "Are you sure you want to restart?",
 9767                    None,
 9768                    &["Restart", "Cancel"],
 9769                    cx,
 9770                )
 9771            })
 9772            .ok();
 9773    }
 9774
 9775    cx.spawn(async move |cx| {
 9776        if let Some(prompt) = prompt {
 9777            let answer = prompt.await?;
 9778            if answer != 0 {
 9779                return anyhow::Ok(());
 9780            }
 9781        }
 9782
 9783        // If the user cancels any save prompt, then keep the app open.
 9784        for window in workspace_windows {
 9785            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9786                let workspace = multi_workspace.workspace().clone();
 9787                workspace.update(cx, |workspace, cx| {
 9788                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9789                })
 9790            }) && !should_close.await?
 9791            {
 9792                return anyhow::Ok(());
 9793            }
 9794        }
 9795        cx.update(|cx| cx.restart());
 9796        anyhow::Ok(())
 9797    })
 9798    .detach_and_log_err(cx);
 9799}
 9800
 9801fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9802    let mut parts = value.split(',');
 9803    let x: usize = parts.next()?.parse().ok()?;
 9804    let y: usize = parts.next()?.parse().ok()?;
 9805    Some(point(px(x as f32), px(y as f32)))
 9806}
 9807
 9808fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9809    let mut parts = value.split(',');
 9810    let width: usize = parts.next()?.parse().ok()?;
 9811    let height: usize = parts.next()?.parse().ok()?;
 9812    Some(size(px(width as f32), px(height as f32)))
 9813}
 9814
 9815/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9816/// appropriate.
 9817///
 9818/// The `border_radius_tiling` parameter allows overriding which corners get
 9819/// rounded, independently of the actual window tiling state. This is used
 9820/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9821/// we want square corners on the left (so the sidebar appears flush with the
 9822/// window edge) but we still need the shadow padding for proper visual
 9823/// appearance. Unlike actual window tiling, this only affects border radius -
 9824/// not padding or shadows.
 9825pub fn client_side_decorations(
 9826    element: impl IntoElement,
 9827    window: &mut Window,
 9828    cx: &mut App,
 9829    border_radius_tiling: Tiling,
 9830) -> Stateful<Div> {
 9831    const BORDER_SIZE: Pixels = px(1.0);
 9832    let decorations = window.window_decorations();
 9833    let tiling = match decorations {
 9834        Decorations::Server => Tiling::default(),
 9835        Decorations::Client { tiling } => tiling,
 9836    };
 9837
 9838    match decorations {
 9839        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9840        Decorations::Server => window.set_client_inset(px(0.0)),
 9841    }
 9842
 9843    struct GlobalResizeEdge(ResizeEdge);
 9844    impl Global for GlobalResizeEdge {}
 9845
 9846    div()
 9847        .id("window-backdrop")
 9848        .bg(transparent_black())
 9849        .map(|div| match decorations {
 9850            Decorations::Server => div,
 9851            Decorations::Client { .. } => div
 9852                .when(
 9853                    !(tiling.top
 9854                        || tiling.right
 9855                        || border_radius_tiling.top
 9856                        || border_radius_tiling.right),
 9857                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9858                )
 9859                .when(
 9860                    !(tiling.top
 9861                        || tiling.left
 9862                        || border_radius_tiling.top
 9863                        || border_radius_tiling.left),
 9864                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9865                )
 9866                .when(
 9867                    !(tiling.bottom
 9868                        || tiling.right
 9869                        || border_radius_tiling.bottom
 9870                        || border_radius_tiling.right),
 9871                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9872                )
 9873                .when(
 9874                    !(tiling.bottom
 9875                        || tiling.left
 9876                        || border_radius_tiling.bottom
 9877                        || border_radius_tiling.left),
 9878                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9879                )
 9880                .when(!tiling.top, |div| {
 9881                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9882                })
 9883                .when(!tiling.bottom, |div| {
 9884                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9885                })
 9886                .when(!tiling.left, |div| {
 9887                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9888                })
 9889                .when(!tiling.right, |div| {
 9890                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9891                })
 9892                .on_mouse_move(move |e, window, cx| {
 9893                    let size = window.window_bounds().get_bounds().size;
 9894                    let pos = e.position;
 9895
 9896                    let new_edge =
 9897                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 9898
 9899                    let edge = cx.try_global::<GlobalResizeEdge>();
 9900                    if new_edge != edge.map(|edge| edge.0) {
 9901                        window
 9902                            .window_handle()
 9903                            .update(cx, |workspace, _, cx| {
 9904                                cx.notify(workspace.entity_id());
 9905                            })
 9906                            .ok();
 9907                    }
 9908                })
 9909                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 9910                    let size = window.window_bounds().get_bounds().size;
 9911                    let pos = e.position;
 9912
 9913                    let edge = match resize_edge(
 9914                        pos,
 9915                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 9916                        size,
 9917                        tiling,
 9918                    ) {
 9919                        Some(value) => value,
 9920                        None => return,
 9921                    };
 9922
 9923                    window.start_window_resize(edge);
 9924                }),
 9925        })
 9926        .size_full()
 9927        .child(
 9928            div()
 9929                .cursor(CursorStyle::Arrow)
 9930                .map(|div| match decorations {
 9931                    Decorations::Server => div,
 9932                    Decorations::Client { .. } => div
 9933                        .border_color(cx.theme().colors().border)
 9934                        .when(
 9935                            !(tiling.top
 9936                                || tiling.right
 9937                                || border_radius_tiling.top
 9938                                || border_radius_tiling.right),
 9939                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9940                        )
 9941                        .when(
 9942                            !(tiling.top
 9943                                || tiling.left
 9944                                || border_radius_tiling.top
 9945                                || border_radius_tiling.left),
 9946                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9947                        )
 9948                        .when(
 9949                            !(tiling.bottom
 9950                                || tiling.right
 9951                                || border_radius_tiling.bottom
 9952                                || border_radius_tiling.right),
 9953                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9954                        )
 9955                        .when(
 9956                            !(tiling.bottom
 9957                                || tiling.left
 9958                                || border_radius_tiling.bottom
 9959                                || border_radius_tiling.left),
 9960                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9961                        )
 9962                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 9963                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 9964                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 9965                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 9966                        .when(!tiling.is_tiled(), |div| {
 9967                            div.shadow(vec![gpui::BoxShadow {
 9968                                color: Hsla {
 9969                                    h: 0.,
 9970                                    s: 0.,
 9971                                    l: 0.,
 9972                                    a: 0.4,
 9973                                },
 9974                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 9975                                spread_radius: px(0.),
 9976                                offset: point(px(0.0), px(0.0)),
 9977                            }])
 9978                        }),
 9979                })
 9980                .on_mouse_move(|_e, _, cx| {
 9981                    cx.stop_propagation();
 9982                })
 9983                .size_full()
 9984                .child(element),
 9985        )
 9986        .map(|div| match decorations {
 9987            Decorations::Server => div,
 9988            Decorations::Client { tiling, .. } => div.child(
 9989                canvas(
 9990                    |_bounds, window, _| {
 9991                        window.insert_hitbox(
 9992                            Bounds::new(
 9993                                point(px(0.0), px(0.0)),
 9994                                window.window_bounds().get_bounds().size,
 9995                            ),
 9996                            HitboxBehavior::Normal,
 9997                        )
 9998                    },
 9999                    move |_bounds, hitbox, window, cx| {
10000                        let mouse = window.mouse_position();
10001                        let size = window.window_bounds().get_bounds().size;
10002                        let Some(edge) =
10003                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10004                        else {
10005                            return;
10006                        };
10007                        cx.set_global(GlobalResizeEdge(edge));
10008                        window.set_cursor_style(
10009                            match edge {
10010                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10011                                ResizeEdge::Left | ResizeEdge::Right => {
10012                                    CursorStyle::ResizeLeftRight
10013                                }
10014                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10015                                    CursorStyle::ResizeUpLeftDownRight
10016                                }
10017                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10018                                    CursorStyle::ResizeUpRightDownLeft
10019                                }
10020                            },
10021                            &hitbox,
10022                        );
10023                    },
10024                )
10025                .size_full()
10026                .absolute(),
10027            ),
10028        })
10029}
10030
10031fn resize_edge(
10032    pos: Point<Pixels>,
10033    shadow_size: Pixels,
10034    window_size: Size<Pixels>,
10035    tiling: Tiling,
10036) -> Option<ResizeEdge> {
10037    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10038    if bounds.contains(&pos) {
10039        return None;
10040    }
10041
10042    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10043    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10044    if !tiling.top && top_left_bounds.contains(&pos) {
10045        return Some(ResizeEdge::TopLeft);
10046    }
10047
10048    let top_right_bounds = Bounds::new(
10049        Point::new(window_size.width - corner_size.width, px(0.)),
10050        corner_size,
10051    );
10052    if !tiling.top && top_right_bounds.contains(&pos) {
10053        return Some(ResizeEdge::TopRight);
10054    }
10055
10056    let bottom_left_bounds = Bounds::new(
10057        Point::new(px(0.), window_size.height - corner_size.height),
10058        corner_size,
10059    );
10060    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10061        return Some(ResizeEdge::BottomLeft);
10062    }
10063
10064    let bottom_right_bounds = Bounds::new(
10065        Point::new(
10066            window_size.width - corner_size.width,
10067            window_size.height - corner_size.height,
10068        ),
10069        corner_size,
10070    );
10071    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10072        return Some(ResizeEdge::BottomRight);
10073    }
10074
10075    if !tiling.top && pos.y < shadow_size {
10076        Some(ResizeEdge::Top)
10077    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10078        Some(ResizeEdge::Bottom)
10079    } else if !tiling.left && pos.x < shadow_size {
10080        Some(ResizeEdge::Left)
10081    } else if !tiling.right && pos.x > window_size.width - shadow_size {
10082        Some(ResizeEdge::Right)
10083    } else {
10084        None
10085    }
10086}
10087
10088fn join_pane_into_active(
10089    active_pane: &Entity<Pane>,
10090    pane: &Entity<Pane>,
10091    window: &mut Window,
10092    cx: &mut App,
10093) {
10094    if pane == active_pane {
10095    } else if pane.read(cx).items_len() == 0 {
10096        pane.update(cx, |_, cx| {
10097            cx.emit(pane::Event::Remove {
10098                focus_on_pane: None,
10099            });
10100        })
10101    } else {
10102        move_all_items(pane, active_pane, window, cx);
10103    }
10104}
10105
10106fn move_all_items(
10107    from_pane: &Entity<Pane>,
10108    to_pane: &Entity<Pane>,
10109    window: &mut Window,
10110    cx: &mut App,
10111) {
10112    let destination_is_different = from_pane != to_pane;
10113    let mut moved_items = 0;
10114    for (item_ix, item_handle) in from_pane
10115        .read(cx)
10116        .items()
10117        .enumerate()
10118        .map(|(ix, item)| (ix, item.clone()))
10119        .collect::<Vec<_>>()
10120    {
10121        let ix = item_ix - moved_items;
10122        if destination_is_different {
10123            // Close item from previous pane
10124            from_pane.update(cx, |source, cx| {
10125                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10126            });
10127            moved_items += 1;
10128        }
10129
10130        // This automatically removes duplicate items in the pane
10131        to_pane.update(cx, |destination, cx| {
10132            destination.add_item(item_handle, true, true, None, window, cx);
10133            window.focus(&destination.focus_handle(cx), cx)
10134        });
10135    }
10136}
10137
10138pub fn move_item(
10139    source: &Entity<Pane>,
10140    destination: &Entity<Pane>,
10141    item_id_to_move: EntityId,
10142    destination_index: usize,
10143    activate: bool,
10144    window: &mut Window,
10145    cx: &mut App,
10146) {
10147    let Some((item_ix, item_handle)) = source
10148        .read(cx)
10149        .items()
10150        .enumerate()
10151        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10152        .map(|(ix, item)| (ix, item.clone()))
10153    else {
10154        // Tab was closed during drag
10155        return;
10156    };
10157
10158    if source != destination {
10159        // Close item from previous pane
10160        source.update(cx, |source, cx| {
10161            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10162        });
10163    }
10164
10165    // This automatically removes duplicate items in the pane
10166    destination.update(cx, |destination, cx| {
10167        destination.add_item_inner(
10168            item_handle,
10169            activate,
10170            activate,
10171            activate,
10172            Some(destination_index),
10173            window,
10174            cx,
10175        );
10176        if activate {
10177            window.focus(&destination.focus_handle(cx), cx)
10178        }
10179    });
10180}
10181
10182pub fn move_active_item(
10183    source: &Entity<Pane>,
10184    destination: &Entity<Pane>,
10185    focus_destination: bool,
10186    close_if_empty: bool,
10187    window: &mut Window,
10188    cx: &mut App,
10189) {
10190    if source == destination {
10191        return;
10192    }
10193    let Some(active_item) = source.read(cx).active_item() else {
10194        return;
10195    };
10196    source.update(cx, |source_pane, cx| {
10197        let item_id = active_item.item_id();
10198        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10199        destination.update(cx, |target_pane, cx| {
10200            target_pane.add_item(
10201                active_item,
10202                focus_destination,
10203                focus_destination,
10204                Some(target_pane.items_len()),
10205                window,
10206                cx,
10207            );
10208        });
10209    });
10210}
10211
10212pub fn clone_active_item(
10213    workspace_id: Option<WorkspaceId>,
10214    source: &Entity<Pane>,
10215    destination: &Entity<Pane>,
10216    focus_destination: bool,
10217    window: &mut Window,
10218    cx: &mut App,
10219) {
10220    if source == destination {
10221        return;
10222    }
10223    let Some(active_item) = source.read(cx).active_item() else {
10224        return;
10225    };
10226    if !active_item.can_split(cx) {
10227        return;
10228    }
10229    let destination = destination.downgrade();
10230    let task = active_item.clone_on_split(workspace_id, window, cx);
10231    window
10232        .spawn(cx, async move |cx| {
10233            let Some(clone) = task.await else {
10234                return;
10235            };
10236            destination
10237                .update_in(cx, |target_pane, window, cx| {
10238                    target_pane.add_item(
10239                        clone,
10240                        focus_destination,
10241                        focus_destination,
10242                        Some(target_pane.items_len()),
10243                        window,
10244                        cx,
10245                    );
10246                })
10247                .log_err();
10248        })
10249        .detach();
10250}
10251
10252#[derive(Debug)]
10253pub struct WorkspacePosition {
10254    pub window_bounds: Option<WindowBounds>,
10255    pub display: Option<Uuid>,
10256    pub centered_layout: bool,
10257}
10258
10259pub fn remote_workspace_position_from_db(
10260    connection_options: RemoteConnectionOptions,
10261    paths_to_open: &[PathBuf],
10262    cx: &App,
10263) -> Task<Result<WorkspacePosition>> {
10264    let paths = paths_to_open.to_vec();
10265    let db = WorkspaceDb::global(cx);
10266    let kvp = db::kvp::KeyValueStore::global(cx);
10267
10268    cx.background_spawn(async move {
10269        let remote_connection_id = db
10270            .get_or_create_remote_connection(connection_options)
10271            .await
10272            .context("fetching serialized ssh project")?;
10273        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10274
10275        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10276            (Some(WindowBounds::Windowed(bounds)), None)
10277        } else {
10278            let restorable_bounds = serialized_workspace
10279                .as_ref()
10280                .and_then(|workspace| {
10281                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10282                })
10283                .or_else(|| persistence::read_default_window_bounds(&kvp));
10284
10285            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10286                (Some(serialized_bounds), Some(serialized_display))
10287            } else {
10288                (None, None)
10289            }
10290        };
10291
10292        let centered_layout = serialized_workspace
10293            .as_ref()
10294            .map(|w| w.centered_layout)
10295            .unwrap_or(false);
10296
10297        Ok(WorkspacePosition {
10298            window_bounds,
10299            display,
10300            centered_layout,
10301        })
10302    })
10303}
10304
10305pub fn with_active_or_new_workspace(
10306    cx: &mut App,
10307    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10308) {
10309    match cx
10310        .active_window()
10311        .and_then(|w| w.downcast::<MultiWorkspace>())
10312    {
10313        Some(multi_workspace) => {
10314            cx.defer(move |cx| {
10315                multi_workspace
10316                    .update(cx, |multi_workspace, window, cx| {
10317                        let workspace = multi_workspace.workspace().clone();
10318                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10319                    })
10320                    .log_err();
10321            });
10322        }
10323        None => {
10324            let app_state = AppState::global(cx);
10325            if let Some(app_state) = app_state.upgrade() {
10326                open_new(
10327                    OpenOptions::default(),
10328                    app_state,
10329                    cx,
10330                    move |workspace, window, cx| f(workspace, window, cx),
10331                )
10332                .detach_and_log_err(cx);
10333            }
10334        }
10335    }
10336}
10337
10338/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10339/// key. This migration path only runs once per panel per workspace.
10340fn load_legacy_panel_size(
10341    panel_key: &str,
10342    dock_position: DockPosition,
10343    workspace: &Workspace,
10344    cx: &mut App,
10345) -> Option<Pixels> {
10346    #[derive(Deserialize)]
10347    struct LegacyPanelState {
10348        #[serde(default)]
10349        width: Option<Pixels>,
10350        #[serde(default)]
10351        height: Option<Pixels>,
10352    }
10353
10354    let workspace_id = workspace
10355        .database_id()
10356        .map(|id| i64::from(id).to_string())
10357        .or_else(|| workspace.session_id())?;
10358
10359    let legacy_key = match panel_key {
10360        "ProjectPanel" => {
10361            format!("{}-{:?}", "ProjectPanel", workspace_id)
10362        }
10363        "OutlinePanel" => {
10364            format!("{}-{:?}", "OutlinePanel", workspace_id)
10365        }
10366        "GitPanel" => {
10367            format!("{}-{:?}", "GitPanel", workspace_id)
10368        }
10369        "TerminalPanel" => {
10370            format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10371        }
10372        _ => return None,
10373    };
10374
10375    let kvp = db::kvp::KeyValueStore::global(cx);
10376    let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10377    let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10378    let size = match dock_position {
10379        DockPosition::Bottom => state.height,
10380        DockPosition::Left | DockPosition::Right => state.width,
10381    }?;
10382
10383    cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10384        .detach_and_log_err(cx);
10385
10386    Some(size)
10387}
10388
10389#[cfg(test)]
10390mod tests {
10391    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10392
10393    use super::*;
10394    use crate::{
10395        dock::{PanelEvent, test::TestPanel},
10396        item::{
10397            ItemBufferKind, ItemEvent,
10398            test::{TestItem, TestProjectItem},
10399        },
10400    };
10401    use fs::FakeFs;
10402    use gpui::{
10403        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10404        UpdateGlobal, VisualTestContext, px,
10405    };
10406    use project::{Project, ProjectEntryId};
10407    use serde_json::json;
10408    use settings::SettingsStore;
10409    use util::path;
10410    use util::rel_path::rel_path;
10411
10412    #[gpui::test]
10413    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10414        init_test(cx);
10415
10416        let fs = FakeFs::new(cx.executor());
10417        let project = Project::test(fs, [], cx).await;
10418        let (workspace, cx) =
10419            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10420
10421        // Adding an item with no ambiguity renders the tab without detail.
10422        let item1 = cx.new(|cx| {
10423            let mut item = TestItem::new(cx);
10424            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10425            item
10426        });
10427        workspace.update_in(cx, |workspace, window, cx| {
10428            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10429        });
10430        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10431
10432        // Adding an item that creates ambiguity increases the level of detail on
10433        // both tabs.
10434        let item2 = cx.new_window_entity(|_window, cx| {
10435            let mut item = TestItem::new(cx);
10436            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10437            item
10438        });
10439        workspace.update_in(cx, |workspace, window, cx| {
10440            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10441        });
10442        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10443        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10444
10445        // Adding an item that creates ambiguity increases the level of detail only
10446        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10447        // we stop at the highest detail available.
10448        let item3 = cx.new(|cx| {
10449            let mut item = TestItem::new(cx);
10450            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10451            item
10452        });
10453        workspace.update_in(cx, |workspace, window, cx| {
10454            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10455        });
10456        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10457        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10458        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10459    }
10460
10461    #[gpui::test]
10462    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10463        init_test(cx);
10464
10465        let fs = FakeFs::new(cx.executor());
10466        fs.insert_tree(
10467            "/root1",
10468            json!({
10469                "one.txt": "",
10470                "two.txt": "",
10471            }),
10472        )
10473        .await;
10474        fs.insert_tree(
10475            "/root2",
10476            json!({
10477                "three.txt": "",
10478            }),
10479        )
10480        .await;
10481
10482        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10483        let (workspace, cx) =
10484            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10485        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10486        let worktree_id = project.update(cx, |project, cx| {
10487            project.worktrees(cx).next().unwrap().read(cx).id()
10488        });
10489
10490        let item1 = cx.new(|cx| {
10491            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10492        });
10493        let item2 = cx.new(|cx| {
10494            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10495        });
10496
10497        // Add an item to an empty pane
10498        workspace.update_in(cx, |workspace, window, cx| {
10499            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10500        });
10501        project.update(cx, |project, cx| {
10502            assert_eq!(
10503                project.active_entry(),
10504                project
10505                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10506                    .map(|e| e.id)
10507            );
10508        });
10509        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10510
10511        // Add a second item to a non-empty pane
10512        workspace.update_in(cx, |workspace, window, cx| {
10513            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10514        });
10515        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10516        project.update(cx, |project, cx| {
10517            assert_eq!(
10518                project.active_entry(),
10519                project
10520                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10521                    .map(|e| e.id)
10522            );
10523        });
10524
10525        // Close the active item
10526        pane.update_in(cx, |pane, window, cx| {
10527            pane.close_active_item(&Default::default(), window, cx)
10528        })
10529        .await
10530        .unwrap();
10531        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10532        project.update(cx, |project, cx| {
10533            assert_eq!(
10534                project.active_entry(),
10535                project
10536                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10537                    .map(|e| e.id)
10538            );
10539        });
10540
10541        // Add a project folder
10542        project
10543            .update(cx, |project, cx| {
10544                project.find_or_create_worktree("root2", true, cx)
10545            })
10546            .await
10547            .unwrap();
10548        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10549
10550        // Remove a project folder
10551        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10552        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10553    }
10554
10555    #[gpui::test]
10556    async fn test_close_window(cx: &mut TestAppContext) {
10557        init_test(cx);
10558
10559        let fs = FakeFs::new(cx.executor());
10560        fs.insert_tree("/root", json!({ "one": "" })).await;
10561
10562        let project = Project::test(fs, ["root".as_ref()], cx).await;
10563        let (workspace, cx) =
10564            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10565
10566        // When there are no dirty items, there's nothing to do.
10567        let item1 = cx.new(TestItem::new);
10568        workspace.update_in(cx, |w, window, cx| {
10569            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10570        });
10571        let task = workspace.update_in(cx, |w, window, cx| {
10572            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10573        });
10574        assert!(task.await.unwrap());
10575
10576        // When there are dirty untitled items, prompt to save each one. If the user
10577        // cancels any prompt, then abort.
10578        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10579        let item3 = cx.new(|cx| {
10580            TestItem::new(cx)
10581                .with_dirty(true)
10582                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10583        });
10584        workspace.update_in(cx, |w, window, cx| {
10585            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10586            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10587        });
10588        let task = workspace.update_in(cx, |w, window, cx| {
10589            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10590        });
10591        cx.executor().run_until_parked();
10592        cx.simulate_prompt_answer("Cancel"); // cancel save all
10593        cx.executor().run_until_parked();
10594        assert!(!cx.has_pending_prompt());
10595        assert!(!task.await.unwrap());
10596    }
10597
10598    #[gpui::test]
10599    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10600        init_test(cx);
10601
10602        let fs = FakeFs::new(cx.executor());
10603        fs.insert_tree("/root", json!({ "one": "" })).await;
10604
10605        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10606        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10607        let multi_workspace_handle =
10608            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10609        cx.run_until_parked();
10610
10611        let workspace_a = multi_workspace_handle
10612            .read_with(cx, |mw, _| mw.workspace().clone())
10613            .unwrap();
10614
10615        let workspace_b = multi_workspace_handle
10616            .update(cx, |mw, window, cx| {
10617                mw.test_add_workspace(project_b, window, cx)
10618            })
10619            .unwrap();
10620
10621        // Activate workspace A
10622        multi_workspace_handle
10623            .update(cx, |mw, window, cx| {
10624                mw.activate_index(0, window, cx);
10625            })
10626            .unwrap();
10627
10628        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10629
10630        // Workspace A has a clean item
10631        let item_a = cx.new(TestItem::new);
10632        workspace_a.update_in(cx, |w, window, cx| {
10633            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10634        });
10635
10636        // Workspace B has a dirty item
10637        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10638        workspace_b.update_in(cx, |w, window, cx| {
10639            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10640        });
10641
10642        // Verify workspace A is active
10643        multi_workspace_handle
10644            .read_with(cx, |mw, _| {
10645                assert_eq!(mw.active_workspace_index(), 0);
10646            })
10647            .unwrap();
10648
10649        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10650        multi_workspace_handle
10651            .update(cx, |mw, window, cx| {
10652                mw.close_window(&CloseWindow, window, cx);
10653            })
10654            .unwrap();
10655        cx.run_until_parked();
10656
10657        // Workspace B should now be active since it has dirty items that need attention
10658        multi_workspace_handle
10659            .read_with(cx, |mw, _| {
10660                assert_eq!(
10661                    mw.active_workspace_index(),
10662                    1,
10663                    "workspace B should be activated when it prompts"
10664                );
10665            })
10666            .unwrap();
10667
10668        // User cancels the save prompt from workspace B
10669        cx.simulate_prompt_answer("Cancel");
10670        cx.run_until_parked();
10671
10672        // Window should still exist because workspace B's close was cancelled
10673        assert!(
10674            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10675            "window should still exist after cancelling one workspace's close"
10676        );
10677    }
10678
10679    #[gpui::test]
10680    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10681        init_test(cx);
10682
10683        // Register TestItem as a serializable item
10684        cx.update(|cx| {
10685            register_serializable_item::<TestItem>(cx);
10686        });
10687
10688        let fs = FakeFs::new(cx.executor());
10689        fs.insert_tree("/root", json!({ "one": "" })).await;
10690
10691        let project = Project::test(fs, ["root".as_ref()], cx).await;
10692        let (workspace, cx) =
10693            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10694
10695        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10696        let item1 = cx.new(|cx| {
10697            TestItem::new(cx)
10698                .with_dirty(true)
10699                .with_serialize(|| Some(Task::ready(Ok(()))))
10700        });
10701        let item2 = cx.new(|cx| {
10702            TestItem::new(cx)
10703                .with_dirty(true)
10704                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10705                .with_serialize(|| Some(Task::ready(Ok(()))))
10706        });
10707        workspace.update_in(cx, |w, window, cx| {
10708            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10709            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10710        });
10711        let task = workspace.update_in(cx, |w, window, cx| {
10712            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10713        });
10714        assert!(task.await.unwrap());
10715    }
10716
10717    #[gpui::test]
10718    async fn test_close_pane_items(cx: &mut TestAppContext) {
10719        init_test(cx);
10720
10721        let fs = FakeFs::new(cx.executor());
10722
10723        let project = Project::test(fs, None, cx).await;
10724        let (workspace, cx) =
10725            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10726
10727        let item1 = cx.new(|cx| {
10728            TestItem::new(cx)
10729                .with_dirty(true)
10730                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10731        });
10732        let item2 = cx.new(|cx| {
10733            TestItem::new(cx)
10734                .with_dirty(true)
10735                .with_conflict(true)
10736                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10737        });
10738        let item3 = cx.new(|cx| {
10739            TestItem::new(cx)
10740                .with_dirty(true)
10741                .with_conflict(true)
10742                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10743        });
10744        let item4 = cx.new(|cx| {
10745            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10746                let project_item = TestProjectItem::new_untitled(cx);
10747                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10748                project_item
10749            }])
10750        });
10751        let pane = workspace.update_in(cx, |workspace, window, cx| {
10752            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10753            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10754            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10755            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10756            workspace.active_pane().clone()
10757        });
10758
10759        let close_items = pane.update_in(cx, |pane, window, cx| {
10760            pane.activate_item(1, true, true, window, cx);
10761            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10762            let item1_id = item1.item_id();
10763            let item3_id = item3.item_id();
10764            let item4_id = item4.item_id();
10765            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10766                [item1_id, item3_id, item4_id].contains(&id)
10767            })
10768        });
10769        cx.executor().run_until_parked();
10770
10771        assert!(cx.has_pending_prompt());
10772        cx.simulate_prompt_answer("Save all");
10773
10774        cx.executor().run_until_parked();
10775
10776        // Item 1 is saved. There's a prompt to save item 3.
10777        pane.update(cx, |pane, cx| {
10778            assert_eq!(item1.read(cx).save_count, 1);
10779            assert_eq!(item1.read(cx).save_as_count, 0);
10780            assert_eq!(item1.read(cx).reload_count, 0);
10781            assert_eq!(pane.items_len(), 3);
10782            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10783        });
10784        assert!(cx.has_pending_prompt());
10785
10786        // Cancel saving item 3.
10787        cx.simulate_prompt_answer("Discard");
10788        cx.executor().run_until_parked();
10789
10790        // Item 3 is reloaded. There's a prompt to save item 4.
10791        pane.update(cx, |pane, cx| {
10792            assert_eq!(item3.read(cx).save_count, 0);
10793            assert_eq!(item3.read(cx).save_as_count, 0);
10794            assert_eq!(item3.read(cx).reload_count, 1);
10795            assert_eq!(pane.items_len(), 2);
10796            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10797        });
10798
10799        // There's a prompt for a path for item 4.
10800        cx.simulate_new_path_selection(|_| Some(Default::default()));
10801        close_items.await.unwrap();
10802
10803        // The requested items are closed.
10804        pane.update(cx, |pane, cx| {
10805            assert_eq!(item4.read(cx).save_count, 0);
10806            assert_eq!(item4.read(cx).save_as_count, 1);
10807            assert_eq!(item4.read(cx).reload_count, 0);
10808            assert_eq!(pane.items_len(), 1);
10809            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10810        });
10811    }
10812
10813    #[gpui::test]
10814    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10815        init_test(cx);
10816
10817        let fs = FakeFs::new(cx.executor());
10818        let project = Project::test(fs, [], cx).await;
10819        let (workspace, cx) =
10820            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10821
10822        // Create several workspace items with single project entries, and two
10823        // workspace items with multiple project entries.
10824        let single_entry_items = (0..=4)
10825            .map(|project_entry_id| {
10826                cx.new(|cx| {
10827                    TestItem::new(cx)
10828                        .with_dirty(true)
10829                        .with_project_items(&[dirty_project_item(
10830                            project_entry_id,
10831                            &format!("{project_entry_id}.txt"),
10832                            cx,
10833                        )])
10834                })
10835            })
10836            .collect::<Vec<_>>();
10837        let item_2_3 = cx.new(|cx| {
10838            TestItem::new(cx)
10839                .with_dirty(true)
10840                .with_buffer_kind(ItemBufferKind::Multibuffer)
10841                .with_project_items(&[
10842                    single_entry_items[2].read(cx).project_items[0].clone(),
10843                    single_entry_items[3].read(cx).project_items[0].clone(),
10844                ])
10845        });
10846        let item_3_4 = cx.new(|cx| {
10847            TestItem::new(cx)
10848                .with_dirty(true)
10849                .with_buffer_kind(ItemBufferKind::Multibuffer)
10850                .with_project_items(&[
10851                    single_entry_items[3].read(cx).project_items[0].clone(),
10852                    single_entry_items[4].read(cx).project_items[0].clone(),
10853                ])
10854        });
10855
10856        // Create two panes that contain the following project entries:
10857        //   left pane:
10858        //     multi-entry items:   (2, 3)
10859        //     single-entry items:  0, 2, 3, 4
10860        //   right pane:
10861        //     single-entry items:  4, 1
10862        //     multi-entry items:   (3, 4)
10863        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10864            let left_pane = workspace.active_pane().clone();
10865            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10866            workspace.add_item_to_active_pane(
10867                single_entry_items[0].boxed_clone(),
10868                None,
10869                true,
10870                window,
10871                cx,
10872            );
10873            workspace.add_item_to_active_pane(
10874                single_entry_items[2].boxed_clone(),
10875                None,
10876                true,
10877                window,
10878                cx,
10879            );
10880            workspace.add_item_to_active_pane(
10881                single_entry_items[3].boxed_clone(),
10882                None,
10883                true,
10884                window,
10885                cx,
10886            );
10887            workspace.add_item_to_active_pane(
10888                single_entry_items[4].boxed_clone(),
10889                None,
10890                true,
10891                window,
10892                cx,
10893            );
10894
10895            let right_pane =
10896                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10897
10898            let boxed_clone = single_entry_items[1].boxed_clone();
10899            let right_pane = window.spawn(cx, async move |cx| {
10900                right_pane.await.inspect(|right_pane| {
10901                    right_pane
10902                        .update_in(cx, |pane, window, cx| {
10903                            pane.add_item(boxed_clone, true, true, None, window, cx);
10904                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10905                        })
10906                        .unwrap();
10907                })
10908            });
10909
10910            (left_pane, right_pane)
10911        });
10912        let right_pane = right_pane.await.unwrap();
10913        cx.focus(&right_pane);
10914
10915        let close = right_pane.update_in(cx, |pane, window, cx| {
10916            pane.close_all_items(&CloseAllItems::default(), window, cx)
10917                .unwrap()
10918        });
10919        cx.executor().run_until_parked();
10920
10921        let msg = cx.pending_prompt().unwrap().0;
10922        assert!(msg.contains("1.txt"));
10923        assert!(!msg.contains("2.txt"));
10924        assert!(!msg.contains("3.txt"));
10925        assert!(!msg.contains("4.txt"));
10926
10927        // With best-effort close, cancelling item 1 keeps it open but items 4
10928        // and (3,4) still close since their entries exist in left pane.
10929        cx.simulate_prompt_answer("Cancel");
10930        close.await;
10931
10932        right_pane.read_with(cx, |pane, _| {
10933            assert_eq!(pane.items_len(), 1);
10934        });
10935
10936        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10937        left_pane
10938            .update_in(cx, |left_pane, window, cx| {
10939                left_pane.close_item_by_id(
10940                    single_entry_items[3].entity_id(),
10941                    SaveIntent::Skip,
10942                    window,
10943                    cx,
10944                )
10945            })
10946            .await
10947            .unwrap();
10948
10949        let close = left_pane.update_in(cx, |pane, window, cx| {
10950            pane.close_all_items(&CloseAllItems::default(), window, cx)
10951                .unwrap()
10952        });
10953        cx.executor().run_until_parked();
10954
10955        let details = cx.pending_prompt().unwrap().1;
10956        assert!(details.contains("0.txt"));
10957        assert!(details.contains("3.txt"));
10958        assert!(details.contains("4.txt"));
10959        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10960        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10961        // assert!(!details.contains("2.txt"));
10962
10963        cx.simulate_prompt_answer("Save all");
10964        cx.executor().run_until_parked();
10965        close.await;
10966
10967        left_pane.read_with(cx, |pane, _| {
10968            assert_eq!(pane.items_len(), 0);
10969        });
10970    }
10971
10972    #[gpui::test]
10973    async fn test_autosave(cx: &mut gpui::TestAppContext) {
10974        init_test(cx);
10975
10976        let fs = FakeFs::new(cx.executor());
10977        let project = Project::test(fs, [], cx).await;
10978        let (workspace, cx) =
10979            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10980        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10981
10982        let item = cx.new(|cx| {
10983            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10984        });
10985        let item_id = item.entity_id();
10986        workspace.update_in(cx, |workspace, window, cx| {
10987            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10988        });
10989
10990        // Autosave on window change.
10991        item.update(cx, |item, cx| {
10992            SettingsStore::update_global(cx, |settings, cx| {
10993                settings.update_user_settings(cx, |settings| {
10994                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10995                })
10996            });
10997            item.is_dirty = true;
10998        });
10999
11000        // Deactivating the window saves the file.
11001        cx.deactivate_window();
11002        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11003
11004        // Re-activating the window doesn't save the file.
11005        cx.update(|window, _| window.activate_window());
11006        cx.executor().run_until_parked();
11007        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11008
11009        // Autosave on focus change.
11010        item.update_in(cx, |item, window, cx| {
11011            cx.focus_self(window);
11012            SettingsStore::update_global(cx, |settings, cx| {
11013                settings.update_user_settings(cx, |settings| {
11014                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11015                })
11016            });
11017            item.is_dirty = true;
11018        });
11019        // Blurring the item saves the file.
11020        item.update_in(cx, |_, window, _| window.blur());
11021        cx.executor().run_until_parked();
11022        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11023
11024        // Deactivating the window still saves the file.
11025        item.update_in(cx, |item, window, cx| {
11026            cx.focus_self(window);
11027            item.is_dirty = true;
11028        });
11029        cx.deactivate_window();
11030        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11031
11032        // Autosave after delay.
11033        item.update(cx, |item, cx| {
11034            SettingsStore::update_global(cx, |settings, cx| {
11035                settings.update_user_settings(cx, |settings| {
11036                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11037                        milliseconds: 500.into(),
11038                    });
11039                })
11040            });
11041            item.is_dirty = true;
11042            cx.emit(ItemEvent::Edit);
11043        });
11044
11045        // Delay hasn't fully expired, so the file is still dirty and unsaved.
11046        cx.executor().advance_clock(Duration::from_millis(250));
11047        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11048
11049        // After delay expires, the file is saved.
11050        cx.executor().advance_clock(Duration::from_millis(250));
11051        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11052
11053        // Autosave after delay, should save earlier than delay if tab is closed
11054        item.update(cx, |item, cx| {
11055            item.is_dirty = true;
11056            cx.emit(ItemEvent::Edit);
11057        });
11058        cx.executor().advance_clock(Duration::from_millis(250));
11059        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11060
11061        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11062        pane.update_in(cx, |pane, window, cx| {
11063            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11064        })
11065        .await
11066        .unwrap();
11067        assert!(!cx.has_pending_prompt());
11068        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11069
11070        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11071        workspace.update_in(cx, |workspace, window, cx| {
11072            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11073        });
11074        item.update_in(cx, |item, _window, cx| {
11075            item.is_dirty = true;
11076            for project_item in &mut item.project_items {
11077                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11078            }
11079        });
11080        cx.run_until_parked();
11081        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11082
11083        // Autosave on focus change, ensuring closing the tab counts as such.
11084        item.update(cx, |item, cx| {
11085            SettingsStore::update_global(cx, |settings, cx| {
11086                settings.update_user_settings(cx, |settings| {
11087                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11088                })
11089            });
11090            item.is_dirty = true;
11091            for project_item in &mut item.project_items {
11092                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11093            }
11094        });
11095
11096        pane.update_in(cx, |pane, window, cx| {
11097            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11098        })
11099        .await
11100        .unwrap();
11101        assert!(!cx.has_pending_prompt());
11102        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11103
11104        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11105        workspace.update_in(cx, |workspace, window, cx| {
11106            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11107        });
11108        item.update_in(cx, |item, window, cx| {
11109            item.project_items[0].update(cx, |item, _| {
11110                item.entry_id = None;
11111            });
11112            item.is_dirty = true;
11113            window.blur();
11114        });
11115        cx.run_until_parked();
11116        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11117
11118        // Ensure autosave is prevented for deleted files also when closing the buffer.
11119        let _close_items = pane.update_in(cx, |pane, window, cx| {
11120            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11121        });
11122        cx.run_until_parked();
11123        assert!(cx.has_pending_prompt());
11124        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11125    }
11126
11127    #[gpui::test]
11128    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11129        init_test(cx);
11130
11131        let fs = FakeFs::new(cx.executor());
11132        let project = Project::test(fs, [], cx).await;
11133        let (workspace, cx) =
11134            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11135
11136        // Create a multibuffer-like item with two child focus handles,
11137        // simulating individual buffer editors within a multibuffer.
11138        let item = cx.new(|cx| {
11139            TestItem::new(cx)
11140                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11141                .with_child_focus_handles(2, cx)
11142        });
11143        workspace.update_in(cx, |workspace, window, cx| {
11144            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11145        });
11146
11147        // Set autosave to OnFocusChange and focus the first child handle,
11148        // simulating the user's cursor being inside one of the multibuffer's excerpts.
11149        item.update_in(cx, |item, window, cx| {
11150            SettingsStore::update_global(cx, |settings, cx| {
11151                settings.update_user_settings(cx, |settings| {
11152                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11153                })
11154            });
11155            item.is_dirty = true;
11156            window.focus(&item.child_focus_handles[0], cx);
11157        });
11158        cx.executor().run_until_parked();
11159        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11160
11161        // Moving focus from one child to another within the same item should
11162        // NOT trigger autosave — focus is still within the item's focus hierarchy.
11163        item.update_in(cx, |item, window, cx| {
11164            window.focus(&item.child_focus_handles[1], cx);
11165        });
11166        cx.executor().run_until_parked();
11167        item.read_with(cx, |item, _| {
11168            assert_eq!(
11169                item.save_count, 0,
11170                "Switching focus between children within the same item should not autosave"
11171            );
11172        });
11173
11174        // Blurring the item saves the file. This is the core regression scenario:
11175        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11176        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11177        // the leaf is always a child focus handle, so `on_blur` never detected
11178        // focus leaving the item.
11179        item.update_in(cx, |_, window, _| window.blur());
11180        cx.executor().run_until_parked();
11181        item.read_with(cx, |item, _| {
11182            assert_eq!(
11183                item.save_count, 1,
11184                "Blurring should trigger autosave when focus was on a child of the item"
11185            );
11186        });
11187
11188        // Deactivating the window should also trigger autosave when a child of
11189        // the multibuffer item currently owns focus.
11190        item.update_in(cx, |item, window, cx| {
11191            item.is_dirty = true;
11192            window.focus(&item.child_focus_handles[0], cx);
11193        });
11194        cx.executor().run_until_parked();
11195        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11196
11197        cx.deactivate_window();
11198        item.read_with(cx, |item, _| {
11199            assert_eq!(
11200                item.save_count, 2,
11201                "Deactivating window should trigger autosave when focus was on a child"
11202            );
11203        });
11204    }
11205
11206    #[gpui::test]
11207    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11208        init_test(cx);
11209
11210        let fs = FakeFs::new(cx.executor());
11211
11212        let project = Project::test(fs, [], cx).await;
11213        let (workspace, cx) =
11214            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11215
11216        let item = cx.new(|cx| {
11217            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11218        });
11219        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11220        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11221        let toolbar_notify_count = Rc::new(RefCell::new(0));
11222
11223        workspace.update_in(cx, |workspace, window, cx| {
11224            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11225            let toolbar_notification_count = toolbar_notify_count.clone();
11226            cx.observe_in(&toolbar, window, move |_, _, _, _| {
11227                *toolbar_notification_count.borrow_mut() += 1
11228            })
11229            .detach();
11230        });
11231
11232        pane.read_with(cx, |pane, _| {
11233            assert!(!pane.can_navigate_backward());
11234            assert!(!pane.can_navigate_forward());
11235        });
11236
11237        item.update_in(cx, |item, _, cx| {
11238            item.set_state("one".to_string(), cx);
11239        });
11240
11241        // Toolbar must be notified to re-render the navigation buttons
11242        assert_eq!(*toolbar_notify_count.borrow(), 1);
11243
11244        pane.read_with(cx, |pane, _| {
11245            assert!(pane.can_navigate_backward());
11246            assert!(!pane.can_navigate_forward());
11247        });
11248
11249        workspace
11250            .update_in(cx, |workspace, window, cx| {
11251                workspace.go_back(pane.downgrade(), window, cx)
11252            })
11253            .await
11254            .unwrap();
11255
11256        assert_eq!(*toolbar_notify_count.borrow(), 2);
11257        pane.read_with(cx, |pane, _| {
11258            assert!(!pane.can_navigate_backward());
11259            assert!(pane.can_navigate_forward());
11260        });
11261    }
11262
11263    /// Tests that the navigation history deduplicates entries for the same item.
11264    ///
11265    /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11266    /// the navigation history deduplicates by keeping only the most recent visit to each item,
11267    /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11268    /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11269    /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11270    ///
11271    /// This behavior prevents the navigation history from growing unnecessarily large and provides
11272    /// a better user experience by eliminating redundant navigation steps when jumping between files.
11273    #[gpui::test]
11274    async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11275        init_test(cx);
11276
11277        let fs = FakeFs::new(cx.executor());
11278        let project = Project::test(fs, [], cx).await;
11279        let (workspace, cx) =
11280            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11281
11282        let item_a = cx.new(|cx| {
11283            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11284        });
11285        let item_b = cx.new(|cx| {
11286            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11287        });
11288        let item_c = cx.new(|cx| {
11289            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11290        });
11291
11292        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11293
11294        workspace.update_in(cx, |workspace, window, cx| {
11295            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11296            workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11297            workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11298        });
11299
11300        workspace.update_in(cx, |workspace, window, cx| {
11301            workspace.activate_item(&item_a, false, false, window, cx);
11302        });
11303        cx.run_until_parked();
11304
11305        workspace.update_in(cx, |workspace, window, cx| {
11306            workspace.activate_item(&item_b, false, false, window, cx);
11307        });
11308        cx.run_until_parked();
11309
11310        workspace.update_in(cx, |workspace, window, cx| {
11311            workspace.activate_item(&item_a, false, false, window, cx);
11312        });
11313        cx.run_until_parked();
11314
11315        workspace.update_in(cx, |workspace, window, cx| {
11316            workspace.activate_item(&item_b, false, false, window, cx);
11317        });
11318        cx.run_until_parked();
11319
11320        workspace.update_in(cx, |workspace, window, cx| {
11321            workspace.activate_item(&item_a, false, false, window, cx);
11322        });
11323        cx.run_until_parked();
11324
11325        workspace.update_in(cx, |workspace, window, cx| {
11326            workspace.activate_item(&item_b, false, false, window, cx);
11327        });
11328        cx.run_until_parked();
11329
11330        workspace.update_in(cx, |workspace, window, cx| {
11331            workspace.activate_item(&item_c, false, false, window, cx);
11332        });
11333        cx.run_until_parked();
11334
11335        let backward_count = pane.read_with(cx, |pane, cx| {
11336            let mut count = 0;
11337            pane.nav_history().for_each_entry(cx, &mut |_, _| {
11338                count += 1;
11339            });
11340            count
11341        });
11342        assert!(
11343            backward_count <= 4,
11344            "Should have at most 4 entries, got {}",
11345            backward_count
11346        );
11347
11348        workspace
11349            .update_in(cx, |workspace, window, cx| {
11350                workspace.go_back(pane.downgrade(), window, cx)
11351            })
11352            .await
11353            .unwrap();
11354
11355        let active_item = workspace.read_with(cx, |workspace, cx| {
11356            workspace.active_item(cx).unwrap().item_id()
11357        });
11358        assert_eq!(
11359            active_item,
11360            item_b.entity_id(),
11361            "After first go_back, should be at item B"
11362        );
11363
11364        workspace
11365            .update_in(cx, |workspace, window, cx| {
11366                workspace.go_back(pane.downgrade(), window, cx)
11367            })
11368            .await
11369            .unwrap();
11370
11371        let active_item = workspace.read_with(cx, |workspace, cx| {
11372            workspace.active_item(cx).unwrap().item_id()
11373        });
11374        assert_eq!(
11375            active_item,
11376            item_a.entity_id(),
11377            "After second go_back, should be at item A"
11378        );
11379
11380        pane.read_with(cx, |pane, _| {
11381            assert!(pane.can_navigate_forward(), "Should be able to go forward");
11382        });
11383    }
11384
11385    #[gpui::test]
11386    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11387        init_test(cx);
11388        let fs = FakeFs::new(cx.executor());
11389        let project = Project::test(fs, [], cx).await;
11390        let (multi_workspace, cx) =
11391            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11392        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11393
11394        workspace.update_in(cx, |workspace, window, cx| {
11395            let first_item = cx.new(|cx| {
11396                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11397            });
11398            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11399            workspace.split_pane(
11400                workspace.active_pane().clone(),
11401                SplitDirection::Right,
11402                window,
11403                cx,
11404            );
11405            workspace.split_pane(
11406                workspace.active_pane().clone(),
11407                SplitDirection::Right,
11408                window,
11409                cx,
11410            );
11411        });
11412
11413        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11414            let panes = workspace.center.panes();
11415            assert!(panes.len() >= 2);
11416            (
11417                panes.first().expect("at least one pane").entity_id(),
11418                panes.last().expect("at least one pane").entity_id(),
11419            )
11420        });
11421
11422        workspace.update_in(cx, |workspace, window, cx| {
11423            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11424        });
11425        workspace.update(cx, |workspace, _| {
11426            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11427            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11428        });
11429
11430        cx.dispatch_action(ActivateLastPane);
11431
11432        workspace.update(cx, |workspace, _| {
11433            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11434        });
11435    }
11436
11437    #[gpui::test]
11438    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11439        init_test(cx);
11440        let fs = FakeFs::new(cx.executor());
11441
11442        let project = Project::test(fs, [], cx).await;
11443        let (workspace, cx) =
11444            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11445
11446        let panel = workspace.update_in(cx, |workspace, window, cx| {
11447            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11448            workspace.add_panel(panel.clone(), window, cx);
11449
11450            workspace
11451                .right_dock()
11452                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11453
11454            panel
11455        });
11456
11457        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11458        pane.update_in(cx, |pane, window, cx| {
11459            let item = cx.new(TestItem::new);
11460            pane.add_item(Box::new(item), true, true, None, window, cx);
11461        });
11462
11463        // Transfer focus from center to panel
11464        workspace.update_in(cx, |workspace, window, cx| {
11465            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11466        });
11467
11468        workspace.update_in(cx, |workspace, window, cx| {
11469            assert!(workspace.right_dock().read(cx).is_open());
11470            assert!(!panel.is_zoomed(window, cx));
11471            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11472        });
11473
11474        // Transfer focus from panel to center
11475        workspace.update_in(cx, |workspace, window, cx| {
11476            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11477        });
11478
11479        workspace.update_in(cx, |workspace, window, cx| {
11480            assert!(workspace.right_dock().read(cx).is_open());
11481            assert!(!panel.is_zoomed(window, cx));
11482            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11483            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11484        });
11485
11486        // Close the dock
11487        workspace.update_in(cx, |workspace, window, cx| {
11488            workspace.toggle_dock(DockPosition::Right, window, cx);
11489        });
11490
11491        workspace.update_in(cx, |workspace, window, cx| {
11492            assert!(!workspace.right_dock().read(cx).is_open());
11493            assert!(!panel.is_zoomed(window, cx));
11494            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11495            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11496        });
11497
11498        // Open the dock
11499        workspace.update_in(cx, |workspace, window, cx| {
11500            workspace.toggle_dock(DockPosition::Right, window, cx);
11501        });
11502
11503        workspace.update_in(cx, |workspace, window, cx| {
11504            assert!(workspace.right_dock().read(cx).is_open());
11505            assert!(!panel.is_zoomed(window, cx));
11506            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11507        });
11508
11509        // Focus and zoom panel
11510        panel.update_in(cx, |panel, window, cx| {
11511            cx.focus_self(window);
11512            panel.set_zoomed(true, window, cx)
11513        });
11514
11515        workspace.update_in(cx, |workspace, window, cx| {
11516            assert!(workspace.right_dock().read(cx).is_open());
11517            assert!(panel.is_zoomed(window, cx));
11518            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11519        });
11520
11521        // Transfer focus to the center closes the dock
11522        workspace.update_in(cx, |workspace, window, cx| {
11523            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11524        });
11525
11526        workspace.update_in(cx, |workspace, window, cx| {
11527            assert!(!workspace.right_dock().read(cx).is_open());
11528            assert!(panel.is_zoomed(window, cx));
11529            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11530        });
11531
11532        // Transferring focus back to the panel keeps it zoomed
11533        workspace.update_in(cx, |workspace, window, cx| {
11534            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11535        });
11536
11537        workspace.update_in(cx, |workspace, window, cx| {
11538            assert!(workspace.right_dock().read(cx).is_open());
11539            assert!(panel.is_zoomed(window, cx));
11540            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11541        });
11542
11543        // Close the dock while it is zoomed
11544        workspace.update_in(cx, |workspace, window, cx| {
11545            workspace.toggle_dock(DockPosition::Right, window, cx)
11546        });
11547
11548        workspace.update_in(cx, |workspace, window, cx| {
11549            assert!(!workspace.right_dock().read(cx).is_open());
11550            assert!(panel.is_zoomed(window, cx));
11551            assert!(workspace.zoomed.is_none());
11552            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11553        });
11554
11555        // Opening the dock, when it's zoomed, retains focus
11556        workspace.update_in(cx, |workspace, window, cx| {
11557            workspace.toggle_dock(DockPosition::Right, window, cx)
11558        });
11559
11560        workspace.update_in(cx, |workspace, window, cx| {
11561            assert!(workspace.right_dock().read(cx).is_open());
11562            assert!(panel.is_zoomed(window, cx));
11563            assert!(workspace.zoomed.is_some());
11564            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11565        });
11566
11567        // Unzoom and close the panel, zoom the active pane.
11568        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11569        workspace.update_in(cx, |workspace, window, cx| {
11570            workspace.toggle_dock(DockPosition::Right, window, cx)
11571        });
11572        pane.update_in(cx, |pane, window, cx| {
11573            pane.toggle_zoom(&Default::default(), window, cx)
11574        });
11575
11576        // Opening a dock unzooms the pane.
11577        workspace.update_in(cx, |workspace, window, cx| {
11578            workspace.toggle_dock(DockPosition::Right, window, cx)
11579        });
11580        workspace.update_in(cx, |workspace, window, cx| {
11581            let pane = pane.read(cx);
11582            assert!(!pane.is_zoomed());
11583            assert!(!pane.focus_handle(cx).is_focused(window));
11584            assert!(workspace.right_dock().read(cx).is_open());
11585            assert!(workspace.zoomed.is_none());
11586        });
11587    }
11588
11589    #[gpui::test]
11590    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11591        init_test(cx);
11592        let fs = FakeFs::new(cx.executor());
11593
11594        let project = Project::test(fs, [], cx).await;
11595        let (workspace, cx) =
11596            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11597
11598        let panel = workspace.update_in(cx, |workspace, window, cx| {
11599            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11600            workspace.add_panel(panel.clone(), window, cx);
11601            panel
11602        });
11603
11604        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11605        pane.update_in(cx, |pane, window, cx| {
11606            let item = cx.new(TestItem::new);
11607            pane.add_item(Box::new(item), true, true, None, window, cx);
11608        });
11609
11610        // Enable close_panel_on_toggle
11611        cx.update_global(|store: &mut SettingsStore, cx| {
11612            store.update_user_settings(cx, |settings| {
11613                settings.workspace.close_panel_on_toggle = Some(true);
11614            });
11615        });
11616
11617        // Panel starts closed. Toggling should open and focus it.
11618        workspace.update_in(cx, |workspace, window, cx| {
11619            assert!(!workspace.right_dock().read(cx).is_open());
11620            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11621        });
11622
11623        workspace.update_in(cx, |workspace, window, cx| {
11624            assert!(
11625                workspace.right_dock().read(cx).is_open(),
11626                "Dock should be open after toggling from center"
11627            );
11628            assert!(
11629                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11630                "Panel should be focused after toggling from center"
11631            );
11632        });
11633
11634        // Panel is open and focused. Toggling should close the panel and
11635        // return focus to the center.
11636        workspace.update_in(cx, |workspace, window, cx| {
11637            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11638        });
11639
11640        workspace.update_in(cx, |workspace, window, cx| {
11641            assert!(
11642                !workspace.right_dock().read(cx).is_open(),
11643                "Dock should be closed after toggling from focused panel"
11644            );
11645            assert!(
11646                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11647                "Panel should not be focused after toggling from focused panel"
11648            );
11649        });
11650
11651        // Open the dock and focus something else so the panel is open but not
11652        // focused. Toggling should focus the panel (not close it).
11653        workspace.update_in(cx, |workspace, window, cx| {
11654            workspace
11655                .right_dock()
11656                .update(cx, |dock, cx| dock.set_open(true, window, cx));
11657            window.focus(&pane.read(cx).focus_handle(cx), cx);
11658        });
11659
11660        workspace.update_in(cx, |workspace, window, cx| {
11661            assert!(workspace.right_dock().read(cx).is_open());
11662            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11663            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11664        });
11665
11666        workspace.update_in(cx, |workspace, window, cx| {
11667            assert!(
11668                workspace.right_dock().read(cx).is_open(),
11669                "Dock should remain open when toggling focuses an open-but-unfocused panel"
11670            );
11671            assert!(
11672                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11673                "Panel should be focused after toggling an open-but-unfocused panel"
11674            );
11675        });
11676
11677        // Now disable the setting and verify the original behavior: toggling
11678        // from a focused panel moves focus to center but leaves the dock open.
11679        cx.update_global(|store: &mut SettingsStore, cx| {
11680            store.update_user_settings(cx, |settings| {
11681                settings.workspace.close_panel_on_toggle = Some(false);
11682            });
11683        });
11684
11685        workspace.update_in(cx, |workspace, window, cx| {
11686            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11687        });
11688
11689        workspace.update_in(cx, |workspace, window, cx| {
11690            assert!(
11691                workspace.right_dock().read(cx).is_open(),
11692                "Dock should remain open when setting is disabled"
11693            );
11694            assert!(
11695                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11696                "Panel should not be focused after toggling with setting disabled"
11697            );
11698        });
11699    }
11700
11701    #[gpui::test]
11702    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11703        init_test(cx);
11704        let fs = FakeFs::new(cx.executor());
11705
11706        let project = Project::test(fs, [], cx).await;
11707        let (workspace, cx) =
11708            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11709
11710        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11711            workspace.active_pane().clone()
11712        });
11713
11714        // Add an item to the pane so it can be zoomed
11715        workspace.update_in(cx, |workspace, window, cx| {
11716            let item = cx.new(TestItem::new);
11717            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11718        });
11719
11720        // Initially not zoomed
11721        workspace.update_in(cx, |workspace, _window, cx| {
11722            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11723            assert!(
11724                workspace.zoomed.is_none(),
11725                "Workspace should track no zoomed pane"
11726            );
11727            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11728        });
11729
11730        // Zoom In
11731        pane.update_in(cx, |pane, window, cx| {
11732            pane.zoom_in(&crate::ZoomIn, window, cx);
11733        });
11734
11735        workspace.update_in(cx, |workspace, window, cx| {
11736            assert!(
11737                pane.read(cx).is_zoomed(),
11738                "Pane should be zoomed after ZoomIn"
11739            );
11740            assert!(
11741                workspace.zoomed.is_some(),
11742                "Workspace should track the zoomed pane"
11743            );
11744            assert!(
11745                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11746                "ZoomIn should focus the pane"
11747            );
11748        });
11749
11750        // Zoom In again is a no-op
11751        pane.update_in(cx, |pane, window, cx| {
11752            pane.zoom_in(&crate::ZoomIn, window, cx);
11753        });
11754
11755        workspace.update_in(cx, |workspace, window, cx| {
11756            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11757            assert!(
11758                workspace.zoomed.is_some(),
11759                "Workspace still tracks zoomed pane"
11760            );
11761            assert!(
11762                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11763                "Pane remains focused after repeated ZoomIn"
11764            );
11765        });
11766
11767        // Zoom Out
11768        pane.update_in(cx, |pane, window, cx| {
11769            pane.zoom_out(&crate::ZoomOut, window, cx);
11770        });
11771
11772        workspace.update_in(cx, |workspace, _window, cx| {
11773            assert!(
11774                !pane.read(cx).is_zoomed(),
11775                "Pane should unzoom after ZoomOut"
11776            );
11777            assert!(
11778                workspace.zoomed.is_none(),
11779                "Workspace clears zoom tracking after ZoomOut"
11780            );
11781        });
11782
11783        // Zoom Out again is a no-op
11784        pane.update_in(cx, |pane, window, cx| {
11785            pane.zoom_out(&crate::ZoomOut, window, cx);
11786        });
11787
11788        workspace.update_in(cx, |workspace, _window, cx| {
11789            assert!(
11790                !pane.read(cx).is_zoomed(),
11791                "Second ZoomOut keeps pane unzoomed"
11792            );
11793            assert!(
11794                workspace.zoomed.is_none(),
11795                "Workspace remains without zoomed pane"
11796            );
11797        });
11798    }
11799
11800    #[gpui::test]
11801    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11802        init_test(cx);
11803        let fs = FakeFs::new(cx.executor());
11804
11805        let project = Project::test(fs, [], cx).await;
11806        let (workspace, cx) =
11807            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11808        workspace.update_in(cx, |workspace, window, cx| {
11809            // Open two docks
11810            let left_dock = workspace.dock_at_position(DockPosition::Left);
11811            let right_dock = workspace.dock_at_position(DockPosition::Right);
11812
11813            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11814            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11815
11816            assert!(left_dock.read(cx).is_open());
11817            assert!(right_dock.read(cx).is_open());
11818        });
11819
11820        workspace.update_in(cx, |workspace, window, cx| {
11821            // Toggle all docks - should close both
11822            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11823
11824            let left_dock = workspace.dock_at_position(DockPosition::Left);
11825            let right_dock = workspace.dock_at_position(DockPosition::Right);
11826            assert!(!left_dock.read(cx).is_open());
11827            assert!(!right_dock.read(cx).is_open());
11828        });
11829
11830        workspace.update_in(cx, |workspace, window, cx| {
11831            // Toggle again - should reopen both
11832            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11833
11834            let left_dock = workspace.dock_at_position(DockPosition::Left);
11835            let right_dock = workspace.dock_at_position(DockPosition::Right);
11836            assert!(left_dock.read(cx).is_open());
11837            assert!(right_dock.read(cx).is_open());
11838        });
11839    }
11840
11841    #[gpui::test]
11842    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11843        init_test(cx);
11844        let fs = FakeFs::new(cx.executor());
11845
11846        let project = Project::test(fs, [], cx).await;
11847        let (workspace, cx) =
11848            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11849        workspace.update_in(cx, |workspace, window, cx| {
11850            // Open two docks
11851            let left_dock = workspace.dock_at_position(DockPosition::Left);
11852            let right_dock = workspace.dock_at_position(DockPosition::Right);
11853
11854            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11855            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11856
11857            assert!(left_dock.read(cx).is_open());
11858            assert!(right_dock.read(cx).is_open());
11859        });
11860
11861        workspace.update_in(cx, |workspace, window, cx| {
11862            // Close them manually
11863            workspace.toggle_dock(DockPosition::Left, window, cx);
11864            workspace.toggle_dock(DockPosition::Right, window, cx);
11865
11866            let left_dock = workspace.dock_at_position(DockPosition::Left);
11867            let right_dock = workspace.dock_at_position(DockPosition::Right);
11868            assert!(!left_dock.read(cx).is_open());
11869            assert!(!right_dock.read(cx).is_open());
11870        });
11871
11872        workspace.update_in(cx, |workspace, window, cx| {
11873            // Toggle all docks - only last closed (right dock) should reopen
11874            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11875
11876            let left_dock = workspace.dock_at_position(DockPosition::Left);
11877            let right_dock = workspace.dock_at_position(DockPosition::Right);
11878            assert!(!left_dock.read(cx).is_open());
11879            assert!(right_dock.read(cx).is_open());
11880        });
11881    }
11882
11883    #[gpui::test]
11884    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11885        init_test(cx);
11886        let fs = FakeFs::new(cx.executor());
11887        let project = Project::test(fs, [], cx).await;
11888        let (multi_workspace, cx) =
11889            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11890        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11891
11892        // Open two docks (left and right) with one panel each
11893        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11894            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11895            workspace.add_panel(left_panel.clone(), window, cx);
11896
11897            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11898            workspace.add_panel(right_panel.clone(), window, cx);
11899
11900            workspace.toggle_dock(DockPosition::Left, window, cx);
11901            workspace.toggle_dock(DockPosition::Right, window, cx);
11902
11903            // Verify initial state
11904            assert!(
11905                workspace.left_dock().read(cx).is_open(),
11906                "Left dock should be open"
11907            );
11908            assert_eq!(
11909                workspace
11910                    .left_dock()
11911                    .read(cx)
11912                    .visible_panel()
11913                    .unwrap()
11914                    .panel_id(),
11915                left_panel.panel_id(),
11916                "Left panel should be visible in left dock"
11917            );
11918            assert!(
11919                workspace.right_dock().read(cx).is_open(),
11920                "Right dock should be open"
11921            );
11922            assert_eq!(
11923                workspace
11924                    .right_dock()
11925                    .read(cx)
11926                    .visible_panel()
11927                    .unwrap()
11928                    .panel_id(),
11929                right_panel.panel_id(),
11930                "Right panel should be visible in right dock"
11931            );
11932            assert!(
11933                !workspace.bottom_dock().read(cx).is_open(),
11934                "Bottom dock should be closed"
11935            );
11936
11937            (left_panel, right_panel)
11938        });
11939
11940        // Focus the left panel and move it to the next position (bottom dock)
11941        workspace.update_in(cx, |workspace, window, cx| {
11942            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11943            assert!(
11944                left_panel.read(cx).focus_handle(cx).is_focused(window),
11945                "Left panel should be focused"
11946            );
11947        });
11948
11949        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11950
11951        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11952        workspace.update(cx, |workspace, cx| {
11953            assert!(
11954                !workspace.left_dock().read(cx).is_open(),
11955                "Left dock should be closed"
11956            );
11957            assert!(
11958                workspace.bottom_dock().read(cx).is_open(),
11959                "Bottom dock should now be open"
11960            );
11961            assert_eq!(
11962                left_panel.read(cx).position,
11963                DockPosition::Bottom,
11964                "Left panel should now be in the bottom dock"
11965            );
11966            assert_eq!(
11967                workspace
11968                    .bottom_dock()
11969                    .read(cx)
11970                    .visible_panel()
11971                    .unwrap()
11972                    .panel_id(),
11973                left_panel.panel_id(),
11974                "Left panel should be the visible panel in the bottom dock"
11975            );
11976        });
11977
11978        // Toggle all docks off
11979        workspace.update_in(cx, |workspace, window, cx| {
11980            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11981            assert!(
11982                !workspace.left_dock().read(cx).is_open(),
11983                "Left dock should be closed"
11984            );
11985            assert!(
11986                !workspace.right_dock().read(cx).is_open(),
11987                "Right dock should be closed"
11988            );
11989            assert!(
11990                !workspace.bottom_dock().read(cx).is_open(),
11991                "Bottom dock should be closed"
11992            );
11993        });
11994
11995        // Toggle all docks back on and verify positions are restored
11996        workspace.update_in(cx, |workspace, window, cx| {
11997            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11998            assert!(
11999                !workspace.left_dock().read(cx).is_open(),
12000                "Left dock should remain closed"
12001            );
12002            assert!(
12003                workspace.right_dock().read(cx).is_open(),
12004                "Right dock should remain open"
12005            );
12006            assert!(
12007                workspace.bottom_dock().read(cx).is_open(),
12008                "Bottom dock should remain open"
12009            );
12010            assert_eq!(
12011                left_panel.read(cx).position,
12012                DockPosition::Bottom,
12013                "Left panel should remain in the bottom dock"
12014            );
12015            assert_eq!(
12016                right_panel.read(cx).position,
12017                DockPosition::Right,
12018                "Right panel should remain in the right dock"
12019            );
12020            assert_eq!(
12021                workspace
12022                    .bottom_dock()
12023                    .read(cx)
12024                    .visible_panel()
12025                    .unwrap()
12026                    .panel_id(),
12027                left_panel.panel_id(),
12028                "Left panel should be the visible panel in the right dock"
12029            );
12030        });
12031    }
12032
12033    #[gpui::test]
12034    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12035        init_test(cx);
12036
12037        let fs = FakeFs::new(cx.executor());
12038
12039        let project = Project::test(fs, None, cx).await;
12040        let (workspace, cx) =
12041            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12042
12043        // Let's arrange the panes like this:
12044        //
12045        // +-----------------------+
12046        // |         top           |
12047        // +------+--------+-------+
12048        // | left | center | right |
12049        // +------+--------+-------+
12050        // |        bottom         |
12051        // +-----------------------+
12052
12053        let top_item = cx.new(|cx| {
12054            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12055        });
12056        let bottom_item = cx.new(|cx| {
12057            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12058        });
12059        let left_item = cx.new(|cx| {
12060            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12061        });
12062        let right_item = cx.new(|cx| {
12063            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12064        });
12065        let center_item = cx.new(|cx| {
12066            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12067        });
12068
12069        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12070            let top_pane_id = workspace.active_pane().entity_id();
12071            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12072            workspace.split_pane(
12073                workspace.active_pane().clone(),
12074                SplitDirection::Down,
12075                window,
12076                cx,
12077            );
12078            top_pane_id
12079        });
12080        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12081            let bottom_pane_id = workspace.active_pane().entity_id();
12082            workspace.add_item_to_active_pane(
12083                Box::new(bottom_item.clone()),
12084                None,
12085                false,
12086                window,
12087                cx,
12088            );
12089            workspace.split_pane(
12090                workspace.active_pane().clone(),
12091                SplitDirection::Up,
12092                window,
12093                cx,
12094            );
12095            bottom_pane_id
12096        });
12097        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12098            let left_pane_id = workspace.active_pane().entity_id();
12099            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12100            workspace.split_pane(
12101                workspace.active_pane().clone(),
12102                SplitDirection::Right,
12103                window,
12104                cx,
12105            );
12106            left_pane_id
12107        });
12108        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12109            let right_pane_id = workspace.active_pane().entity_id();
12110            workspace.add_item_to_active_pane(
12111                Box::new(right_item.clone()),
12112                None,
12113                false,
12114                window,
12115                cx,
12116            );
12117            workspace.split_pane(
12118                workspace.active_pane().clone(),
12119                SplitDirection::Left,
12120                window,
12121                cx,
12122            );
12123            right_pane_id
12124        });
12125        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12126            let center_pane_id = workspace.active_pane().entity_id();
12127            workspace.add_item_to_active_pane(
12128                Box::new(center_item.clone()),
12129                None,
12130                false,
12131                window,
12132                cx,
12133            );
12134            center_pane_id
12135        });
12136        cx.executor().run_until_parked();
12137
12138        workspace.update_in(cx, |workspace, window, cx| {
12139            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12140
12141            // Join into next from center pane into right
12142            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12143        });
12144
12145        workspace.update_in(cx, |workspace, window, cx| {
12146            let active_pane = workspace.active_pane();
12147            assert_eq!(right_pane_id, active_pane.entity_id());
12148            assert_eq!(2, active_pane.read(cx).items_len());
12149            let item_ids_in_pane =
12150                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12151            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12152            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12153
12154            // Join into next from right pane into bottom
12155            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12156        });
12157
12158        workspace.update_in(cx, |workspace, window, cx| {
12159            let active_pane = workspace.active_pane();
12160            assert_eq!(bottom_pane_id, active_pane.entity_id());
12161            assert_eq!(3, active_pane.read(cx).items_len());
12162            let item_ids_in_pane =
12163                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12164            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12165            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12166            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12167
12168            // Join into next from bottom pane into left
12169            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12170        });
12171
12172        workspace.update_in(cx, |workspace, window, cx| {
12173            let active_pane = workspace.active_pane();
12174            assert_eq!(left_pane_id, active_pane.entity_id());
12175            assert_eq!(4, active_pane.read(cx).items_len());
12176            let item_ids_in_pane =
12177                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12178            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12179            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12180            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12181            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12182
12183            // Join into next from left pane into top
12184            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12185        });
12186
12187        workspace.update_in(cx, |workspace, window, cx| {
12188            let active_pane = workspace.active_pane();
12189            assert_eq!(top_pane_id, active_pane.entity_id());
12190            assert_eq!(5, active_pane.read(cx).items_len());
12191            let item_ids_in_pane =
12192                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12193            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12194            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12195            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12196            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12197            assert!(item_ids_in_pane.contains(&top_item.item_id()));
12198
12199            // Single pane left: no-op
12200            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12201        });
12202
12203        workspace.update(cx, |workspace, _cx| {
12204            let active_pane = workspace.active_pane();
12205            assert_eq!(top_pane_id, active_pane.entity_id());
12206        });
12207    }
12208
12209    fn add_an_item_to_active_pane(
12210        cx: &mut VisualTestContext,
12211        workspace: &Entity<Workspace>,
12212        item_id: u64,
12213    ) -> Entity<TestItem> {
12214        let item = cx.new(|cx| {
12215            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12216                item_id,
12217                "item{item_id}.txt",
12218                cx,
12219            )])
12220        });
12221        workspace.update_in(cx, |workspace, window, cx| {
12222            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12223        });
12224        item
12225    }
12226
12227    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12228        workspace.update_in(cx, |workspace, window, cx| {
12229            workspace.split_pane(
12230                workspace.active_pane().clone(),
12231                SplitDirection::Right,
12232                window,
12233                cx,
12234            )
12235        })
12236    }
12237
12238    #[gpui::test]
12239    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12240        init_test(cx);
12241        let fs = FakeFs::new(cx.executor());
12242        let project = Project::test(fs, None, cx).await;
12243        let (workspace, cx) =
12244            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12245
12246        add_an_item_to_active_pane(cx, &workspace, 1);
12247        split_pane(cx, &workspace);
12248        add_an_item_to_active_pane(cx, &workspace, 2);
12249        split_pane(cx, &workspace); // empty pane
12250        split_pane(cx, &workspace);
12251        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12252
12253        cx.executor().run_until_parked();
12254
12255        workspace.update(cx, |workspace, cx| {
12256            let num_panes = workspace.panes().len();
12257            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12258            let active_item = workspace
12259                .active_pane()
12260                .read(cx)
12261                .active_item()
12262                .expect("item is in focus");
12263
12264            assert_eq!(num_panes, 4);
12265            assert_eq!(num_items_in_current_pane, 1);
12266            assert_eq!(active_item.item_id(), last_item.item_id());
12267        });
12268
12269        workspace.update_in(cx, |workspace, window, cx| {
12270            workspace.join_all_panes(window, cx);
12271        });
12272
12273        workspace.update(cx, |workspace, cx| {
12274            let num_panes = workspace.panes().len();
12275            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12276            let active_item = workspace
12277                .active_pane()
12278                .read(cx)
12279                .active_item()
12280                .expect("item is in focus");
12281
12282            assert_eq!(num_panes, 1);
12283            assert_eq!(num_items_in_current_pane, 3);
12284            assert_eq!(active_item.item_id(), last_item.item_id());
12285        });
12286    }
12287
12288    #[gpui::test]
12289    async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12290        init_test(cx);
12291        let fs = FakeFs::new(cx.executor());
12292
12293        let project = Project::test(fs, [], cx).await;
12294        let (multi_workspace, cx) =
12295            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12296        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12297
12298        workspace.update(cx, |workspace, _cx| {
12299            workspace.bounds.size.width = px(800.);
12300        });
12301
12302        workspace.update_in(cx, |workspace, window, cx| {
12303            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12304            workspace.add_panel(panel, window, cx);
12305            workspace.toggle_dock(DockPosition::Right, window, cx);
12306        });
12307
12308        let (panel, resized_width, ratio_basis_width) =
12309            workspace.update_in(cx, |workspace, window, cx| {
12310                let item = cx.new(|cx| {
12311                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12312                });
12313                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12314
12315                let dock = workspace.right_dock().read(cx);
12316                let workspace_width = workspace.bounds.size.width;
12317                let initial_width = workspace
12318                    .dock_size(&dock, window, cx)
12319                    .expect("flexible dock should have an initial width");
12320
12321                assert_eq!(initial_width, workspace_width / 2.);
12322
12323                workspace.resize_right_dock(px(300.), window, cx);
12324
12325                let dock = workspace.right_dock().read(cx);
12326                let resized_width = workspace
12327                    .dock_size(&dock, window, cx)
12328                    .expect("flexible dock should keep its resized width");
12329
12330                assert_eq!(resized_width, px(300.));
12331
12332                let panel = workspace
12333                    .right_dock()
12334                    .read(cx)
12335                    .visible_panel()
12336                    .expect("flexible dock should have a visible panel")
12337                    .panel_id();
12338
12339                (panel, resized_width, workspace_width)
12340            });
12341
12342        workspace.update_in(cx, |workspace, window, cx| {
12343            workspace.toggle_dock(DockPosition::Right, window, cx);
12344            workspace.toggle_dock(DockPosition::Right, window, cx);
12345
12346            let dock = workspace.right_dock().read(cx);
12347            let reopened_width = workspace
12348                .dock_size(&dock, window, cx)
12349                .expect("flexible dock should restore when reopened");
12350
12351            assert_eq!(reopened_width, resized_width);
12352
12353            let right_dock = workspace.right_dock().read(cx);
12354            let flexible_panel = right_dock
12355                .visible_panel()
12356                .expect("flexible dock should still have a visible panel");
12357            assert_eq!(flexible_panel.panel_id(), panel);
12358            assert_eq!(
12359                right_dock
12360                    .stored_panel_size_state(flexible_panel.as_ref())
12361                    .and_then(|size_state| size_state.flexible_size_ratio),
12362                Some(resized_width.to_f64() as f32 / workspace.bounds.size.width.to_f64() as f32)
12363            );
12364        });
12365
12366        workspace.update_in(cx, |workspace, window, cx| {
12367            workspace.split_pane(
12368                workspace.active_pane().clone(),
12369                SplitDirection::Right,
12370                window,
12371                cx,
12372            );
12373
12374            let dock = workspace.right_dock().read(cx);
12375            let split_width = workspace
12376                .dock_size(&dock, window, cx)
12377                .expect("flexible dock should keep its user-resized proportion");
12378
12379            assert_eq!(split_width, px(300.));
12380
12381            workspace.bounds.size.width = px(1600.);
12382
12383            let dock = workspace.right_dock().read(cx);
12384            let resized_window_width = workspace
12385                .dock_size(&dock, window, cx)
12386                .expect("flexible dock should preserve proportional size on window resize");
12387
12388            assert_eq!(
12389                resized_window_width,
12390                workspace.bounds.size.width
12391                    * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12392            );
12393        });
12394    }
12395
12396    #[gpui::test]
12397    async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12398        init_test(cx);
12399        let fs = FakeFs::new(cx.executor());
12400
12401        // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12402        {
12403            let project = Project::test(fs.clone(), [], cx).await;
12404            let (multi_workspace, cx) =
12405                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12406            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12407
12408            workspace.update(cx, |workspace, _cx| {
12409                workspace.set_random_database_id();
12410                workspace.bounds.size.width = px(800.);
12411            });
12412
12413            let panel = workspace.update_in(cx, |workspace, window, cx| {
12414                let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12415                workspace.add_panel(panel.clone(), window, cx);
12416                workspace.toggle_dock(DockPosition::Left, window, cx);
12417                panel
12418            });
12419
12420            workspace.update_in(cx, |workspace, window, cx| {
12421                workspace.resize_left_dock(px(350.), window, cx);
12422            });
12423
12424            cx.run_until_parked();
12425
12426            let persisted = workspace.read_with(cx, |workspace, cx| {
12427                workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12428            });
12429            assert_eq!(
12430                persisted.and_then(|s| s.size),
12431                Some(px(350.)),
12432                "fixed-width panel size should be persisted to KVP"
12433            );
12434
12435            // Remove the panel and re-add a fresh instance with the same key.
12436            // The new instance should have its size state restored from KVP.
12437            workspace.update_in(cx, |workspace, window, cx| {
12438                workspace.remove_panel(&panel, window, cx);
12439            });
12440
12441            workspace.update_in(cx, |workspace, window, cx| {
12442                let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12443                workspace.add_panel(new_panel, window, cx);
12444
12445                let left_dock = workspace.left_dock().read(cx);
12446                let size_state = left_dock
12447                    .panel::<TestPanel>()
12448                    .and_then(|p| left_dock.stored_panel_size_state(&p));
12449                assert_eq!(
12450                    size_state.and_then(|s| s.size),
12451                    Some(px(350.)),
12452                    "re-added fixed-width panel should restore persisted size from KVP"
12453                );
12454            });
12455        }
12456
12457        // Flexible panel: both pixel size and ratio are persisted and restored.
12458        {
12459            let project = Project::test(fs.clone(), [], cx).await;
12460            let (multi_workspace, cx) =
12461                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12462            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12463
12464            workspace.update(cx, |workspace, _cx| {
12465                workspace.set_random_database_id();
12466                workspace.bounds.size.width = px(800.);
12467            });
12468
12469            let panel = workspace.update_in(cx, |workspace, window, cx| {
12470                let item = cx.new(|cx| {
12471                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12472                });
12473                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12474
12475                let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12476                workspace.add_panel(panel.clone(), window, cx);
12477                workspace.toggle_dock(DockPosition::Right, window, cx);
12478                panel
12479            });
12480
12481            workspace.update_in(cx, |workspace, window, cx| {
12482                workspace.resize_right_dock(px(300.), window, cx);
12483            });
12484
12485            cx.run_until_parked();
12486
12487            let persisted = workspace
12488                .read_with(cx, |workspace, cx| {
12489                    workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12490                })
12491                .expect("flexible panel state should be persisted to KVP");
12492            assert_eq!(
12493                persisted.size, None,
12494                "flexible panel should not persist a redundant pixel size"
12495            );
12496            let original_ratio = persisted
12497                .flexible_size_ratio
12498                .expect("flexible panel ratio should be persisted");
12499
12500            // Remove the panel and re-add: both size and ratio should be restored.
12501            workspace.update_in(cx, |workspace, window, cx| {
12502                workspace.remove_panel(&panel, window, cx);
12503            });
12504
12505            workspace.update_in(cx, |workspace, window, cx| {
12506                let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12507                workspace.add_panel(new_panel, window, cx);
12508
12509                let right_dock = workspace.right_dock().read(cx);
12510                let size_state = right_dock
12511                    .panel::<TestPanel>()
12512                    .and_then(|p| right_dock.stored_panel_size_state(&p))
12513                    .expect("re-added flexible panel should have restored size state from KVP");
12514                assert_eq!(
12515                    size_state.size, None,
12516                    "re-added flexible panel should not have a persisted pixel size"
12517                );
12518                assert_eq!(
12519                    size_state.flexible_size_ratio,
12520                    Some(original_ratio),
12521                    "re-added flexible panel should restore persisted ratio"
12522                );
12523            });
12524        }
12525    }
12526
12527    #[gpui::test]
12528    async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12529        init_test(cx);
12530        let fs = FakeFs::new(cx.executor());
12531
12532        let project = Project::test(fs, [], cx).await;
12533        let (multi_workspace, cx) =
12534            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12535        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12536
12537        workspace.update(cx, |workspace, _cx| {
12538            workspace.bounds.size.width = px(900.);
12539        });
12540
12541        // Step 1: Add a tab to the center pane then open a flexible panel in the left
12542        // dock. With one full-width center pane the default ratio is 0.5, so the panel
12543        // and the center pane each take half the workspace width.
12544        workspace.update_in(cx, |workspace, window, cx| {
12545            let item = cx.new(|cx| {
12546                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12547            });
12548            workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12549
12550            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12551            workspace.add_panel(panel, window, cx);
12552            workspace.toggle_dock(DockPosition::Left, window, cx);
12553
12554            let left_dock = workspace.left_dock().read(cx);
12555            let left_width = workspace
12556                .dock_size(&left_dock, window, cx)
12557                .expect("left dock should have an active panel");
12558
12559            assert_eq!(
12560                left_width,
12561                workspace.bounds.size.width / 2.,
12562                "flexible left panel should split evenly with the center pane"
12563            );
12564        });
12565
12566        // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12567        // change horizontal width fractions, so the flexible panel stays at the same
12568        // width as each half of the split.
12569        workspace.update_in(cx, |workspace, window, cx| {
12570            workspace.split_pane(
12571                workspace.active_pane().clone(),
12572                SplitDirection::Down,
12573                window,
12574                cx,
12575            );
12576
12577            let left_dock = workspace.left_dock().read(cx);
12578            let left_width = workspace
12579                .dock_size(&left_dock, window, cx)
12580                .expect("left dock should still have an active panel after vertical split");
12581
12582            assert_eq!(
12583                left_width,
12584                workspace.bounds.size.width / 2.,
12585                "flexible left panel width should match each vertically-split pane"
12586            );
12587        });
12588
12589        // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12590        // size reduces the available width, so the flexible left panel and the center
12591        // panes all shrink proportionally to accommodate it.
12592        workspace.update_in(cx, |workspace, window, cx| {
12593            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12594            workspace.add_panel(panel, window, cx);
12595            workspace.toggle_dock(DockPosition::Right, window, cx);
12596
12597            let right_dock = workspace.right_dock().read(cx);
12598            let right_width = workspace
12599                .dock_size(&right_dock, window, cx)
12600                .expect("right dock should have an active panel");
12601
12602            let left_dock = workspace.left_dock().read(cx);
12603            let left_width = workspace
12604                .dock_size(&left_dock, window, cx)
12605                .expect("left dock should still have an active panel");
12606
12607            let available_width = workspace.bounds.size.width - right_width;
12608            assert_eq!(
12609                left_width,
12610                available_width / 2.,
12611                "flexible left panel should shrink proportionally as the right dock takes space"
12612            );
12613        });
12614    }
12615
12616    struct TestModal(FocusHandle);
12617
12618    impl TestModal {
12619        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12620            Self(cx.focus_handle())
12621        }
12622    }
12623
12624    impl EventEmitter<DismissEvent> for TestModal {}
12625
12626    impl Focusable for TestModal {
12627        fn focus_handle(&self, _cx: &App) -> FocusHandle {
12628            self.0.clone()
12629        }
12630    }
12631
12632    impl ModalView for TestModal {}
12633
12634    impl Render for TestModal {
12635        fn render(
12636            &mut self,
12637            _window: &mut Window,
12638            _cx: &mut Context<TestModal>,
12639        ) -> impl IntoElement {
12640            div().track_focus(&self.0)
12641        }
12642    }
12643
12644    #[gpui::test]
12645    async fn test_panels(cx: &mut gpui::TestAppContext) {
12646        init_test(cx);
12647        let fs = FakeFs::new(cx.executor());
12648
12649        let project = Project::test(fs, [], cx).await;
12650        let (multi_workspace, cx) =
12651            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12652        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12653
12654        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12655            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12656            workspace.add_panel(panel_1.clone(), window, cx);
12657            workspace.toggle_dock(DockPosition::Left, window, cx);
12658            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12659            workspace.add_panel(panel_2.clone(), window, cx);
12660            workspace.toggle_dock(DockPosition::Right, window, cx);
12661
12662            let left_dock = workspace.left_dock();
12663            assert_eq!(
12664                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12665                panel_1.panel_id()
12666            );
12667            assert_eq!(
12668                workspace.dock_size(&left_dock.read(cx), window, cx),
12669                Some(px(300.))
12670            );
12671
12672            workspace.resize_left_dock(px(1337.), window, cx);
12673            assert_eq!(
12674                workspace
12675                    .right_dock()
12676                    .read(cx)
12677                    .visible_panel()
12678                    .unwrap()
12679                    .panel_id(),
12680                panel_2.panel_id(),
12681            );
12682
12683            (panel_1, panel_2)
12684        });
12685
12686        // Move panel_1 to the right
12687        panel_1.update_in(cx, |panel_1, window, cx| {
12688            panel_1.set_position(DockPosition::Right, window, cx)
12689        });
12690
12691        workspace.update_in(cx, |workspace, window, cx| {
12692            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12693            // Since it was the only panel on the left, the left dock should now be closed.
12694            assert!(!workspace.left_dock().read(cx).is_open());
12695            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12696            let right_dock = workspace.right_dock();
12697            assert_eq!(
12698                right_dock.read(cx).visible_panel().unwrap().panel_id(),
12699                panel_1.panel_id()
12700            );
12701            assert_eq!(
12702                right_dock
12703                    .read(cx)
12704                    .active_panel_size()
12705                    .unwrap()
12706                    .size
12707                    .unwrap(),
12708                px(1337.)
12709            );
12710
12711            // Now we move panel_2 to the left
12712            panel_2.set_position(DockPosition::Left, window, cx);
12713        });
12714
12715        workspace.update(cx, |workspace, cx| {
12716            // Since panel_2 was not visible on the right, we don't open the left dock.
12717            assert!(!workspace.left_dock().read(cx).is_open());
12718            // And the right dock is unaffected in its displaying of panel_1
12719            assert!(workspace.right_dock().read(cx).is_open());
12720            assert_eq!(
12721                workspace
12722                    .right_dock()
12723                    .read(cx)
12724                    .visible_panel()
12725                    .unwrap()
12726                    .panel_id(),
12727                panel_1.panel_id(),
12728            );
12729        });
12730
12731        // Move panel_1 back to the left
12732        panel_1.update_in(cx, |panel_1, window, cx| {
12733            panel_1.set_position(DockPosition::Left, window, cx)
12734        });
12735
12736        workspace.update_in(cx, |workspace, window, cx| {
12737            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12738            let left_dock = workspace.left_dock();
12739            assert!(left_dock.read(cx).is_open());
12740            assert_eq!(
12741                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12742                panel_1.panel_id()
12743            );
12744            assert_eq!(
12745                workspace.dock_size(&left_dock.read(cx), window, cx),
12746                Some(px(1337.))
12747            );
12748            // And the right dock should be closed as it no longer has any panels.
12749            assert!(!workspace.right_dock().read(cx).is_open());
12750
12751            // Now we move panel_1 to the bottom
12752            panel_1.set_position(DockPosition::Bottom, window, cx);
12753        });
12754
12755        workspace.update_in(cx, |workspace, window, cx| {
12756            // Since panel_1 was visible on the left, we close the left dock.
12757            assert!(!workspace.left_dock().read(cx).is_open());
12758            // The bottom dock is sized based on the panel's default size,
12759            // since the panel orientation changed from vertical to horizontal.
12760            let bottom_dock = workspace.bottom_dock();
12761            assert_eq!(
12762                workspace.dock_size(&bottom_dock.read(cx), window, cx),
12763                Some(px(300.))
12764            );
12765            // Close bottom dock and move panel_1 back to the left.
12766            bottom_dock.update(cx, |bottom_dock, cx| {
12767                bottom_dock.set_open(false, window, cx)
12768            });
12769            panel_1.set_position(DockPosition::Left, window, cx);
12770        });
12771
12772        // Emit activated event on panel 1
12773        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12774
12775        // Now the left dock is open and panel_1 is active and focused.
12776        workspace.update_in(cx, |workspace, window, cx| {
12777            let left_dock = workspace.left_dock();
12778            assert!(left_dock.read(cx).is_open());
12779            assert_eq!(
12780                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12781                panel_1.panel_id(),
12782            );
12783            assert!(panel_1.focus_handle(cx).is_focused(window));
12784        });
12785
12786        // Emit closed event on panel 2, which is not active
12787        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12788
12789        // Wo don't close the left dock, because panel_2 wasn't the active panel
12790        workspace.update(cx, |workspace, cx| {
12791            let left_dock = workspace.left_dock();
12792            assert!(left_dock.read(cx).is_open());
12793            assert_eq!(
12794                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12795                panel_1.panel_id(),
12796            );
12797        });
12798
12799        // Emitting a ZoomIn event shows the panel as zoomed.
12800        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12801        workspace.read_with(cx, |workspace, _| {
12802            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12803            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12804        });
12805
12806        // Move panel to another dock while it is zoomed
12807        panel_1.update_in(cx, |panel, window, cx| {
12808            panel.set_position(DockPosition::Right, window, cx)
12809        });
12810        workspace.read_with(cx, |workspace, _| {
12811            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12812
12813            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12814        });
12815
12816        // This is a helper for getting a:
12817        // - valid focus on an element,
12818        // - that isn't a part of the panes and panels system of the Workspace,
12819        // - and doesn't trigger the 'on_focus_lost' API.
12820        let focus_other_view = {
12821            let workspace = workspace.clone();
12822            move |cx: &mut VisualTestContext| {
12823                workspace.update_in(cx, |workspace, window, cx| {
12824                    if workspace.active_modal::<TestModal>(cx).is_some() {
12825                        workspace.toggle_modal(window, cx, TestModal::new);
12826                        workspace.toggle_modal(window, cx, TestModal::new);
12827                    } else {
12828                        workspace.toggle_modal(window, cx, TestModal::new);
12829                    }
12830                })
12831            }
12832        };
12833
12834        // If focus is transferred to another view that's not a panel or another pane, we still show
12835        // the panel as zoomed.
12836        focus_other_view(cx);
12837        workspace.read_with(cx, |workspace, _| {
12838            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12839            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12840        });
12841
12842        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12843        workspace.update_in(cx, |_workspace, window, cx| {
12844            cx.focus_self(window);
12845        });
12846        workspace.read_with(cx, |workspace, _| {
12847            assert_eq!(workspace.zoomed, None);
12848            assert_eq!(workspace.zoomed_position, None);
12849        });
12850
12851        // If focus is transferred again to another view that's not a panel or a pane, we won't
12852        // show the panel as zoomed because it wasn't zoomed before.
12853        focus_other_view(cx);
12854        workspace.read_with(cx, |workspace, _| {
12855            assert_eq!(workspace.zoomed, None);
12856            assert_eq!(workspace.zoomed_position, None);
12857        });
12858
12859        // When the panel is activated, it is zoomed again.
12860        cx.dispatch_action(ToggleRightDock);
12861        workspace.read_with(cx, |workspace, _| {
12862            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12863            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12864        });
12865
12866        // Emitting a ZoomOut event unzooms the panel.
12867        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12868        workspace.read_with(cx, |workspace, _| {
12869            assert_eq!(workspace.zoomed, None);
12870            assert_eq!(workspace.zoomed_position, None);
12871        });
12872
12873        // Emit closed event on panel 1, which is active
12874        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12875
12876        // Now the left dock is closed, because panel_1 was the active panel
12877        workspace.update(cx, |workspace, cx| {
12878            let right_dock = workspace.right_dock();
12879            assert!(!right_dock.read(cx).is_open());
12880        });
12881    }
12882
12883    #[gpui::test]
12884    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12885        init_test(cx);
12886
12887        let fs = FakeFs::new(cx.background_executor.clone());
12888        let project = Project::test(fs, [], cx).await;
12889        let (workspace, cx) =
12890            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12891        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12892
12893        let dirty_regular_buffer = cx.new(|cx| {
12894            TestItem::new(cx)
12895                .with_dirty(true)
12896                .with_label("1.txt")
12897                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12898        });
12899        let dirty_regular_buffer_2 = cx.new(|cx| {
12900            TestItem::new(cx)
12901                .with_dirty(true)
12902                .with_label("2.txt")
12903                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12904        });
12905        let dirty_multi_buffer_with_both = cx.new(|cx| {
12906            TestItem::new(cx)
12907                .with_dirty(true)
12908                .with_buffer_kind(ItemBufferKind::Multibuffer)
12909                .with_label("Fake Project Search")
12910                .with_project_items(&[
12911                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12912                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12913                ])
12914        });
12915        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12916        workspace.update_in(cx, |workspace, window, cx| {
12917            workspace.add_item(
12918                pane.clone(),
12919                Box::new(dirty_regular_buffer.clone()),
12920                None,
12921                false,
12922                false,
12923                window,
12924                cx,
12925            );
12926            workspace.add_item(
12927                pane.clone(),
12928                Box::new(dirty_regular_buffer_2.clone()),
12929                None,
12930                false,
12931                false,
12932                window,
12933                cx,
12934            );
12935            workspace.add_item(
12936                pane.clone(),
12937                Box::new(dirty_multi_buffer_with_both.clone()),
12938                None,
12939                false,
12940                false,
12941                window,
12942                cx,
12943            );
12944        });
12945
12946        pane.update_in(cx, |pane, window, cx| {
12947            pane.activate_item(2, true, true, window, cx);
12948            assert_eq!(
12949                pane.active_item().unwrap().item_id(),
12950                multi_buffer_with_both_files_id,
12951                "Should select the multi buffer in the pane"
12952            );
12953        });
12954        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12955            pane.close_other_items(
12956                &CloseOtherItems {
12957                    save_intent: Some(SaveIntent::Save),
12958                    close_pinned: true,
12959                },
12960                None,
12961                window,
12962                cx,
12963            )
12964        });
12965        cx.background_executor.run_until_parked();
12966        assert!(!cx.has_pending_prompt());
12967        close_all_but_multi_buffer_task
12968            .await
12969            .expect("Closing all buffers but the multi buffer failed");
12970        pane.update(cx, |pane, cx| {
12971            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12972            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12973            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12974            assert_eq!(pane.items_len(), 1);
12975            assert_eq!(
12976                pane.active_item().unwrap().item_id(),
12977                multi_buffer_with_both_files_id,
12978                "Should have only the multi buffer left in the pane"
12979            );
12980            assert!(
12981                dirty_multi_buffer_with_both.read(cx).is_dirty,
12982                "The multi buffer containing the unsaved buffer should still be dirty"
12983            );
12984        });
12985
12986        dirty_regular_buffer.update(cx, |buffer, cx| {
12987            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12988        });
12989
12990        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12991            pane.close_active_item(
12992                &CloseActiveItem {
12993                    save_intent: Some(SaveIntent::Close),
12994                    close_pinned: false,
12995                },
12996                window,
12997                cx,
12998            )
12999        });
13000        cx.background_executor.run_until_parked();
13001        assert!(
13002            cx.has_pending_prompt(),
13003            "Dirty multi buffer should prompt a save dialog"
13004        );
13005        cx.simulate_prompt_answer("Save");
13006        cx.background_executor.run_until_parked();
13007        close_multi_buffer_task
13008            .await
13009            .expect("Closing the multi buffer failed");
13010        pane.update(cx, |pane, cx| {
13011            assert_eq!(
13012                dirty_multi_buffer_with_both.read(cx).save_count,
13013                1,
13014                "Multi buffer item should get be saved"
13015            );
13016            // Test impl does not save inner items, so we do not assert them
13017            assert_eq!(
13018                pane.items_len(),
13019                0,
13020                "No more items should be left in the pane"
13021            );
13022            assert!(pane.active_item().is_none());
13023        });
13024    }
13025
13026    #[gpui::test]
13027    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13028        cx: &mut TestAppContext,
13029    ) {
13030        init_test(cx);
13031
13032        let fs = FakeFs::new(cx.background_executor.clone());
13033        let project = Project::test(fs, [], cx).await;
13034        let (workspace, cx) =
13035            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13036        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13037
13038        let dirty_regular_buffer = cx.new(|cx| {
13039            TestItem::new(cx)
13040                .with_dirty(true)
13041                .with_label("1.txt")
13042                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13043        });
13044        let dirty_regular_buffer_2 = cx.new(|cx| {
13045            TestItem::new(cx)
13046                .with_dirty(true)
13047                .with_label("2.txt")
13048                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13049        });
13050        let clear_regular_buffer = cx.new(|cx| {
13051            TestItem::new(cx)
13052                .with_label("3.txt")
13053                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13054        });
13055
13056        let dirty_multi_buffer_with_both = cx.new(|cx| {
13057            TestItem::new(cx)
13058                .with_dirty(true)
13059                .with_buffer_kind(ItemBufferKind::Multibuffer)
13060                .with_label("Fake Project Search")
13061                .with_project_items(&[
13062                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13063                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13064                    clear_regular_buffer.read(cx).project_items[0].clone(),
13065                ])
13066        });
13067        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13068        workspace.update_in(cx, |workspace, window, cx| {
13069            workspace.add_item(
13070                pane.clone(),
13071                Box::new(dirty_regular_buffer.clone()),
13072                None,
13073                false,
13074                false,
13075                window,
13076                cx,
13077            );
13078            workspace.add_item(
13079                pane.clone(),
13080                Box::new(dirty_multi_buffer_with_both.clone()),
13081                None,
13082                false,
13083                false,
13084                window,
13085                cx,
13086            );
13087        });
13088
13089        pane.update_in(cx, |pane, window, cx| {
13090            pane.activate_item(1, true, true, window, cx);
13091            assert_eq!(
13092                pane.active_item().unwrap().item_id(),
13093                multi_buffer_with_both_files_id,
13094                "Should select the multi buffer in the pane"
13095            );
13096        });
13097        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13098            pane.close_active_item(
13099                &CloseActiveItem {
13100                    save_intent: None,
13101                    close_pinned: false,
13102                },
13103                window,
13104                cx,
13105            )
13106        });
13107        cx.background_executor.run_until_parked();
13108        assert!(
13109            cx.has_pending_prompt(),
13110            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13111        );
13112    }
13113
13114    /// Tests that when `close_on_file_delete` is enabled, files are automatically
13115    /// closed when they are deleted from disk.
13116    #[gpui::test]
13117    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13118        init_test(cx);
13119
13120        // Enable the close_on_disk_deletion setting
13121        cx.update_global(|store: &mut SettingsStore, cx| {
13122            store.update_user_settings(cx, |settings| {
13123                settings.workspace.close_on_file_delete = Some(true);
13124            });
13125        });
13126
13127        let fs = FakeFs::new(cx.background_executor.clone());
13128        let project = Project::test(fs, [], cx).await;
13129        let (workspace, cx) =
13130            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13131        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13132
13133        // Create a test item that simulates a file
13134        let item = cx.new(|cx| {
13135            TestItem::new(cx)
13136                .with_label("test.txt")
13137                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13138        });
13139
13140        // Add item to workspace
13141        workspace.update_in(cx, |workspace, window, cx| {
13142            workspace.add_item(
13143                pane.clone(),
13144                Box::new(item.clone()),
13145                None,
13146                false,
13147                false,
13148                window,
13149                cx,
13150            );
13151        });
13152
13153        // Verify the item is in the pane
13154        pane.read_with(cx, |pane, _| {
13155            assert_eq!(pane.items().count(), 1);
13156        });
13157
13158        // Simulate file deletion by setting the item's deleted state
13159        item.update(cx, |item, _| {
13160            item.set_has_deleted_file(true);
13161        });
13162
13163        // Emit UpdateTab event to trigger the close behavior
13164        cx.run_until_parked();
13165        item.update(cx, |_, cx| {
13166            cx.emit(ItemEvent::UpdateTab);
13167        });
13168
13169        // Allow the close operation to complete
13170        cx.run_until_parked();
13171
13172        // Verify the item was automatically closed
13173        pane.read_with(cx, |pane, _| {
13174            assert_eq!(
13175                pane.items().count(),
13176                0,
13177                "Item should be automatically closed when file is deleted"
13178            );
13179        });
13180    }
13181
13182    /// Tests that when `close_on_file_delete` is disabled (default), files remain
13183    /// open with a strikethrough when they are deleted from disk.
13184    #[gpui::test]
13185    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13186        init_test(cx);
13187
13188        // Ensure close_on_disk_deletion is disabled (default)
13189        cx.update_global(|store: &mut SettingsStore, cx| {
13190            store.update_user_settings(cx, |settings| {
13191                settings.workspace.close_on_file_delete = Some(false);
13192            });
13193        });
13194
13195        let fs = FakeFs::new(cx.background_executor.clone());
13196        let project = Project::test(fs, [], cx).await;
13197        let (workspace, cx) =
13198            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13199        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13200
13201        // Create a test item that simulates a file
13202        let item = cx.new(|cx| {
13203            TestItem::new(cx)
13204                .with_label("test.txt")
13205                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13206        });
13207
13208        // Add item to workspace
13209        workspace.update_in(cx, |workspace, window, cx| {
13210            workspace.add_item(
13211                pane.clone(),
13212                Box::new(item.clone()),
13213                None,
13214                false,
13215                false,
13216                window,
13217                cx,
13218            );
13219        });
13220
13221        // Verify the item is in the pane
13222        pane.read_with(cx, |pane, _| {
13223            assert_eq!(pane.items().count(), 1);
13224        });
13225
13226        // Simulate file deletion
13227        item.update(cx, |item, _| {
13228            item.set_has_deleted_file(true);
13229        });
13230
13231        // Emit UpdateTab event
13232        cx.run_until_parked();
13233        item.update(cx, |_, cx| {
13234            cx.emit(ItemEvent::UpdateTab);
13235        });
13236
13237        // Allow any potential close operation to complete
13238        cx.run_until_parked();
13239
13240        // Verify the item remains open (with strikethrough)
13241        pane.read_with(cx, |pane, _| {
13242            assert_eq!(
13243                pane.items().count(),
13244                1,
13245                "Item should remain open when close_on_disk_deletion is disabled"
13246            );
13247        });
13248
13249        // Verify the item shows as deleted
13250        item.read_with(cx, |item, _| {
13251            assert!(
13252                item.has_deleted_file,
13253                "Item should be marked as having deleted file"
13254            );
13255        });
13256    }
13257
13258    /// Tests that dirty files are not automatically closed when deleted from disk,
13259    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13260    /// unsaved changes without being prompted.
13261    #[gpui::test]
13262    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13263        init_test(cx);
13264
13265        // Enable the close_on_file_delete setting
13266        cx.update_global(|store: &mut SettingsStore, cx| {
13267            store.update_user_settings(cx, |settings| {
13268                settings.workspace.close_on_file_delete = Some(true);
13269            });
13270        });
13271
13272        let fs = FakeFs::new(cx.background_executor.clone());
13273        let project = Project::test(fs, [], cx).await;
13274        let (workspace, cx) =
13275            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13276        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13277
13278        // Create a dirty test item
13279        let item = cx.new(|cx| {
13280            TestItem::new(cx)
13281                .with_dirty(true)
13282                .with_label("test.txt")
13283                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13284        });
13285
13286        // Add item to workspace
13287        workspace.update_in(cx, |workspace, window, cx| {
13288            workspace.add_item(
13289                pane.clone(),
13290                Box::new(item.clone()),
13291                None,
13292                false,
13293                false,
13294                window,
13295                cx,
13296            );
13297        });
13298
13299        // Simulate file deletion
13300        item.update(cx, |item, _| {
13301            item.set_has_deleted_file(true);
13302        });
13303
13304        // Emit UpdateTab event to trigger the close behavior
13305        cx.run_until_parked();
13306        item.update(cx, |_, cx| {
13307            cx.emit(ItemEvent::UpdateTab);
13308        });
13309
13310        // Allow any potential close operation to complete
13311        cx.run_until_parked();
13312
13313        // Verify the item remains open (dirty files are not auto-closed)
13314        pane.read_with(cx, |pane, _| {
13315            assert_eq!(
13316                pane.items().count(),
13317                1,
13318                "Dirty items should not be automatically closed even when file is deleted"
13319            );
13320        });
13321
13322        // Verify the item is marked as deleted and still dirty
13323        item.read_with(cx, |item, _| {
13324            assert!(
13325                item.has_deleted_file,
13326                "Item should be marked as having deleted file"
13327            );
13328            assert!(item.is_dirty, "Item should still be dirty");
13329        });
13330    }
13331
13332    /// Tests that navigation history is cleaned up when files are auto-closed
13333    /// due to deletion from disk.
13334    #[gpui::test]
13335    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13336        init_test(cx);
13337
13338        // Enable the close_on_file_delete setting
13339        cx.update_global(|store: &mut SettingsStore, cx| {
13340            store.update_user_settings(cx, |settings| {
13341                settings.workspace.close_on_file_delete = Some(true);
13342            });
13343        });
13344
13345        let fs = FakeFs::new(cx.background_executor.clone());
13346        let project = Project::test(fs, [], cx).await;
13347        let (workspace, cx) =
13348            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13349        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13350
13351        // Create test items
13352        let item1 = cx.new(|cx| {
13353            TestItem::new(cx)
13354                .with_label("test1.txt")
13355                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13356        });
13357        let item1_id = item1.item_id();
13358
13359        let item2 = cx.new(|cx| {
13360            TestItem::new(cx)
13361                .with_label("test2.txt")
13362                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13363        });
13364
13365        // Add items to workspace
13366        workspace.update_in(cx, |workspace, window, cx| {
13367            workspace.add_item(
13368                pane.clone(),
13369                Box::new(item1.clone()),
13370                None,
13371                false,
13372                false,
13373                window,
13374                cx,
13375            );
13376            workspace.add_item(
13377                pane.clone(),
13378                Box::new(item2.clone()),
13379                None,
13380                false,
13381                false,
13382                window,
13383                cx,
13384            );
13385        });
13386
13387        // Activate item1 to ensure it gets navigation entries
13388        pane.update_in(cx, |pane, window, cx| {
13389            pane.activate_item(0, true, true, window, cx);
13390        });
13391
13392        // Switch to item2 and back to create navigation history
13393        pane.update_in(cx, |pane, window, cx| {
13394            pane.activate_item(1, true, true, window, cx);
13395        });
13396        cx.run_until_parked();
13397
13398        pane.update_in(cx, |pane, window, cx| {
13399            pane.activate_item(0, true, true, window, cx);
13400        });
13401        cx.run_until_parked();
13402
13403        // Simulate file deletion for item1
13404        item1.update(cx, |item, _| {
13405            item.set_has_deleted_file(true);
13406        });
13407
13408        // Emit UpdateTab event to trigger the close behavior
13409        item1.update(cx, |_, cx| {
13410            cx.emit(ItemEvent::UpdateTab);
13411        });
13412        cx.run_until_parked();
13413
13414        // Verify item1 was closed
13415        pane.read_with(cx, |pane, _| {
13416            assert_eq!(
13417                pane.items().count(),
13418                1,
13419                "Should have 1 item remaining after auto-close"
13420            );
13421        });
13422
13423        // Check navigation history after close
13424        let has_item = pane.read_with(cx, |pane, cx| {
13425            let mut has_item = false;
13426            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13427                if entry.item.id() == item1_id {
13428                    has_item = true;
13429                }
13430            });
13431            has_item
13432        });
13433
13434        assert!(
13435            !has_item,
13436            "Navigation history should not contain closed item entries"
13437        );
13438    }
13439
13440    #[gpui::test]
13441    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13442        cx: &mut TestAppContext,
13443    ) {
13444        init_test(cx);
13445
13446        let fs = FakeFs::new(cx.background_executor.clone());
13447        let project = Project::test(fs, [], cx).await;
13448        let (workspace, cx) =
13449            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13450        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13451
13452        let dirty_regular_buffer = cx.new(|cx| {
13453            TestItem::new(cx)
13454                .with_dirty(true)
13455                .with_label("1.txt")
13456                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13457        });
13458        let dirty_regular_buffer_2 = cx.new(|cx| {
13459            TestItem::new(cx)
13460                .with_dirty(true)
13461                .with_label("2.txt")
13462                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13463        });
13464        let clear_regular_buffer = cx.new(|cx| {
13465            TestItem::new(cx)
13466                .with_label("3.txt")
13467                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13468        });
13469
13470        let dirty_multi_buffer = cx.new(|cx| {
13471            TestItem::new(cx)
13472                .with_dirty(true)
13473                .with_buffer_kind(ItemBufferKind::Multibuffer)
13474                .with_label("Fake Project Search")
13475                .with_project_items(&[
13476                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13477                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13478                    clear_regular_buffer.read(cx).project_items[0].clone(),
13479                ])
13480        });
13481        workspace.update_in(cx, |workspace, window, cx| {
13482            workspace.add_item(
13483                pane.clone(),
13484                Box::new(dirty_regular_buffer.clone()),
13485                None,
13486                false,
13487                false,
13488                window,
13489                cx,
13490            );
13491            workspace.add_item(
13492                pane.clone(),
13493                Box::new(dirty_regular_buffer_2.clone()),
13494                None,
13495                false,
13496                false,
13497                window,
13498                cx,
13499            );
13500            workspace.add_item(
13501                pane.clone(),
13502                Box::new(dirty_multi_buffer.clone()),
13503                None,
13504                false,
13505                false,
13506                window,
13507                cx,
13508            );
13509        });
13510
13511        pane.update_in(cx, |pane, window, cx| {
13512            pane.activate_item(2, true, true, window, cx);
13513            assert_eq!(
13514                pane.active_item().unwrap().item_id(),
13515                dirty_multi_buffer.item_id(),
13516                "Should select the multi buffer in the pane"
13517            );
13518        });
13519        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13520            pane.close_active_item(
13521                &CloseActiveItem {
13522                    save_intent: None,
13523                    close_pinned: false,
13524                },
13525                window,
13526                cx,
13527            )
13528        });
13529        cx.background_executor.run_until_parked();
13530        assert!(
13531            !cx.has_pending_prompt(),
13532            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13533        );
13534        close_multi_buffer_task
13535            .await
13536            .expect("Closing multi buffer failed");
13537        pane.update(cx, |pane, cx| {
13538            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13539            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13540            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13541            assert_eq!(
13542                pane.items()
13543                    .map(|item| item.item_id())
13544                    .sorted()
13545                    .collect::<Vec<_>>(),
13546                vec![
13547                    dirty_regular_buffer.item_id(),
13548                    dirty_regular_buffer_2.item_id(),
13549                ],
13550                "Should have no multi buffer left in the pane"
13551            );
13552            assert!(dirty_regular_buffer.read(cx).is_dirty);
13553            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13554        });
13555    }
13556
13557    #[gpui::test]
13558    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13559        init_test(cx);
13560        let fs = FakeFs::new(cx.executor());
13561        let project = Project::test(fs, [], cx).await;
13562        let (multi_workspace, cx) =
13563            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13564        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13565
13566        // Add a new panel to the right dock, opening the dock and setting the
13567        // focus to the new panel.
13568        let panel = workspace.update_in(cx, |workspace, window, cx| {
13569            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13570            workspace.add_panel(panel.clone(), window, cx);
13571
13572            workspace
13573                .right_dock()
13574                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13575
13576            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13577
13578            panel
13579        });
13580
13581        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13582        // panel to the next valid position which, in this case, is the left
13583        // dock.
13584        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13585        workspace.update(cx, |workspace, cx| {
13586            assert!(workspace.left_dock().read(cx).is_open());
13587            assert_eq!(panel.read(cx).position, DockPosition::Left);
13588        });
13589
13590        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13591        // panel to the next valid position which, in this case, is the bottom
13592        // dock.
13593        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13594        workspace.update(cx, |workspace, cx| {
13595            assert!(workspace.bottom_dock().read(cx).is_open());
13596            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13597        });
13598
13599        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13600        // around moving the panel to its initial position, the right dock.
13601        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13602        workspace.update(cx, |workspace, cx| {
13603            assert!(workspace.right_dock().read(cx).is_open());
13604            assert_eq!(panel.read(cx).position, DockPosition::Right);
13605        });
13606
13607        // Remove focus from the panel, ensuring that, if the panel is not
13608        // focused, the `MoveFocusedPanelToNextPosition` action does not update
13609        // the panel's position, so the panel is still in the right dock.
13610        workspace.update_in(cx, |workspace, window, cx| {
13611            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13612        });
13613
13614        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13615        workspace.update(cx, |workspace, cx| {
13616            assert!(workspace.right_dock().read(cx).is_open());
13617            assert_eq!(panel.read(cx).position, DockPosition::Right);
13618        });
13619    }
13620
13621    #[gpui::test]
13622    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13623        init_test(cx);
13624
13625        let fs = FakeFs::new(cx.executor());
13626        let project = Project::test(fs, [], cx).await;
13627        let (workspace, cx) =
13628            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13629
13630        let item_1 = cx.new(|cx| {
13631            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13632        });
13633        workspace.update_in(cx, |workspace, window, cx| {
13634            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13635            workspace.move_item_to_pane_in_direction(
13636                &MoveItemToPaneInDirection {
13637                    direction: SplitDirection::Right,
13638                    focus: true,
13639                    clone: false,
13640                },
13641                window,
13642                cx,
13643            );
13644            workspace.move_item_to_pane_at_index(
13645                &MoveItemToPane {
13646                    destination: 3,
13647                    focus: true,
13648                    clone: false,
13649                },
13650                window,
13651                cx,
13652            );
13653
13654            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13655            assert_eq!(
13656                pane_items_paths(&workspace.active_pane, cx),
13657                vec!["first.txt".to_string()],
13658                "Single item was not moved anywhere"
13659            );
13660        });
13661
13662        let item_2 = cx.new(|cx| {
13663            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13664        });
13665        workspace.update_in(cx, |workspace, window, cx| {
13666            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13667            assert_eq!(
13668                pane_items_paths(&workspace.panes[0], cx),
13669                vec!["first.txt".to_string(), "second.txt".to_string()],
13670            );
13671            workspace.move_item_to_pane_in_direction(
13672                &MoveItemToPaneInDirection {
13673                    direction: SplitDirection::Right,
13674                    focus: true,
13675                    clone: false,
13676                },
13677                window,
13678                cx,
13679            );
13680
13681            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13682            assert_eq!(
13683                pane_items_paths(&workspace.panes[0], cx),
13684                vec!["first.txt".to_string()],
13685                "After moving, one item should be left in the original pane"
13686            );
13687            assert_eq!(
13688                pane_items_paths(&workspace.panes[1], cx),
13689                vec!["second.txt".to_string()],
13690                "New item should have been moved to the new pane"
13691            );
13692        });
13693
13694        let item_3 = cx.new(|cx| {
13695            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13696        });
13697        workspace.update_in(cx, |workspace, window, cx| {
13698            let original_pane = workspace.panes[0].clone();
13699            workspace.set_active_pane(&original_pane, window, cx);
13700            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13701            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13702            assert_eq!(
13703                pane_items_paths(&workspace.active_pane, cx),
13704                vec!["first.txt".to_string(), "third.txt".to_string()],
13705                "New pane should be ready to move one item out"
13706            );
13707
13708            workspace.move_item_to_pane_at_index(
13709                &MoveItemToPane {
13710                    destination: 3,
13711                    focus: true,
13712                    clone: false,
13713                },
13714                window,
13715                cx,
13716            );
13717            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13718            assert_eq!(
13719                pane_items_paths(&workspace.active_pane, cx),
13720                vec!["first.txt".to_string()],
13721                "After moving, one item should be left in the original pane"
13722            );
13723            assert_eq!(
13724                pane_items_paths(&workspace.panes[1], cx),
13725                vec!["second.txt".to_string()],
13726                "Previously created pane should be unchanged"
13727            );
13728            assert_eq!(
13729                pane_items_paths(&workspace.panes[2], cx),
13730                vec!["third.txt".to_string()],
13731                "New item should have been moved to the new pane"
13732            );
13733        });
13734    }
13735
13736    #[gpui::test]
13737    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13738        init_test(cx);
13739
13740        let fs = FakeFs::new(cx.executor());
13741        let project = Project::test(fs, [], cx).await;
13742        let (workspace, cx) =
13743            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13744
13745        let item_1 = cx.new(|cx| {
13746            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13747        });
13748        workspace.update_in(cx, |workspace, window, cx| {
13749            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13750            workspace.move_item_to_pane_in_direction(
13751                &MoveItemToPaneInDirection {
13752                    direction: SplitDirection::Right,
13753                    focus: true,
13754                    clone: true,
13755                },
13756                window,
13757                cx,
13758            );
13759        });
13760        cx.run_until_parked();
13761        workspace.update_in(cx, |workspace, window, cx| {
13762            workspace.move_item_to_pane_at_index(
13763                &MoveItemToPane {
13764                    destination: 3,
13765                    focus: true,
13766                    clone: true,
13767                },
13768                window,
13769                cx,
13770            );
13771        });
13772        cx.run_until_parked();
13773
13774        workspace.update(cx, |workspace, cx| {
13775            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13776            for pane in workspace.panes() {
13777                assert_eq!(
13778                    pane_items_paths(pane, cx),
13779                    vec!["first.txt".to_string()],
13780                    "Single item exists in all panes"
13781                );
13782            }
13783        });
13784
13785        // verify that the active pane has been updated after waiting for the
13786        // pane focus event to fire and resolve
13787        workspace.read_with(cx, |workspace, _app| {
13788            assert_eq!(
13789                workspace.active_pane(),
13790                &workspace.panes[2],
13791                "The third pane should be the active one: {:?}",
13792                workspace.panes
13793            );
13794        })
13795    }
13796
13797    #[gpui::test]
13798    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13799        init_test(cx);
13800
13801        let fs = FakeFs::new(cx.executor());
13802        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13803
13804        let project = Project::test(fs, ["root".as_ref()], cx).await;
13805        let (workspace, cx) =
13806            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13807
13808        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13809        // Add item to pane A with project path
13810        let item_a = cx.new(|cx| {
13811            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13812        });
13813        workspace.update_in(cx, |workspace, window, cx| {
13814            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13815        });
13816
13817        // Split to create pane B
13818        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13819            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13820        });
13821
13822        // Add item with SAME project path to pane B, and pin it
13823        let item_b = cx.new(|cx| {
13824            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13825        });
13826        pane_b.update_in(cx, |pane, window, cx| {
13827            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13828            pane.set_pinned_count(1);
13829        });
13830
13831        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13832        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13833
13834        // close_pinned: false should only close the unpinned copy
13835        workspace.update_in(cx, |workspace, window, cx| {
13836            workspace.close_item_in_all_panes(
13837                &CloseItemInAllPanes {
13838                    save_intent: Some(SaveIntent::Close),
13839                    close_pinned: false,
13840                },
13841                window,
13842                cx,
13843            )
13844        });
13845        cx.executor().run_until_parked();
13846
13847        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13848        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13849        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13850        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13851
13852        // Split again, seeing as closing the previous item also closed its
13853        // pane, so only pane remains, which does not allow us to properly test
13854        // that both items close when `close_pinned: true`.
13855        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13856            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13857        });
13858
13859        // Add an item with the same project path to pane C so that
13860        // close_item_in_all_panes can determine what to close across all panes
13861        // (it reads the active item from the active pane, and split_pane
13862        // creates an empty pane).
13863        let item_c = cx.new(|cx| {
13864            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13865        });
13866        pane_c.update_in(cx, |pane, window, cx| {
13867            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13868        });
13869
13870        // close_pinned: true should close the pinned copy too
13871        workspace.update_in(cx, |workspace, window, cx| {
13872            let panes_count = workspace.panes().len();
13873            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13874
13875            workspace.close_item_in_all_panes(
13876                &CloseItemInAllPanes {
13877                    save_intent: Some(SaveIntent::Close),
13878                    close_pinned: true,
13879                },
13880                window,
13881                cx,
13882            )
13883        });
13884        cx.executor().run_until_parked();
13885
13886        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13887        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13888        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13889        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13890    }
13891
13892    mod register_project_item_tests {
13893
13894        use super::*;
13895
13896        // View
13897        struct TestPngItemView {
13898            focus_handle: FocusHandle,
13899        }
13900        // Model
13901        struct TestPngItem {}
13902
13903        impl project::ProjectItem for TestPngItem {
13904            fn try_open(
13905                _project: &Entity<Project>,
13906                path: &ProjectPath,
13907                cx: &mut App,
13908            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13909                if path.path.extension().unwrap() == "png" {
13910                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13911                } else {
13912                    None
13913                }
13914            }
13915
13916            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13917                None
13918            }
13919
13920            fn project_path(&self, _: &App) -> Option<ProjectPath> {
13921                None
13922            }
13923
13924            fn is_dirty(&self) -> bool {
13925                false
13926            }
13927        }
13928
13929        impl Item for TestPngItemView {
13930            type Event = ();
13931            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13932                "".into()
13933            }
13934        }
13935        impl EventEmitter<()> for TestPngItemView {}
13936        impl Focusable for TestPngItemView {
13937            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13938                self.focus_handle.clone()
13939            }
13940        }
13941
13942        impl Render for TestPngItemView {
13943            fn render(
13944                &mut self,
13945                _window: &mut Window,
13946                _cx: &mut Context<Self>,
13947            ) -> impl IntoElement {
13948                Empty
13949            }
13950        }
13951
13952        impl ProjectItem for TestPngItemView {
13953            type Item = TestPngItem;
13954
13955            fn for_project_item(
13956                _project: Entity<Project>,
13957                _pane: Option<&Pane>,
13958                _item: Entity<Self::Item>,
13959                _: &mut Window,
13960                cx: &mut Context<Self>,
13961            ) -> Self
13962            where
13963                Self: Sized,
13964            {
13965                Self {
13966                    focus_handle: cx.focus_handle(),
13967                }
13968            }
13969        }
13970
13971        // View
13972        struct TestIpynbItemView {
13973            focus_handle: FocusHandle,
13974        }
13975        // Model
13976        struct TestIpynbItem {}
13977
13978        impl project::ProjectItem for TestIpynbItem {
13979            fn try_open(
13980                _project: &Entity<Project>,
13981                path: &ProjectPath,
13982                cx: &mut App,
13983            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13984                if path.path.extension().unwrap() == "ipynb" {
13985                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13986                } else {
13987                    None
13988                }
13989            }
13990
13991            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13992                None
13993            }
13994
13995            fn project_path(&self, _: &App) -> Option<ProjectPath> {
13996                None
13997            }
13998
13999            fn is_dirty(&self) -> bool {
14000                false
14001            }
14002        }
14003
14004        impl Item for TestIpynbItemView {
14005            type Event = ();
14006            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14007                "".into()
14008            }
14009        }
14010        impl EventEmitter<()> for TestIpynbItemView {}
14011        impl Focusable for TestIpynbItemView {
14012            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14013                self.focus_handle.clone()
14014            }
14015        }
14016
14017        impl Render for TestIpynbItemView {
14018            fn render(
14019                &mut self,
14020                _window: &mut Window,
14021                _cx: &mut Context<Self>,
14022            ) -> impl IntoElement {
14023                Empty
14024            }
14025        }
14026
14027        impl ProjectItem for TestIpynbItemView {
14028            type Item = TestIpynbItem;
14029
14030            fn for_project_item(
14031                _project: Entity<Project>,
14032                _pane: Option<&Pane>,
14033                _item: Entity<Self::Item>,
14034                _: &mut Window,
14035                cx: &mut Context<Self>,
14036            ) -> Self
14037            where
14038                Self: Sized,
14039            {
14040                Self {
14041                    focus_handle: cx.focus_handle(),
14042                }
14043            }
14044        }
14045
14046        struct TestAlternatePngItemView {
14047            focus_handle: FocusHandle,
14048        }
14049
14050        impl Item for TestAlternatePngItemView {
14051            type Event = ();
14052            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14053                "".into()
14054            }
14055        }
14056
14057        impl EventEmitter<()> for TestAlternatePngItemView {}
14058        impl Focusable for TestAlternatePngItemView {
14059            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14060                self.focus_handle.clone()
14061            }
14062        }
14063
14064        impl Render for TestAlternatePngItemView {
14065            fn render(
14066                &mut self,
14067                _window: &mut Window,
14068                _cx: &mut Context<Self>,
14069            ) -> impl IntoElement {
14070                Empty
14071            }
14072        }
14073
14074        impl ProjectItem for TestAlternatePngItemView {
14075            type Item = TestPngItem;
14076
14077            fn for_project_item(
14078                _project: Entity<Project>,
14079                _pane: Option<&Pane>,
14080                _item: Entity<Self::Item>,
14081                _: &mut Window,
14082                cx: &mut Context<Self>,
14083            ) -> Self
14084            where
14085                Self: Sized,
14086            {
14087                Self {
14088                    focus_handle: cx.focus_handle(),
14089                }
14090            }
14091        }
14092
14093        #[gpui::test]
14094        async fn test_register_project_item(cx: &mut TestAppContext) {
14095            init_test(cx);
14096
14097            cx.update(|cx| {
14098                register_project_item::<TestPngItemView>(cx);
14099                register_project_item::<TestIpynbItemView>(cx);
14100            });
14101
14102            let fs = FakeFs::new(cx.executor());
14103            fs.insert_tree(
14104                "/root1",
14105                json!({
14106                    "one.png": "BINARYDATAHERE",
14107                    "two.ipynb": "{ totally a notebook }",
14108                    "three.txt": "editing text, sure why not?"
14109                }),
14110            )
14111            .await;
14112
14113            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14114            let (workspace, cx) =
14115                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14116
14117            let worktree_id = project.update(cx, |project, cx| {
14118                project.worktrees(cx).next().unwrap().read(cx).id()
14119            });
14120
14121            let handle = workspace
14122                .update_in(cx, |workspace, window, cx| {
14123                    let project_path = (worktree_id, rel_path("one.png"));
14124                    workspace.open_path(project_path, None, true, window, cx)
14125                })
14126                .await
14127                .unwrap();
14128
14129            // Now we can check if the handle we got back errored or not
14130            assert_eq!(
14131                handle.to_any_view().entity_type(),
14132                TypeId::of::<TestPngItemView>()
14133            );
14134
14135            let handle = workspace
14136                .update_in(cx, |workspace, window, cx| {
14137                    let project_path = (worktree_id, rel_path("two.ipynb"));
14138                    workspace.open_path(project_path, None, true, window, cx)
14139                })
14140                .await
14141                .unwrap();
14142
14143            assert_eq!(
14144                handle.to_any_view().entity_type(),
14145                TypeId::of::<TestIpynbItemView>()
14146            );
14147
14148            let handle = workspace
14149                .update_in(cx, |workspace, window, cx| {
14150                    let project_path = (worktree_id, rel_path("three.txt"));
14151                    workspace.open_path(project_path, None, true, window, cx)
14152                })
14153                .await;
14154            assert!(handle.is_err());
14155        }
14156
14157        #[gpui::test]
14158        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14159            init_test(cx);
14160
14161            cx.update(|cx| {
14162                register_project_item::<TestPngItemView>(cx);
14163                register_project_item::<TestAlternatePngItemView>(cx);
14164            });
14165
14166            let fs = FakeFs::new(cx.executor());
14167            fs.insert_tree(
14168                "/root1",
14169                json!({
14170                    "one.png": "BINARYDATAHERE",
14171                    "two.ipynb": "{ totally a notebook }",
14172                    "three.txt": "editing text, sure why not?"
14173                }),
14174            )
14175            .await;
14176            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14177            let (workspace, cx) =
14178                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14179            let worktree_id = project.update(cx, |project, cx| {
14180                project.worktrees(cx).next().unwrap().read(cx).id()
14181            });
14182
14183            let handle = workspace
14184                .update_in(cx, |workspace, window, cx| {
14185                    let project_path = (worktree_id, rel_path("one.png"));
14186                    workspace.open_path(project_path, None, true, window, cx)
14187                })
14188                .await
14189                .unwrap();
14190
14191            // This _must_ be the second item registered
14192            assert_eq!(
14193                handle.to_any_view().entity_type(),
14194                TypeId::of::<TestAlternatePngItemView>()
14195            );
14196
14197            let handle = workspace
14198                .update_in(cx, |workspace, window, cx| {
14199                    let project_path = (worktree_id, rel_path("three.txt"));
14200                    workspace.open_path(project_path, None, true, window, cx)
14201                })
14202                .await;
14203            assert!(handle.is_err());
14204        }
14205    }
14206
14207    #[gpui::test]
14208    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14209        init_test(cx);
14210
14211        let fs = FakeFs::new(cx.executor());
14212        let project = Project::test(fs, [], cx).await;
14213        let (workspace, _cx) =
14214            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14215
14216        // Test with status bar shown (default)
14217        workspace.read_with(cx, |workspace, cx| {
14218            let visible = workspace.status_bar_visible(cx);
14219            assert!(visible, "Status bar should be visible by default");
14220        });
14221
14222        // Test with status bar hidden
14223        cx.update_global(|store: &mut SettingsStore, cx| {
14224            store.update_user_settings(cx, |settings| {
14225                settings.status_bar.get_or_insert_default().show = Some(false);
14226            });
14227        });
14228
14229        workspace.read_with(cx, |workspace, cx| {
14230            let visible = workspace.status_bar_visible(cx);
14231            assert!(!visible, "Status bar should be hidden when show is false");
14232        });
14233
14234        // Test with status bar shown explicitly
14235        cx.update_global(|store: &mut SettingsStore, cx| {
14236            store.update_user_settings(cx, |settings| {
14237                settings.status_bar.get_or_insert_default().show = Some(true);
14238            });
14239        });
14240
14241        workspace.read_with(cx, |workspace, cx| {
14242            let visible = workspace.status_bar_visible(cx);
14243            assert!(visible, "Status bar should be visible when show is true");
14244        });
14245    }
14246
14247    #[gpui::test]
14248    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14249        init_test(cx);
14250
14251        let fs = FakeFs::new(cx.executor());
14252        let project = Project::test(fs, [], cx).await;
14253        let (multi_workspace, cx) =
14254            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14255        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14256        let panel = workspace.update_in(cx, |workspace, window, cx| {
14257            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14258            workspace.add_panel(panel.clone(), window, cx);
14259
14260            workspace
14261                .right_dock()
14262                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14263
14264            panel
14265        });
14266
14267        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14268        let item_a = cx.new(TestItem::new);
14269        let item_b = cx.new(TestItem::new);
14270        let item_a_id = item_a.entity_id();
14271        let item_b_id = item_b.entity_id();
14272
14273        pane.update_in(cx, |pane, window, cx| {
14274            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14275            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14276        });
14277
14278        pane.read_with(cx, |pane, _| {
14279            assert_eq!(pane.items_len(), 2);
14280            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14281        });
14282
14283        workspace.update_in(cx, |workspace, window, cx| {
14284            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14285        });
14286
14287        workspace.update_in(cx, |_, window, cx| {
14288            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14289        });
14290
14291        // Assert that the `pane::CloseActiveItem` action is handled at the
14292        // workspace level when one of the dock panels is focused and, in that
14293        // case, the center pane's active item is closed but the focus is not
14294        // moved.
14295        cx.dispatch_action(pane::CloseActiveItem::default());
14296        cx.run_until_parked();
14297
14298        pane.read_with(cx, |pane, _| {
14299            assert_eq!(pane.items_len(), 1);
14300            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14301        });
14302
14303        workspace.update_in(cx, |workspace, window, cx| {
14304            assert!(workspace.right_dock().read(cx).is_open());
14305            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14306        });
14307    }
14308
14309    #[gpui::test]
14310    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14311        init_test(cx);
14312        let fs = FakeFs::new(cx.executor());
14313
14314        let project_a = Project::test(fs.clone(), [], cx).await;
14315        let project_b = Project::test(fs, [], cx).await;
14316
14317        let multi_workspace_handle =
14318            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14319        cx.run_until_parked();
14320
14321        let workspace_a = multi_workspace_handle
14322            .read_with(cx, |mw, _| mw.workspace().clone())
14323            .unwrap();
14324
14325        let _workspace_b = multi_workspace_handle
14326            .update(cx, |mw, window, cx| {
14327                mw.test_add_workspace(project_b, window, cx)
14328            })
14329            .unwrap();
14330
14331        // Switch to workspace A
14332        multi_workspace_handle
14333            .update(cx, |mw, window, cx| {
14334                mw.activate_index(0, window, cx);
14335            })
14336            .unwrap();
14337
14338        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14339
14340        // Add a panel to workspace A's right dock and open the dock
14341        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14342            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14343            workspace.add_panel(panel.clone(), window, cx);
14344            workspace
14345                .right_dock()
14346                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14347            panel
14348        });
14349
14350        // Focus the panel through the workspace (matching existing test pattern)
14351        workspace_a.update_in(cx, |workspace, window, cx| {
14352            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14353        });
14354
14355        // Zoom the panel
14356        panel.update_in(cx, |panel, window, cx| {
14357            panel.set_zoomed(true, window, cx);
14358        });
14359
14360        // Verify the panel is zoomed and the dock is open
14361        workspace_a.update_in(cx, |workspace, window, cx| {
14362            assert!(
14363                workspace.right_dock().read(cx).is_open(),
14364                "dock should be open before switch"
14365            );
14366            assert!(
14367                panel.is_zoomed(window, cx),
14368                "panel should be zoomed before switch"
14369            );
14370            assert!(
14371                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14372                "panel should be focused before switch"
14373            );
14374        });
14375
14376        // Switch to workspace B
14377        multi_workspace_handle
14378            .update(cx, |mw, window, cx| {
14379                mw.activate_index(1, window, cx);
14380            })
14381            .unwrap();
14382        cx.run_until_parked();
14383
14384        // Switch back to workspace A
14385        multi_workspace_handle
14386            .update(cx, |mw, window, cx| {
14387                mw.activate_index(0, window, cx);
14388            })
14389            .unwrap();
14390        cx.run_until_parked();
14391
14392        // Verify the panel is still zoomed and the dock is still open
14393        workspace_a.update_in(cx, |workspace, window, cx| {
14394            assert!(
14395                workspace.right_dock().read(cx).is_open(),
14396                "dock should still be open after switching back"
14397            );
14398            assert!(
14399                panel.is_zoomed(window, cx),
14400                "panel should still be zoomed after switching back"
14401            );
14402        });
14403    }
14404
14405    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14406        pane.read(cx)
14407            .items()
14408            .flat_map(|item| {
14409                item.project_paths(cx)
14410                    .into_iter()
14411                    .map(|path| path.path.display(PathStyle::local()).into_owned())
14412            })
14413            .collect()
14414    }
14415
14416    pub fn init_test(cx: &mut TestAppContext) {
14417        cx.update(|cx| {
14418            let settings_store = SettingsStore::test(cx);
14419            cx.set_global(settings_store);
14420            cx.set_global(db::AppDatabase::test_new());
14421            theme::init(theme::LoadThemes::JustBase, cx);
14422        });
14423    }
14424
14425    #[gpui::test]
14426    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14427        use settings::{ThemeName, ThemeSelection};
14428        use theme::SystemAppearance;
14429        use zed_actions::theme::ToggleMode;
14430
14431        init_test(cx);
14432
14433        let fs = FakeFs::new(cx.executor());
14434        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14435
14436        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14437            .await;
14438
14439        // Build a test project and workspace view so the test can invoke
14440        // the workspace action handler the same way the UI would.
14441        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14442        let (workspace, cx) =
14443            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14444
14445        // Seed the settings file with a plain static light theme so the
14446        // first toggle always starts from a known persisted state.
14447        workspace.update_in(cx, |_workspace, _window, cx| {
14448            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14449            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14450                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14451            });
14452        });
14453        cx.executor().advance_clock(Duration::from_millis(200));
14454        cx.run_until_parked();
14455
14456        // Confirm the initial persisted settings contain the static theme
14457        // we just wrote before any toggling happens.
14458        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14459        assert!(settings_text.contains(r#""theme": "One Light""#));
14460
14461        // Toggle once. This should migrate the persisted theme settings
14462        // into light/dark slots and enable system mode.
14463        workspace.update_in(cx, |workspace, window, cx| {
14464            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14465        });
14466        cx.executor().advance_clock(Duration::from_millis(200));
14467        cx.run_until_parked();
14468
14469        // 1. Static -> Dynamic
14470        // this assertion checks theme changed from static to dynamic.
14471        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14472        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14473        assert_eq!(
14474            parsed["theme"],
14475            serde_json::json!({
14476                "mode": "system",
14477                "light": "One Light",
14478                "dark": "One Dark"
14479            })
14480        );
14481
14482        // 2. Toggle again, suppose it will change the mode to light
14483        workspace.update_in(cx, |workspace, window, cx| {
14484            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14485        });
14486        cx.executor().advance_clock(Duration::from_millis(200));
14487        cx.run_until_parked();
14488
14489        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14490        assert!(settings_text.contains(r#""mode": "light""#));
14491    }
14492
14493    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14494        let item = TestProjectItem::new(id, path, cx);
14495        item.update(cx, |item, _| {
14496            item.is_dirty = true;
14497        });
14498        item
14499    }
14500
14501    #[gpui::test]
14502    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14503        cx: &mut gpui::TestAppContext,
14504    ) {
14505        init_test(cx);
14506        let fs = FakeFs::new(cx.executor());
14507
14508        let project = Project::test(fs, [], cx).await;
14509        let (workspace, cx) =
14510            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14511
14512        let panel = workspace.update_in(cx, |workspace, window, cx| {
14513            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14514            workspace.add_panel(panel.clone(), window, cx);
14515            workspace
14516                .right_dock()
14517                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14518            panel
14519        });
14520
14521        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14522        pane.update_in(cx, |pane, window, cx| {
14523            let item = cx.new(TestItem::new);
14524            pane.add_item(Box::new(item), true, true, None, window, cx);
14525        });
14526
14527        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14528        // mirrors the real-world flow and avoids side effects from directly
14529        // focusing the panel while the center pane is active.
14530        workspace.update_in(cx, |workspace, window, cx| {
14531            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14532        });
14533
14534        panel.update_in(cx, |panel, window, cx| {
14535            panel.set_zoomed(true, window, cx);
14536        });
14537
14538        workspace.update_in(cx, |workspace, window, cx| {
14539            assert!(workspace.right_dock().read(cx).is_open());
14540            assert!(panel.is_zoomed(window, cx));
14541            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14542        });
14543
14544        // Simulate a spurious pane::Event::Focus on the center pane while the
14545        // panel still has focus. This mirrors what happens during macOS window
14546        // activation: the center pane fires a focus event even though actual
14547        // focus remains on the dock panel.
14548        pane.update_in(cx, |_, _, cx| {
14549            cx.emit(pane::Event::Focus);
14550        });
14551
14552        // The dock must remain open because the panel had focus at the time the
14553        // event was processed. Before the fix, dock_to_preserve was None for
14554        // panels that don't implement pane(), causing the dock to close.
14555        workspace.update_in(cx, |workspace, window, cx| {
14556            assert!(
14557                workspace.right_dock().read(cx).is_open(),
14558                "Dock should stay open when its zoomed panel (without pane()) still has focus"
14559            );
14560            assert!(panel.is_zoomed(window, cx));
14561        });
14562    }
14563
14564    #[gpui::test]
14565    async fn test_panels_stay_open_after_position_change_and_settings_update(
14566        cx: &mut gpui::TestAppContext,
14567    ) {
14568        init_test(cx);
14569        let fs = FakeFs::new(cx.executor());
14570        let project = Project::test(fs, [], cx).await;
14571        let (workspace, cx) =
14572            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14573
14574        // Add two panels to the left dock and open it.
14575        let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14576            let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14577            let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14578            workspace.add_panel(panel_a.clone(), window, cx);
14579            workspace.add_panel(panel_b.clone(), window, cx);
14580            workspace.left_dock().update(cx, |dock, cx| {
14581                dock.set_open(true, window, cx);
14582                dock.activate_panel(0, window, cx);
14583            });
14584            (panel_a, panel_b)
14585        });
14586
14587        workspace.update_in(cx, |workspace, _, cx| {
14588            assert!(workspace.left_dock().read(cx).is_open());
14589        });
14590
14591        // Simulate a feature flag changing default dock positions: both panels
14592        // move from Left to Right.
14593        workspace.update_in(cx, |_workspace, _window, cx| {
14594            panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14595            panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14596            cx.update_global::<SettingsStore, _>(|_, _| {});
14597        });
14598
14599        // Both panels should now be in the right dock.
14600        workspace.update_in(cx, |workspace, _, cx| {
14601            let right_dock = workspace.right_dock().read(cx);
14602            assert_eq!(right_dock.panels_len(), 2);
14603        });
14604
14605        // Open the right dock and activate panel_b (simulating the user
14606        // opening the panel after it moved).
14607        workspace.update_in(cx, |workspace, window, cx| {
14608            workspace.right_dock().update(cx, |dock, cx| {
14609                dock.set_open(true, window, cx);
14610                dock.activate_panel(1, window, cx);
14611            });
14612        });
14613
14614        // Now trigger another SettingsStore change
14615        workspace.update_in(cx, |_workspace, _window, cx| {
14616            cx.update_global::<SettingsStore, _>(|_, _| {});
14617        });
14618
14619        workspace.update_in(cx, |workspace, _, cx| {
14620            assert!(
14621                workspace.right_dock().read(cx).is_open(),
14622                "Right dock should still be open after a settings change"
14623            );
14624            assert_eq!(
14625                workspace.right_dock().read(cx).panels_len(),
14626                2,
14627                "Both panels should still be in the right dock"
14628            );
14629        });
14630    }
14631}