workspace.rs

    1pub mod dock;
    2pub mod history_manager;
    3pub mod invalid_item_view;
    4pub mod item;
    5mod modal_layer;
    6mod multi_workspace;
    7pub mod notifications;
    8pub mod pane;
    9pub mod pane_group;
   10pub mod path_list {
   11    pub use util::path_list::{PathList, SerializedPathList};
   12}
   13mod persistence;
   14pub mod searchable;
   15mod security_modal;
   16pub mod shared_screen;
   17use db::smol::future::yield_now;
   18pub use shared_screen::SharedScreen;
   19mod status_bar;
   20pub mod tasks;
   21mod theme_preview;
   22mod toast_layer;
   23mod toolbar;
   24pub mod welcome;
   25mod workspace_settings;
   26
   27pub use crate::notifications::NotificationFrame;
   28pub use dock::Panel;
   29pub use multi_workspace::{
   30    CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
   31    MultiWorkspaceEvent, NextWorkspace, PreviousWorkspace, Sidebar, SidebarHandle,
   32    ToggleWorkspaceSidebar,
   33};
   34pub use path_list::{PathList, SerializedPathList};
   35pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   36
   37use anyhow::{Context as _, Result, anyhow};
   38use client::{
   39    ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
   40    proto::{self, ErrorCode, PanelId, PeerId},
   41};
   42use collections::{HashMap, HashSet, hash_map};
   43use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   44use fs::Fs;
   45use futures::{
   46    Future, FutureExt, StreamExt,
   47    channel::{
   48        mpsc::{self, UnboundedReceiver, UnboundedSender},
   49        oneshot,
   50    },
   51    future::{Shared, try_join_all},
   52};
   53use gpui::{
   54    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
   55    CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   56    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   57    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   58    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   59    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   60};
   61pub use history_manager::*;
   62pub use item::{
   63    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   64    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   65};
   66use itertools::Itertools;
   67use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   68pub use modal_layer::*;
   69use node_runtime::NodeRuntime;
   70use notifications::{
   71    DetachAndPromptErr, Notifications, dismiss_app_notification,
   72    simple_message_notification::MessageNotification,
   73};
   74pub use pane::*;
   75pub use pane_group::{
   76    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   77    SplitDirection,
   78};
   79use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
   80pub use persistence::{
   81    WorkspaceDb, delete_unloaded_items,
   82    model::{
   83        DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
   84        SessionWorkspace,
   85    },
   86    read_serialized_multi_workspaces, resolve_worktree_workspaces,
   87};
   88use postage::stream::Stream;
   89use project::{
   90    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
   91    WorktreeSettings,
   92    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   93    project_settings::ProjectSettings,
   94    toolchain_store::ToolchainStoreEvent,
   95    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
   96};
   97use remote::{
   98    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
   99    remote_client::ConnectionIdentifier,
  100};
  101use schemars::JsonSchema;
  102use serde::Deserialize;
  103use session::AppSession;
  104use settings::{
  105    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  106};
  107
  108use sqlez::{
  109    bindable::{Bind, Column, StaticColumnCount},
  110    statement::Statement,
  111};
  112use status_bar::StatusBar;
  113pub use status_bar::StatusItemView;
  114use std::{
  115    any::TypeId,
  116    borrow::Cow,
  117    cell::RefCell,
  118    cmp,
  119    collections::VecDeque,
  120    env,
  121    hash::Hash,
  122    path::{Path, PathBuf},
  123    process::ExitStatus,
  124    rc::Rc,
  125    sync::{
  126        Arc, LazyLock, Weak,
  127        atomic::{AtomicBool, AtomicUsize},
  128    },
  129    time::Duration,
  130};
  131use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  132use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
  133pub use toolbar::{
  134    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  135};
  136pub use ui;
  137use ui::{Window, prelude::*};
  138use util::{
  139    ResultExt, TryFutureExt,
  140    paths::{PathStyle, SanitizedPath},
  141    rel_path::RelPath,
  142    serde::default_true,
  143};
  144use uuid::Uuid;
  145pub use workspace_settings::{
  146    AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
  147    WorkspaceSettings,
  148};
  149use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
  150
  151use crate::{item::ItemBufferKind, notifications::NotificationId};
  152use crate::{
  153    persistence::{
  154        SerializedAxis,
  155        model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
  156    },
  157    security_modal::SecurityModal,
  158};
  159
  160pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  161
  162static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  163    env::var("ZED_WINDOW_SIZE")
  164        .ok()
  165        .as_deref()
  166        .and_then(parse_pixel_size_env_var)
  167});
  168
  169static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  170    env::var("ZED_WINDOW_POSITION")
  171        .ok()
  172        .as_deref()
  173        .and_then(parse_pixel_position_env_var)
  174});
  175
  176pub trait TerminalProvider {
  177    fn spawn(
  178        &self,
  179        task: SpawnInTerminal,
  180        window: &mut Window,
  181        cx: &mut App,
  182    ) -> Task<Option<Result<ExitStatus>>>;
  183}
  184
  185pub trait DebuggerProvider {
  186    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  187    fn start_session(
  188        &self,
  189        definition: DebugScenario,
  190        task_context: SharedTaskContext,
  191        active_buffer: Option<Entity<Buffer>>,
  192        worktree_id: Option<WorktreeId>,
  193        window: &mut Window,
  194        cx: &mut App,
  195    );
  196
  197    fn spawn_task_or_modal(
  198        &self,
  199        workspace: &mut Workspace,
  200        action: &Spawn,
  201        window: &mut Window,
  202        cx: &mut Context<Workspace>,
  203    );
  204
  205    fn task_scheduled(&self, cx: &mut App);
  206    fn debug_scenario_scheduled(&self, cx: &mut App);
  207    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  208
  209    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  210}
  211
  212/// Opens a file or directory.
  213#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  214#[action(namespace = workspace)]
  215pub struct Open {
  216    /// When true, opens in a new window. When false, adds to the current
  217    /// window as a new workspace (multi-workspace).
  218    #[serde(default = "Open::default_create_new_window")]
  219    pub create_new_window: bool,
  220}
  221
  222impl Open {
  223    pub const DEFAULT: Self = Self {
  224        create_new_window: true,
  225    };
  226
  227    /// Used by `#[serde(default)]` on the `create_new_window` field so that
  228    /// the serde default and `Open::DEFAULT` stay in sync.
  229    fn default_create_new_window() -> bool {
  230        Self::DEFAULT.create_new_window
  231    }
  232}
  233
  234impl Default for Open {
  235    fn default() -> Self {
  236        Self::DEFAULT
  237    }
  238}
  239
  240actions!(
  241    workspace,
  242    [
  243        /// Activates the next pane in the workspace.
  244        ActivateNextPane,
  245        /// Activates the previous pane in the workspace.
  246        ActivatePreviousPane,
  247        /// Activates the last pane in the workspace.
  248        ActivateLastPane,
  249        /// Switches to the next window.
  250        ActivateNextWindow,
  251        /// Switches to the previous window.
  252        ActivatePreviousWindow,
  253        /// Adds a folder to the current project.
  254        AddFolderToProject,
  255        /// Clears all notifications.
  256        ClearAllNotifications,
  257        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  258        ClearNavigationHistory,
  259        /// Closes the active dock.
  260        CloseActiveDock,
  261        /// Closes all docks.
  262        CloseAllDocks,
  263        /// Toggles all docks.
  264        ToggleAllDocks,
  265        /// Closes the current window.
  266        CloseWindow,
  267        /// Closes the current project.
  268        CloseProject,
  269        /// Opens the feedback dialog.
  270        Feedback,
  271        /// Follows the next collaborator in the session.
  272        FollowNextCollaborator,
  273        /// Moves the focused panel to the next position.
  274        MoveFocusedPanelToNextPosition,
  275        /// Creates a new file.
  276        NewFile,
  277        /// Creates a new file in a vertical split.
  278        NewFileSplitVertical,
  279        /// Creates a new file in a horizontal split.
  280        NewFileSplitHorizontal,
  281        /// Opens a new search.
  282        NewSearch,
  283        /// Opens a new window.
  284        NewWindow,
  285        /// Opens multiple files.
  286        OpenFiles,
  287        /// Opens the current location in terminal.
  288        OpenInTerminal,
  289        /// Opens the component preview.
  290        OpenComponentPreview,
  291        /// Reloads the active item.
  292        ReloadActiveItem,
  293        /// Resets the active dock to its default size.
  294        ResetActiveDockSize,
  295        /// Resets all open docks to their default sizes.
  296        ResetOpenDocksSize,
  297        /// Reloads the application
  298        Reload,
  299        /// Saves the current file with a new name.
  300        SaveAs,
  301        /// Saves without formatting.
  302        SaveWithoutFormat,
  303        /// Shuts down all debug adapters.
  304        ShutdownDebugAdapters,
  305        /// Suppresses the current notification.
  306        SuppressNotification,
  307        /// Toggles the bottom dock.
  308        ToggleBottomDock,
  309        /// Toggles centered layout mode.
  310        ToggleCenteredLayout,
  311        /// Toggles edit prediction feature globally for all files.
  312        ToggleEditPrediction,
  313        /// Toggles the left dock.
  314        ToggleLeftDock,
  315        /// Toggles the right dock.
  316        ToggleRightDock,
  317        /// Toggles zoom on the active pane.
  318        ToggleZoom,
  319        /// Toggles read-only mode for the active item (if supported by that item).
  320        ToggleReadOnlyFile,
  321        /// Zooms in on the active pane.
  322        ZoomIn,
  323        /// Zooms out of the active pane.
  324        ZoomOut,
  325        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  326        /// If the modal is shown already, closes it without trusting any worktree.
  327        ToggleWorktreeSecurity,
  328        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  329        /// Requires restart to take effect on already opened projects.
  330        ClearTrustedWorktrees,
  331        /// Stops following a collaborator.
  332        Unfollow,
  333        /// Restores the banner.
  334        RestoreBanner,
  335        /// Toggles expansion of the selected item.
  336        ToggleExpandItem,
  337    ]
  338);
  339
  340/// Activates a specific pane by its index.
  341#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  342#[action(namespace = workspace)]
  343pub struct ActivatePane(pub usize);
  344
  345/// Moves an item to a specific pane by index.
  346#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  347#[action(namespace = workspace)]
  348#[serde(deny_unknown_fields)]
  349pub struct MoveItemToPane {
  350    #[serde(default = "default_1")]
  351    pub destination: usize,
  352    #[serde(default = "default_true")]
  353    pub focus: bool,
  354    #[serde(default)]
  355    pub clone: bool,
  356}
  357
  358fn default_1() -> usize {
  359    1
  360}
  361
  362/// Moves an item to a pane in the specified direction.
  363#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  364#[action(namespace = workspace)]
  365#[serde(deny_unknown_fields)]
  366pub struct MoveItemToPaneInDirection {
  367    #[serde(default = "default_right")]
  368    pub direction: SplitDirection,
  369    #[serde(default = "default_true")]
  370    pub focus: bool,
  371    #[serde(default)]
  372    pub clone: bool,
  373}
  374
  375/// Creates a new file in a split of the desired direction.
  376#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  377#[action(namespace = workspace)]
  378#[serde(deny_unknown_fields)]
  379pub struct NewFileSplit(pub SplitDirection);
  380
  381fn default_right() -> SplitDirection {
  382    SplitDirection::Right
  383}
  384
  385/// Saves all open files in the workspace.
  386#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  387#[action(namespace = workspace)]
  388#[serde(deny_unknown_fields)]
  389pub struct SaveAll {
  390    #[serde(default)]
  391    pub save_intent: Option<SaveIntent>,
  392}
  393
  394/// Saves the current file with the specified options.
  395#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  396#[action(namespace = workspace)]
  397#[serde(deny_unknown_fields)]
  398pub struct Save {
  399    #[serde(default)]
  400    pub save_intent: Option<SaveIntent>,
  401}
  402
  403/// Moves Focus to the central panes in the workspace.
  404#[derive(Clone, Debug, PartialEq, Eq, Action)]
  405#[action(namespace = workspace)]
  406pub struct FocusCenterPane;
  407
  408///  Closes all items and panes in the workspace.
  409#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  410#[action(namespace = workspace)]
  411#[serde(deny_unknown_fields)]
  412pub struct CloseAllItemsAndPanes {
  413    #[serde(default)]
  414    pub save_intent: Option<SaveIntent>,
  415}
  416
  417/// Closes all inactive tabs and panes in the workspace.
  418#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  419#[action(namespace = workspace)]
  420#[serde(deny_unknown_fields)]
  421pub struct CloseInactiveTabsAndPanes {
  422    #[serde(default)]
  423    pub save_intent: Option<SaveIntent>,
  424}
  425
  426/// Closes the active item across all panes.
  427#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  428#[action(namespace = workspace)]
  429#[serde(deny_unknown_fields)]
  430pub struct CloseItemInAllPanes {
  431    #[serde(default)]
  432    pub save_intent: Option<SaveIntent>,
  433    #[serde(default)]
  434    pub close_pinned: bool,
  435}
  436
  437/// Sends a sequence of keystrokes to the active element.
  438#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  439#[action(namespace = workspace)]
  440pub struct SendKeystrokes(pub String);
  441
  442actions!(
  443    project_symbols,
  444    [
  445        /// Toggles the project symbols search.
  446        #[action(name = "Toggle")]
  447        ToggleProjectSymbols
  448    ]
  449);
  450
  451/// Toggles the file finder interface.
  452#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  453#[action(namespace = file_finder, name = "Toggle")]
  454#[serde(deny_unknown_fields)]
  455pub struct ToggleFileFinder {
  456    #[serde(default)]
  457    pub separate_history: bool,
  458}
  459
  460/// Opens a new terminal in the center.
  461#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  462#[action(namespace = workspace)]
  463#[serde(deny_unknown_fields)]
  464pub struct NewCenterTerminal {
  465    /// If true, creates a local terminal even in remote projects.
  466    #[serde(default)]
  467    pub local: bool,
  468}
  469
  470/// Opens a new terminal.
  471#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  472#[action(namespace = workspace)]
  473#[serde(deny_unknown_fields)]
  474pub struct NewTerminal {
  475    /// If true, creates a local terminal even in remote projects.
  476    #[serde(default)]
  477    pub local: bool,
  478}
  479
  480/// Increases size of a currently focused dock by a given amount of pixels.
  481#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  482#[action(namespace = workspace)]
  483#[serde(deny_unknown_fields)]
  484pub struct IncreaseActiveDockSize {
  485    /// For 0px parameter, uses UI font size value.
  486    #[serde(default)]
  487    pub px: u32,
  488}
  489
  490/// Decreases size of a currently focused dock by a given amount of pixels.
  491#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  492#[action(namespace = workspace)]
  493#[serde(deny_unknown_fields)]
  494pub struct DecreaseActiveDockSize {
  495    /// For 0px parameter, uses UI font size value.
  496    #[serde(default)]
  497    pub px: u32,
  498}
  499
  500/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  501#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  502#[action(namespace = workspace)]
  503#[serde(deny_unknown_fields)]
  504pub struct IncreaseOpenDocksSize {
  505    /// For 0px parameter, uses UI font size value.
  506    #[serde(default)]
  507    pub px: u32,
  508}
  509
  510/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  511#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  512#[action(namespace = workspace)]
  513#[serde(deny_unknown_fields)]
  514pub struct DecreaseOpenDocksSize {
  515    /// For 0px parameter, uses UI font size value.
  516    #[serde(default)]
  517    pub px: u32,
  518}
  519
  520actions!(
  521    workspace,
  522    [
  523        /// Activates the pane to the left.
  524        ActivatePaneLeft,
  525        /// Activates the pane to the right.
  526        ActivatePaneRight,
  527        /// Activates the pane above.
  528        ActivatePaneUp,
  529        /// Activates the pane below.
  530        ActivatePaneDown,
  531        /// Swaps the current pane with the one to the left.
  532        SwapPaneLeft,
  533        /// Swaps the current pane with the one to the right.
  534        SwapPaneRight,
  535        /// Swaps the current pane with the one above.
  536        SwapPaneUp,
  537        /// Swaps the current pane with the one below.
  538        SwapPaneDown,
  539        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  540        SwapPaneAdjacent,
  541        /// Move the current pane to be at the far left.
  542        MovePaneLeft,
  543        /// Move the current pane to be at the far right.
  544        MovePaneRight,
  545        /// Move the current pane to be at the very top.
  546        MovePaneUp,
  547        /// Move the current pane to be at the very bottom.
  548        MovePaneDown,
  549    ]
  550);
  551
  552#[derive(PartialEq, Eq, Debug)]
  553pub enum CloseIntent {
  554    /// Quit the program entirely.
  555    Quit,
  556    /// Close a window.
  557    CloseWindow,
  558    /// Replace the workspace in an existing window.
  559    ReplaceWindow,
  560}
  561
  562#[derive(Clone)]
  563pub struct Toast {
  564    id: NotificationId,
  565    msg: Cow<'static, str>,
  566    autohide: bool,
  567    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  568}
  569
  570impl Toast {
  571    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  572        Toast {
  573            id,
  574            msg: msg.into(),
  575            on_click: None,
  576            autohide: false,
  577        }
  578    }
  579
  580    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  581    where
  582        M: Into<Cow<'static, str>>,
  583        F: Fn(&mut Window, &mut App) + 'static,
  584    {
  585        self.on_click = Some((message.into(), Arc::new(on_click)));
  586        self
  587    }
  588
  589    pub fn autohide(mut self) -> Self {
  590        self.autohide = true;
  591        self
  592    }
  593}
  594
  595impl PartialEq for Toast {
  596    fn eq(&self, other: &Self) -> bool {
  597        self.id == other.id
  598            && self.msg == other.msg
  599            && self.on_click.is_some() == other.on_click.is_some()
  600    }
  601}
  602
  603/// Opens a new terminal with the specified working directory.
  604#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  605#[action(namespace = workspace)]
  606#[serde(deny_unknown_fields)]
  607pub struct OpenTerminal {
  608    pub working_directory: PathBuf,
  609    /// If true, creates a local terminal even in remote projects.
  610    #[serde(default)]
  611    pub local: bool,
  612}
  613
  614#[derive(
  615    Clone,
  616    Copy,
  617    Debug,
  618    Default,
  619    Hash,
  620    PartialEq,
  621    Eq,
  622    PartialOrd,
  623    Ord,
  624    serde::Serialize,
  625    serde::Deserialize,
  626)]
  627pub struct WorkspaceId(i64);
  628
  629impl WorkspaceId {
  630    pub fn from_i64(value: i64) -> Self {
  631        Self(value)
  632    }
  633}
  634
  635impl StaticColumnCount for WorkspaceId {}
  636impl Bind for WorkspaceId {
  637    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  638        self.0.bind(statement, start_index)
  639    }
  640}
  641impl Column for WorkspaceId {
  642    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  643        i64::column(statement, start_index)
  644            .map(|(i, next_index)| (Self(i), next_index))
  645            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  646    }
  647}
  648impl From<WorkspaceId> for i64 {
  649    fn from(val: WorkspaceId) -> Self {
  650        val.0
  651    }
  652}
  653
  654fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
  655    if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
  656        workspace_window
  657            .update(cx, |multi_workspace, window, cx| {
  658                let workspace = multi_workspace.workspace().clone();
  659                workspace.update(cx, |workspace, cx| {
  660                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  661                });
  662            })
  663            .ok();
  664    } else {
  665        let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, true, cx);
  666        cx.spawn(async move |cx| {
  667            let OpenResult { window, .. } = task.await?;
  668            window.update(cx, |multi_workspace, window, cx| {
  669                window.activate_window();
  670                let workspace = multi_workspace.workspace().clone();
  671                workspace.update(cx, |workspace, cx| {
  672                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  673                });
  674            })?;
  675            anyhow::Ok(())
  676        })
  677        .detach_and_log_err(cx);
  678    }
  679}
  680
  681pub fn prompt_for_open_path_and_open(
  682    workspace: &mut Workspace,
  683    app_state: Arc<AppState>,
  684    options: PathPromptOptions,
  685    create_new_window: bool,
  686    window: &mut Window,
  687    cx: &mut Context<Workspace>,
  688) {
  689    let paths = workspace.prompt_for_open_path(
  690        options,
  691        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  692        window,
  693        cx,
  694    );
  695    let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
  696    cx.spawn_in(window, async move |this, cx| {
  697        let Some(paths) = paths.await.log_err().flatten() else {
  698            return;
  699        };
  700        if !create_new_window {
  701            if let Some(handle) = multi_workspace_handle {
  702                if let Some(task) = handle
  703                    .update(cx, |multi_workspace, window, cx| {
  704                        multi_workspace.open_project(paths, window, cx)
  705                    })
  706                    .log_err()
  707                {
  708                    task.await.log_err();
  709                }
  710                return;
  711            }
  712        }
  713        if let Some(task) = this
  714            .update_in(cx, |this, window, cx| {
  715                this.open_workspace_for_paths(false, paths, window, cx)
  716            })
  717            .log_err()
  718        {
  719            task.await.log_err();
  720        }
  721    })
  722    .detach();
  723}
  724
  725pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  726    component::init();
  727    theme_preview::init(cx);
  728    toast_layer::init(cx);
  729    history_manager::init(app_state.fs.clone(), cx);
  730
  731    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  732        .on_action(|_: &Reload, cx| reload(cx))
  733        .on_action({
  734            let app_state = Arc::downgrade(&app_state);
  735            move |_: &Open, cx: &mut App| {
  736                if let Some(app_state) = app_state.upgrade() {
  737                    prompt_and_open_paths(
  738                        app_state,
  739                        PathPromptOptions {
  740                            files: true,
  741                            directories: true,
  742                            multiple: true,
  743                            prompt: None,
  744                        },
  745                        cx,
  746                    );
  747                }
  748            }
  749        })
  750        .on_action({
  751            let app_state = Arc::downgrade(&app_state);
  752            move |_: &OpenFiles, cx: &mut App| {
  753                let directories = cx.can_select_mixed_files_and_dirs();
  754                if let Some(app_state) = app_state.upgrade() {
  755                    prompt_and_open_paths(
  756                        app_state,
  757                        PathPromptOptions {
  758                            files: true,
  759                            directories,
  760                            multiple: true,
  761                            prompt: None,
  762                        },
  763                        cx,
  764                    );
  765                }
  766            }
  767        });
  768}
  769
  770type BuildProjectItemFn =
  771    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  772
  773type BuildProjectItemForPathFn =
  774    fn(
  775        &Entity<Project>,
  776        &ProjectPath,
  777        &mut Window,
  778        &mut App,
  779    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  780
  781#[derive(Clone, Default)]
  782struct ProjectItemRegistry {
  783    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  784    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  785}
  786
  787impl ProjectItemRegistry {
  788    fn register<T: ProjectItem>(&mut self) {
  789        self.build_project_item_fns_by_type.insert(
  790            TypeId::of::<T::Item>(),
  791            |item, project, pane, window, cx| {
  792                let item = item.downcast().unwrap();
  793                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  794                    as Box<dyn ItemHandle>
  795            },
  796        );
  797        self.build_project_item_for_path_fns
  798            .push(|project, project_path, window, cx| {
  799                let project_path = project_path.clone();
  800                let is_file = project
  801                    .read(cx)
  802                    .entry_for_path(&project_path, cx)
  803                    .is_some_and(|entry| entry.is_file());
  804                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  805                let is_local = project.read(cx).is_local();
  806                let project_item =
  807                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  808                let project = project.clone();
  809                Some(window.spawn(cx, async move |cx| {
  810                    match project_item.await.with_context(|| {
  811                        format!(
  812                            "opening project path {:?}",
  813                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  814                        )
  815                    }) {
  816                        Ok(project_item) => {
  817                            let project_item = project_item;
  818                            let project_entry_id: Option<ProjectEntryId> =
  819                                project_item.read_with(cx, project::ProjectItem::entry_id);
  820                            let build_workspace_item = Box::new(
  821                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  822                                    Box::new(cx.new(|cx| {
  823                                        T::for_project_item(
  824                                            project,
  825                                            Some(pane),
  826                                            project_item,
  827                                            window,
  828                                            cx,
  829                                        )
  830                                    })) as Box<dyn ItemHandle>
  831                                },
  832                            ) as Box<_>;
  833                            Ok((project_entry_id, build_workspace_item))
  834                        }
  835                        Err(e) => {
  836                            log::warn!("Failed to open a project item: {e:#}");
  837                            if e.error_code() == ErrorCode::Internal {
  838                                if let Some(abs_path) =
  839                                    entry_abs_path.as_deref().filter(|_| is_file)
  840                                {
  841                                    if let Some(broken_project_item_view) =
  842                                        cx.update(|window, cx| {
  843                                            T::for_broken_project_item(
  844                                                abs_path, is_local, &e, window, cx,
  845                                            )
  846                                        })?
  847                                    {
  848                                        let build_workspace_item = Box::new(
  849                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  850                                                cx.new(|_| broken_project_item_view).boxed_clone()
  851                                            },
  852                                        )
  853                                        as Box<_>;
  854                                        return Ok((None, build_workspace_item));
  855                                    }
  856                                }
  857                            }
  858                            Err(e)
  859                        }
  860                    }
  861                }))
  862            });
  863    }
  864
  865    fn open_path(
  866        &self,
  867        project: &Entity<Project>,
  868        path: &ProjectPath,
  869        window: &mut Window,
  870        cx: &mut App,
  871    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  872        let Some(open_project_item) = self
  873            .build_project_item_for_path_fns
  874            .iter()
  875            .rev()
  876            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  877        else {
  878            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  879        };
  880        open_project_item
  881    }
  882
  883    fn build_item<T: project::ProjectItem>(
  884        &self,
  885        item: Entity<T>,
  886        project: Entity<Project>,
  887        pane: Option<&Pane>,
  888        window: &mut Window,
  889        cx: &mut App,
  890    ) -> Option<Box<dyn ItemHandle>> {
  891        let build = self
  892            .build_project_item_fns_by_type
  893            .get(&TypeId::of::<T>())?;
  894        Some(build(item.into_any(), project, pane, window, cx))
  895    }
  896}
  897
  898type WorkspaceItemBuilder =
  899    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  900
  901impl Global for ProjectItemRegistry {}
  902
  903/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  904/// items will get a chance to open the file, starting from the project item that
  905/// was added last.
  906pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  907    cx.default_global::<ProjectItemRegistry>().register::<I>();
  908}
  909
  910#[derive(Default)]
  911pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  912
  913struct FollowableViewDescriptor {
  914    from_state_proto: fn(
  915        Entity<Workspace>,
  916        ViewId,
  917        &mut Option<proto::view::Variant>,
  918        &mut Window,
  919        &mut App,
  920    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  921    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  922}
  923
  924impl Global for FollowableViewRegistry {}
  925
  926impl FollowableViewRegistry {
  927    pub fn register<I: FollowableItem>(cx: &mut App) {
  928        cx.default_global::<Self>().0.insert(
  929            TypeId::of::<I>(),
  930            FollowableViewDescriptor {
  931                from_state_proto: |workspace, id, state, window, cx| {
  932                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  933                        cx.foreground_executor()
  934                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  935                    })
  936                },
  937                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  938            },
  939        );
  940    }
  941
  942    pub fn from_state_proto(
  943        workspace: Entity<Workspace>,
  944        view_id: ViewId,
  945        mut state: Option<proto::view::Variant>,
  946        window: &mut Window,
  947        cx: &mut App,
  948    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  949        cx.update_default_global(|this: &mut Self, cx| {
  950            this.0.values().find_map(|descriptor| {
  951                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  952            })
  953        })
  954    }
  955
  956    pub fn to_followable_view(
  957        view: impl Into<AnyView>,
  958        cx: &App,
  959    ) -> Option<Box<dyn FollowableItemHandle>> {
  960        let this = cx.try_global::<Self>()?;
  961        let view = view.into();
  962        let descriptor = this.0.get(&view.entity_type())?;
  963        Some((descriptor.to_followable_view)(&view))
  964    }
  965}
  966
  967#[derive(Copy, Clone)]
  968struct SerializableItemDescriptor {
  969    deserialize: fn(
  970        Entity<Project>,
  971        WeakEntity<Workspace>,
  972        WorkspaceId,
  973        ItemId,
  974        &mut Window,
  975        &mut Context<Pane>,
  976    ) -> Task<Result<Box<dyn ItemHandle>>>,
  977    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  978    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  979}
  980
  981#[derive(Default)]
  982struct SerializableItemRegistry {
  983    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  984    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  985}
  986
  987impl Global for SerializableItemRegistry {}
  988
  989impl SerializableItemRegistry {
  990    fn deserialize(
  991        item_kind: &str,
  992        project: Entity<Project>,
  993        workspace: WeakEntity<Workspace>,
  994        workspace_id: WorkspaceId,
  995        item_item: ItemId,
  996        window: &mut Window,
  997        cx: &mut Context<Pane>,
  998    ) -> Task<Result<Box<dyn ItemHandle>>> {
  999        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1000            return Task::ready(Err(anyhow!(
 1001                "cannot deserialize {}, descriptor not found",
 1002                item_kind
 1003            )));
 1004        };
 1005
 1006        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
 1007    }
 1008
 1009    fn cleanup(
 1010        item_kind: &str,
 1011        workspace_id: WorkspaceId,
 1012        loaded_items: Vec<ItemId>,
 1013        window: &mut Window,
 1014        cx: &mut App,
 1015    ) -> Task<Result<()>> {
 1016        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1017            return Task::ready(Err(anyhow!(
 1018                "cannot cleanup {}, descriptor not found",
 1019                item_kind
 1020            )));
 1021        };
 1022
 1023        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
 1024    }
 1025
 1026    fn view_to_serializable_item_handle(
 1027        view: AnyView,
 1028        cx: &App,
 1029    ) -> Option<Box<dyn SerializableItemHandle>> {
 1030        let this = cx.try_global::<Self>()?;
 1031        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
 1032        Some((descriptor.view_to_serializable_item)(view))
 1033    }
 1034
 1035    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
 1036        let this = cx.try_global::<Self>()?;
 1037        this.descriptors_by_kind.get(item_kind).copied()
 1038    }
 1039}
 1040
 1041pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
 1042    let serialized_item_kind = I::serialized_item_kind();
 1043
 1044    let registry = cx.default_global::<SerializableItemRegistry>();
 1045    let descriptor = SerializableItemDescriptor {
 1046        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
 1047            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
 1048            cx.foreground_executor()
 1049                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 1050        },
 1051        cleanup: |workspace_id, loaded_items, window, cx| {
 1052            I::cleanup(workspace_id, loaded_items, window, cx)
 1053        },
 1054        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1055    };
 1056    registry
 1057        .descriptors_by_kind
 1058        .insert(Arc::from(serialized_item_kind), descriptor);
 1059    registry
 1060        .descriptors_by_type
 1061        .insert(TypeId::of::<I>(), descriptor);
 1062}
 1063
 1064pub struct AppState {
 1065    pub languages: Arc<LanguageRegistry>,
 1066    pub client: Arc<Client>,
 1067    pub user_store: Entity<UserStore>,
 1068    pub workspace_store: Entity<WorkspaceStore>,
 1069    pub fs: Arc<dyn fs::Fs>,
 1070    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1071    pub node_runtime: NodeRuntime,
 1072    pub session: Entity<AppSession>,
 1073}
 1074
 1075struct GlobalAppState(Weak<AppState>);
 1076
 1077impl Global for GlobalAppState {}
 1078
 1079pub struct WorkspaceStore {
 1080    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1081    client: Arc<Client>,
 1082    _subscriptions: Vec<client::Subscription>,
 1083}
 1084
 1085#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1086pub enum CollaboratorId {
 1087    PeerId(PeerId),
 1088    Agent,
 1089}
 1090
 1091impl From<PeerId> for CollaboratorId {
 1092    fn from(peer_id: PeerId) -> Self {
 1093        CollaboratorId::PeerId(peer_id)
 1094    }
 1095}
 1096
 1097impl From<&PeerId> for CollaboratorId {
 1098    fn from(peer_id: &PeerId) -> Self {
 1099        CollaboratorId::PeerId(*peer_id)
 1100    }
 1101}
 1102
 1103#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1104struct Follower {
 1105    project_id: Option<u64>,
 1106    peer_id: PeerId,
 1107}
 1108
 1109impl AppState {
 1110    #[track_caller]
 1111    pub fn global(cx: &App) -> Weak<Self> {
 1112        cx.global::<GlobalAppState>().0.clone()
 1113    }
 1114    pub fn try_global(cx: &App) -> Option<Weak<Self>> {
 1115        cx.try_global::<GlobalAppState>()
 1116            .map(|state| state.0.clone())
 1117    }
 1118    pub fn set_global(state: Weak<AppState>, cx: &mut App) {
 1119        cx.set_global(GlobalAppState(state));
 1120    }
 1121
 1122    #[cfg(any(test, feature = "test-support"))]
 1123    pub fn test(cx: &mut App) -> Arc<Self> {
 1124        use fs::Fs;
 1125        use node_runtime::NodeRuntime;
 1126        use session::Session;
 1127        use settings::SettingsStore;
 1128
 1129        if !cx.has_global::<SettingsStore>() {
 1130            let settings_store = SettingsStore::test(cx);
 1131            cx.set_global(settings_store);
 1132        }
 1133
 1134        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1135        <dyn Fs>::set_global(fs.clone(), cx);
 1136        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1137        let clock = Arc::new(clock::FakeSystemClock::new());
 1138        let http_client = http_client::FakeHttpClient::with_404_response();
 1139        let client = Client::new(clock, http_client, cx);
 1140        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1141        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1142        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1143
 1144        theme::init(theme::LoadThemes::JustBase, cx);
 1145        client::init(&client, cx);
 1146
 1147        Arc::new(Self {
 1148            client,
 1149            fs,
 1150            languages,
 1151            user_store,
 1152            workspace_store,
 1153            node_runtime: NodeRuntime::unavailable(),
 1154            build_window_options: |_, _| Default::default(),
 1155            session,
 1156        })
 1157    }
 1158}
 1159
 1160struct DelayedDebouncedEditAction {
 1161    task: Option<Task<()>>,
 1162    cancel_channel: Option<oneshot::Sender<()>>,
 1163}
 1164
 1165impl DelayedDebouncedEditAction {
 1166    fn new() -> DelayedDebouncedEditAction {
 1167        DelayedDebouncedEditAction {
 1168            task: None,
 1169            cancel_channel: None,
 1170        }
 1171    }
 1172
 1173    fn fire_new<F>(
 1174        &mut self,
 1175        delay: Duration,
 1176        window: &mut Window,
 1177        cx: &mut Context<Workspace>,
 1178        func: F,
 1179    ) where
 1180        F: 'static
 1181            + Send
 1182            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1183    {
 1184        if let Some(channel) = self.cancel_channel.take() {
 1185            _ = channel.send(());
 1186        }
 1187
 1188        let (sender, mut receiver) = oneshot::channel::<()>();
 1189        self.cancel_channel = Some(sender);
 1190
 1191        let previous_task = self.task.take();
 1192        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1193            let mut timer = cx.background_executor().timer(delay).fuse();
 1194            if let Some(previous_task) = previous_task {
 1195                previous_task.await;
 1196            }
 1197
 1198            futures::select_biased! {
 1199                _ = receiver => return,
 1200                    _ = timer => {}
 1201            }
 1202
 1203            if let Some(result) = workspace
 1204                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1205                .log_err()
 1206            {
 1207                result.await.log_err();
 1208            }
 1209        }));
 1210    }
 1211}
 1212
 1213pub enum Event {
 1214    PaneAdded(Entity<Pane>),
 1215    PaneRemoved,
 1216    ItemAdded {
 1217        item: Box<dyn ItemHandle>,
 1218    },
 1219    ActiveItemChanged,
 1220    ItemRemoved {
 1221        item_id: EntityId,
 1222    },
 1223    UserSavedItem {
 1224        pane: WeakEntity<Pane>,
 1225        item: Box<dyn WeakItemHandle>,
 1226        save_intent: SaveIntent,
 1227    },
 1228    ContactRequestedJoin(u64),
 1229    WorkspaceCreated(WeakEntity<Workspace>),
 1230    OpenBundledFile {
 1231        text: Cow<'static, str>,
 1232        title: &'static str,
 1233        language: &'static str,
 1234    },
 1235    ZoomChanged,
 1236    ModalOpened,
 1237    Activate,
 1238    PanelAdded(AnyView),
 1239}
 1240
 1241#[derive(Debug, Clone)]
 1242pub enum OpenVisible {
 1243    All,
 1244    None,
 1245    OnlyFiles,
 1246    OnlyDirectories,
 1247}
 1248
 1249enum WorkspaceLocation {
 1250    // Valid local paths or SSH project to serialize
 1251    Location(SerializedWorkspaceLocation, PathList),
 1252    // No valid location found hence clear session id
 1253    DetachFromSession,
 1254    // No valid location found to serialize
 1255    None,
 1256}
 1257
 1258type PromptForNewPath = Box<
 1259    dyn Fn(
 1260        &mut Workspace,
 1261        DirectoryLister,
 1262        Option<String>,
 1263        &mut Window,
 1264        &mut Context<Workspace>,
 1265    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1266>;
 1267
 1268type PromptForOpenPath = Box<
 1269    dyn Fn(
 1270        &mut Workspace,
 1271        DirectoryLister,
 1272        &mut Window,
 1273        &mut Context<Workspace>,
 1274    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1275>;
 1276
 1277#[derive(Default)]
 1278struct DispatchingKeystrokes {
 1279    dispatched: HashSet<Vec<Keystroke>>,
 1280    queue: VecDeque<Keystroke>,
 1281    task: Option<Shared<Task<()>>>,
 1282}
 1283
 1284/// Collects everything project-related for a certain window opened.
 1285/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1286///
 1287/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1288/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1289/// that can be used to register a global action to be triggered from any place in the window.
 1290pub struct Workspace {
 1291    weak_self: WeakEntity<Self>,
 1292    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1293    zoomed: Option<AnyWeakView>,
 1294    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1295    zoomed_position: Option<DockPosition>,
 1296    center: PaneGroup,
 1297    left_dock: Entity<Dock>,
 1298    bottom_dock: Entity<Dock>,
 1299    right_dock: Entity<Dock>,
 1300    panes: Vec<Entity<Pane>>,
 1301    active_worktree_override: Option<WorktreeId>,
 1302    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1303    active_pane: Entity<Pane>,
 1304    last_active_center_pane: Option<WeakEntity<Pane>>,
 1305    last_active_view_id: Option<proto::ViewId>,
 1306    status_bar: Entity<StatusBar>,
 1307    pub(crate) modal_layer: Entity<ModalLayer>,
 1308    toast_layer: Entity<ToastLayer>,
 1309    titlebar_item: Option<AnyView>,
 1310    notifications: Notifications,
 1311    suppressed_notifications: HashSet<NotificationId>,
 1312    project: Entity<Project>,
 1313    follower_states: HashMap<CollaboratorId, FollowerState>,
 1314    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1315    window_edited: bool,
 1316    last_window_title: Option<String>,
 1317    dirty_items: HashMap<EntityId, Subscription>,
 1318    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1319    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1320    database_id: Option<WorkspaceId>,
 1321    app_state: Arc<AppState>,
 1322    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1323    _subscriptions: Vec<Subscription>,
 1324    _apply_leader_updates: Task<Result<()>>,
 1325    _observe_current_user: Task<Result<()>>,
 1326    _schedule_serialize_workspace: Option<Task<()>>,
 1327    _serialize_workspace_task: Option<Task<()>>,
 1328    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1329    pane_history_timestamp: Arc<AtomicUsize>,
 1330    bounds: Bounds<Pixels>,
 1331    pub centered_layout: bool,
 1332    bounds_save_task_queued: Option<Task<()>>,
 1333    on_prompt_for_new_path: Option<PromptForNewPath>,
 1334    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1335    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1336    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1337    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1338    _items_serializer: Task<Result<()>>,
 1339    session_id: Option<String>,
 1340    scheduled_tasks: Vec<Task<()>>,
 1341    last_open_dock_positions: Vec<DockPosition>,
 1342    removing: bool,
 1343    _panels_task: Option<Task<Result<()>>>,
 1344    sidebar_focus_handle: Option<FocusHandle>,
 1345}
 1346
 1347impl EventEmitter<Event> for Workspace {}
 1348
 1349#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1350pub struct ViewId {
 1351    pub creator: CollaboratorId,
 1352    pub id: u64,
 1353}
 1354
 1355pub struct FollowerState {
 1356    center_pane: Entity<Pane>,
 1357    dock_pane: Option<Entity<Pane>>,
 1358    active_view_id: Option<ViewId>,
 1359    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1360}
 1361
 1362struct FollowerView {
 1363    view: Box<dyn FollowableItemHandle>,
 1364    location: Option<proto::PanelId>,
 1365}
 1366
 1367impl Workspace {
 1368    pub fn new(
 1369        workspace_id: Option<WorkspaceId>,
 1370        project: Entity<Project>,
 1371        app_state: Arc<AppState>,
 1372        window: &mut Window,
 1373        cx: &mut Context<Self>,
 1374    ) -> Self {
 1375        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1376            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1377                if let TrustedWorktreesEvent::Trusted(..) = e {
 1378                    // Do not persist auto trusted worktrees
 1379                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1380                        worktrees_store.update(cx, |worktrees_store, cx| {
 1381                            worktrees_store.schedule_serialization(
 1382                                cx,
 1383                                |new_trusted_worktrees, cx| {
 1384                                    let timeout =
 1385                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1386                                    let db = WorkspaceDb::global(cx);
 1387                                    cx.background_spawn(async move {
 1388                                        timeout.await;
 1389                                        db.save_trusted_worktrees(new_trusted_worktrees)
 1390                                            .await
 1391                                            .log_err();
 1392                                    })
 1393                                },
 1394                            )
 1395                        });
 1396                    }
 1397                }
 1398            })
 1399            .detach();
 1400
 1401            cx.observe_global::<SettingsStore>(|_, cx| {
 1402                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1403                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1404                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1405                            trusted_worktrees.auto_trust_all(cx);
 1406                        })
 1407                    }
 1408                }
 1409            })
 1410            .detach();
 1411        }
 1412
 1413        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1414            match event {
 1415                project::Event::RemoteIdChanged(_) => {
 1416                    this.update_window_title(window, cx);
 1417                }
 1418
 1419                project::Event::CollaboratorLeft(peer_id) => {
 1420                    this.collaborator_left(*peer_id, window, cx);
 1421                }
 1422
 1423                &project::Event::WorktreeRemoved(_) => {
 1424                    this.update_window_title(window, cx);
 1425                    this.serialize_workspace(window, cx);
 1426                    this.update_history(cx);
 1427                }
 1428
 1429                &project::Event::WorktreeAdded(id) => {
 1430                    this.update_window_title(window, cx);
 1431                    if this
 1432                        .project()
 1433                        .read(cx)
 1434                        .worktree_for_id(id, cx)
 1435                        .is_some_and(|wt| wt.read(cx).is_visible())
 1436                    {
 1437                        this.serialize_workspace(window, cx);
 1438                        this.update_history(cx);
 1439                    }
 1440                }
 1441                project::Event::WorktreeUpdatedEntries(..) => {
 1442                    this.update_window_title(window, cx);
 1443                    this.serialize_workspace(window, cx);
 1444                }
 1445
 1446                project::Event::DisconnectedFromHost => {
 1447                    this.update_window_edited(window, cx);
 1448                    let leaders_to_unfollow =
 1449                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1450                    for leader_id in leaders_to_unfollow {
 1451                        this.unfollow(leader_id, window, cx);
 1452                    }
 1453                }
 1454
 1455                project::Event::DisconnectedFromRemote {
 1456                    server_not_running: _,
 1457                } => {
 1458                    this.update_window_edited(window, cx);
 1459                }
 1460
 1461                project::Event::Closed => {
 1462                    window.remove_window();
 1463                }
 1464
 1465                project::Event::DeletedEntry(_, entry_id) => {
 1466                    for pane in this.panes.iter() {
 1467                        pane.update(cx, |pane, cx| {
 1468                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1469                        });
 1470                    }
 1471                }
 1472
 1473                project::Event::Toast {
 1474                    notification_id,
 1475                    message,
 1476                    link,
 1477                } => this.show_notification(
 1478                    NotificationId::named(notification_id.clone()),
 1479                    cx,
 1480                    |cx| {
 1481                        let mut notification = MessageNotification::new(message.clone(), cx);
 1482                        if let Some(link) = link {
 1483                            notification = notification
 1484                                .more_info_message(link.label)
 1485                                .more_info_url(link.url);
 1486                        }
 1487
 1488                        cx.new(|_| notification)
 1489                    },
 1490                ),
 1491
 1492                project::Event::HideToast { notification_id } => {
 1493                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1494                }
 1495
 1496                project::Event::LanguageServerPrompt(request) => {
 1497                    struct LanguageServerPrompt;
 1498
 1499                    this.show_notification(
 1500                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1501                        cx,
 1502                        |cx| {
 1503                            cx.new(|cx| {
 1504                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1505                            })
 1506                        },
 1507                    );
 1508                }
 1509
 1510                project::Event::AgentLocationChanged => {
 1511                    this.handle_agent_location_changed(window, cx)
 1512                }
 1513
 1514                _ => {}
 1515            }
 1516            cx.notify()
 1517        })
 1518        .detach();
 1519
 1520        cx.subscribe_in(
 1521            &project.read(cx).breakpoint_store(),
 1522            window,
 1523            |workspace, _, event, window, cx| match event {
 1524                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1525                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1526                    workspace.serialize_workspace(window, cx);
 1527                }
 1528                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1529            },
 1530        )
 1531        .detach();
 1532        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1533            cx.subscribe_in(
 1534                &toolchain_store,
 1535                window,
 1536                |workspace, _, event, window, cx| match event {
 1537                    ToolchainStoreEvent::CustomToolchainsModified => {
 1538                        workspace.serialize_workspace(window, cx);
 1539                    }
 1540                    _ => {}
 1541                },
 1542            )
 1543            .detach();
 1544        }
 1545
 1546        cx.on_focus_lost(window, |this, window, cx| {
 1547            let focus_handle = this.focus_handle(cx);
 1548            window.focus(&focus_handle, cx);
 1549        })
 1550        .detach();
 1551
 1552        let weak_handle = cx.entity().downgrade();
 1553        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1554
 1555        let center_pane = cx.new(|cx| {
 1556            let mut center_pane = Pane::new(
 1557                weak_handle.clone(),
 1558                project.clone(),
 1559                pane_history_timestamp.clone(),
 1560                None,
 1561                NewFile.boxed_clone(),
 1562                true,
 1563                window,
 1564                cx,
 1565            );
 1566            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1567            center_pane.set_should_display_welcome_page(true);
 1568            center_pane
 1569        });
 1570        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1571            .detach();
 1572
 1573        window.focus(&center_pane.focus_handle(cx), cx);
 1574
 1575        cx.emit(Event::PaneAdded(center_pane.clone()));
 1576
 1577        let any_window_handle = window.window_handle();
 1578        app_state.workspace_store.update(cx, |store, _| {
 1579            store
 1580                .workspaces
 1581                .insert((any_window_handle, weak_handle.clone()));
 1582        });
 1583
 1584        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1585        let mut connection_status = app_state.client.status();
 1586        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1587            current_user.next().await;
 1588            connection_status.next().await;
 1589            let mut stream =
 1590                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1591
 1592            while stream.recv().await.is_some() {
 1593                this.update(cx, |_, cx| cx.notify())?;
 1594            }
 1595            anyhow::Ok(())
 1596        });
 1597
 1598        // All leader updates are enqueued and then processed in a single task, so
 1599        // that each asynchronous operation can be run in order.
 1600        let (leader_updates_tx, mut leader_updates_rx) =
 1601            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1602        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1603            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1604                Self::process_leader_update(&this, leader_id, update, cx)
 1605                    .await
 1606                    .log_err();
 1607            }
 1608
 1609            Ok(())
 1610        });
 1611
 1612        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1613        let modal_layer = cx.new(|_| ModalLayer::new());
 1614        let toast_layer = cx.new(|_| ToastLayer::new());
 1615        cx.subscribe(
 1616            &modal_layer,
 1617            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1618                cx.emit(Event::ModalOpened);
 1619            },
 1620        )
 1621        .detach();
 1622
 1623        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1624        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1625        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1626        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1627        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1628        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1629        let status_bar = cx.new(|cx| {
 1630            let mut status_bar = StatusBar::new(&center_pane.clone(), window, cx);
 1631            status_bar.add_left_item(left_dock_buttons, window, cx);
 1632            status_bar.add_right_item(right_dock_buttons, window, cx);
 1633            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1634            status_bar
 1635        });
 1636
 1637        let session_id = app_state.session.read(cx).id().to_owned();
 1638
 1639        let mut active_call = None;
 1640        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1641            let subscriptions =
 1642                vec![
 1643                    call.0
 1644                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1645                ];
 1646            active_call = Some((call, subscriptions));
 1647        }
 1648
 1649        let (serializable_items_tx, serializable_items_rx) =
 1650            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1651        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1652            Self::serialize_items(&this, serializable_items_rx, cx).await
 1653        });
 1654
 1655        let subscriptions = vec![
 1656            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1657            cx.observe_window_bounds(window, move |this, window, cx| {
 1658                if this.bounds_save_task_queued.is_some() {
 1659                    return;
 1660                }
 1661                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1662                    cx.background_executor()
 1663                        .timer(Duration::from_millis(100))
 1664                        .await;
 1665                    this.update_in(cx, |this, window, cx| {
 1666                        this.save_window_bounds(window, cx).detach();
 1667                        this.bounds_save_task_queued.take();
 1668                    })
 1669                    .ok();
 1670                }));
 1671                cx.notify();
 1672            }),
 1673            cx.observe_window_appearance(window, |_, window, cx| {
 1674                let window_appearance = window.appearance();
 1675
 1676                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1677
 1678                GlobalTheme::reload_theme(cx);
 1679                GlobalTheme::reload_icon_theme(cx);
 1680            }),
 1681            cx.on_release({
 1682                let weak_handle = weak_handle.clone();
 1683                move |this, cx| {
 1684                    this.app_state.workspace_store.update(cx, move |store, _| {
 1685                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1686                    })
 1687                }
 1688            }),
 1689        ];
 1690
 1691        cx.defer_in(window, move |this, window, cx| {
 1692            this.update_window_title(window, cx);
 1693            this.show_initial_notifications(cx);
 1694        });
 1695
 1696        let mut center = PaneGroup::new(center_pane.clone());
 1697        center.set_is_center(true);
 1698        center.mark_positions(cx);
 1699
 1700        Workspace {
 1701            weak_self: weak_handle.clone(),
 1702            zoomed: None,
 1703            zoomed_position: None,
 1704            previous_dock_drag_coordinates: None,
 1705            center,
 1706            panes: vec![center_pane.clone()],
 1707            panes_by_item: Default::default(),
 1708            active_pane: center_pane.clone(),
 1709            last_active_center_pane: Some(center_pane.downgrade()),
 1710            last_active_view_id: None,
 1711            status_bar,
 1712            modal_layer,
 1713            toast_layer,
 1714            titlebar_item: None,
 1715            active_worktree_override: None,
 1716            notifications: Notifications::default(),
 1717            suppressed_notifications: HashSet::default(),
 1718            left_dock,
 1719            bottom_dock,
 1720            right_dock,
 1721            _panels_task: None,
 1722            project: project.clone(),
 1723            follower_states: Default::default(),
 1724            last_leaders_by_pane: Default::default(),
 1725            dispatching_keystrokes: Default::default(),
 1726            window_edited: false,
 1727            last_window_title: None,
 1728            dirty_items: Default::default(),
 1729            active_call,
 1730            database_id: workspace_id,
 1731            app_state,
 1732            _observe_current_user,
 1733            _apply_leader_updates,
 1734            _schedule_serialize_workspace: None,
 1735            _serialize_workspace_task: None,
 1736            _schedule_serialize_ssh_paths: None,
 1737            leader_updates_tx,
 1738            _subscriptions: subscriptions,
 1739            pane_history_timestamp,
 1740            workspace_actions: Default::default(),
 1741            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1742            bounds: Default::default(),
 1743            centered_layout: false,
 1744            bounds_save_task_queued: None,
 1745            on_prompt_for_new_path: None,
 1746            on_prompt_for_open_path: None,
 1747            terminal_provider: None,
 1748            debugger_provider: None,
 1749            serializable_items_tx,
 1750            _items_serializer,
 1751            session_id: Some(session_id),
 1752
 1753            scheduled_tasks: Vec::new(),
 1754            last_open_dock_positions: Vec::new(),
 1755            removing: false,
 1756            sidebar_focus_handle: None,
 1757        }
 1758    }
 1759
 1760    pub fn new_local(
 1761        abs_paths: Vec<PathBuf>,
 1762        app_state: Arc<AppState>,
 1763        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1764        env: Option<HashMap<String, String>>,
 1765        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1766        activate: bool,
 1767        cx: &mut App,
 1768    ) -> Task<anyhow::Result<OpenResult>> {
 1769        let project_handle = Project::local(
 1770            app_state.client.clone(),
 1771            app_state.node_runtime.clone(),
 1772            app_state.user_store.clone(),
 1773            app_state.languages.clone(),
 1774            app_state.fs.clone(),
 1775            env,
 1776            Default::default(),
 1777            cx,
 1778        );
 1779
 1780        let db = WorkspaceDb::global(cx);
 1781        let kvp = db::kvp::KeyValueStore::global(cx);
 1782        cx.spawn(async move |cx| {
 1783            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1784            for path in abs_paths.into_iter() {
 1785                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1786                    paths_to_open.push(canonical)
 1787                } else {
 1788                    paths_to_open.push(path)
 1789                }
 1790            }
 1791
 1792            let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
 1793
 1794            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1795                paths_to_open = paths.ordered_paths().cloned().collect();
 1796                if !paths.is_lexicographically_ordered() {
 1797                    project_handle.update(cx, |project, cx| {
 1798                        project.set_worktrees_reordered(true, cx);
 1799                    });
 1800                }
 1801            }
 1802
 1803            // Get project paths for all of the abs_paths
 1804            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1805                Vec::with_capacity(paths_to_open.len());
 1806
 1807            for path in paths_to_open.into_iter() {
 1808                if let Some((_, project_entry)) = cx
 1809                    .update(|cx| {
 1810                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1811                    })
 1812                    .await
 1813                    .log_err()
 1814                {
 1815                    project_paths.push((path, Some(project_entry)));
 1816                } else {
 1817                    project_paths.push((path, None));
 1818                }
 1819            }
 1820
 1821            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1822                serialized_workspace.id
 1823            } else {
 1824                db.next_id().await.unwrap_or_else(|_| Default::default())
 1825            };
 1826
 1827            let toolchains = db.toolchains(workspace_id).await?;
 1828
 1829            for (toolchain, worktree_path, path) in toolchains {
 1830                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1831                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1832                    this.find_worktree(&worktree_path, cx)
 1833                        .and_then(|(worktree, rel_path)| {
 1834                            if rel_path.is_empty() {
 1835                                Some(worktree.read(cx).id())
 1836                            } else {
 1837                                None
 1838                            }
 1839                        })
 1840                }) else {
 1841                    // We did not find a worktree with a given path, but that's whatever.
 1842                    continue;
 1843                };
 1844                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1845                    continue;
 1846                }
 1847
 1848                project_handle
 1849                    .update(cx, |this, cx| {
 1850                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1851                    })
 1852                    .await;
 1853            }
 1854            if let Some(workspace) = serialized_workspace.as_ref() {
 1855                project_handle.update(cx, |this, cx| {
 1856                    for (scope, toolchains) in &workspace.user_toolchains {
 1857                        for toolchain in toolchains {
 1858                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1859                        }
 1860                    }
 1861                });
 1862            }
 1863
 1864            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1865                if let Some(window) = requesting_window {
 1866                    let centered_layout = serialized_workspace
 1867                        .as_ref()
 1868                        .map(|w| w.centered_layout)
 1869                        .unwrap_or(false);
 1870
 1871                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1872                        let workspace = cx.new(|cx| {
 1873                            let mut workspace = Workspace::new(
 1874                                Some(workspace_id),
 1875                                project_handle.clone(),
 1876                                app_state.clone(),
 1877                                window,
 1878                                cx,
 1879                            );
 1880
 1881                            workspace.centered_layout = centered_layout;
 1882
 1883                            // Call init callback to add items before window renders
 1884                            if let Some(init) = init {
 1885                                init(&mut workspace, window, cx);
 1886                            }
 1887
 1888                            workspace
 1889                        });
 1890                        if activate {
 1891                            multi_workspace.activate(workspace.clone(), cx);
 1892                        } else {
 1893                            multi_workspace.add_workspace(workspace.clone(), cx);
 1894                        }
 1895                        workspace
 1896                    })?;
 1897                    (window, workspace)
 1898                } else {
 1899                    let window_bounds_override = window_bounds_env_override();
 1900
 1901                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1902                        (Some(WindowBounds::Windowed(bounds)), None)
 1903                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1904                        && let Some(display) = workspace.display
 1905                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1906                    {
 1907                        // Reopening an existing workspace - restore its saved bounds
 1908                        (Some(bounds.0), Some(display))
 1909                    } else if let Some((display, bounds)) =
 1910                        persistence::read_default_window_bounds(&kvp)
 1911                    {
 1912                        // New or empty workspace - use the last known window bounds
 1913                        (Some(bounds), Some(display))
 1914                    } else {
 1915                        // New window - let GPUI's default_bounds() handle cascading
 1916                        (None, None)
 1917                    };
 1918
 1919                    // Use the serialized workspace to construct the new window
 1920                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1921                    options.window_bounds = window_bounds;
 1922                    let centered_layout = serialized_workspace
 1923                        .as_ref()
 1924                        .map(|w| w.centered_layout)
 1925                        .unwrap_or(false);
 1926                    let window = cx.open_window(options, {
 1927                        let app_state = app_state.clone();
 1928                        let project_handle = project_handle.clone();
 1929                        move |window, cx| {
 1930                            let workspace = cx.new(|cx| {
 1931                                let mut workspace = Workspace::new(
 1932                                    Some(workspace_id),
 1933                                    project_handle,
 1934                                    app_state,
 1935                                    window,
 1936                                    cx,
 1937                                );
 1938                                workspace.centered_layout = centered_layout;
 1939
 1940                                // Call init callback to add items before window renders
 1941                                if let Some(init) = init {
 1942                                    init(&mut workspace, window, cx);
 1943                                }
 1944
 1945                                workspace
 1946                            });
 1947                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 1948                        }
 1949                    })?;
 1950                    let workspace =
 1951                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 1952                            multi_workspace.workspace().clone()
 1953                        })?;
 1954                    (window, workspace)
 1955                };
 1956
 1957            notify_if_database_failed(window, cx);
 1958            // Check if this is an empty workspace (no paths to open)
 1959            // An empty workspace is one where project_paths is empty
 1960            let is_empty_workspace = project_paths.is_empty();
 1961            // Check if serialized workspace has paths before it's moved
 1962            let serialized_workspace_has_paths = serialized_workspace
 1963                .as_ref()
 1964                .map(|ws| !ws.paths.is_empty())
 1965                .unwrap_or(false);
 1966
 1967            let opened_items = window
 1968                .update(cx, |_, window, cx| {
 1969                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 1970                        open_items(serialized_workspace, project_paths, window, cx)
 1971                    })
 1972                })?
 1973                .await
 1974                .unwrap_or_default();
 1975
 1976            // Restore default dock state for empty workspaces
 1977            // Only restore if:
 1978            // 1. This is an empty workspace (no paths), AND
 1979            // 2. The serialized workspace either doesn't exist or has no paths
 1980            if is_empty_workspace && !serialized_workspace_has_paths {
 1981                if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
 1982                    window
 1983                        .update(cx, |_, window, cx| {
 1984                            workspace.update(cx, |workspace, cx| {
 1985                                for (dock, serialized_dock) in [
 1986                                    (&workspace.right_dock, &default_docks.right),
 1987                                    (&workspace.left_dock, &default_docks.left),
 1988                                    (&workspace.bottom_dock, &default_docks.bottom),
 1989                                ] {
 1990                                    dock.update(cx, |dock, cx| {
 1991                                        dock.serialized_dock = Some(serialized_dock.clone());
 1992                                        dock.restore_state(window, cx);
 1993                                    });
 1994                                }
 1995                                cx.notify();
 1996                            });
 1997                        })
 1998                        .log_err();
 1999                }
 2000            }
 2001
 2002            window
 2003                .update(cx, |_, _window, cx| {
 2004                    workspace.update(cx, |this: &mut Workspace, cx| {
 2005                        this.update_history(cx);
 2006                    });
 2007                })
 2008                .log_err();
 2009            Ok(OpenResult {
 2010                window,
 2011                workspace,
 2012                opened_items,
 2013            })
 2014        })
 2015    }
 2016
 2017    pub fn weak_handle(&self) -> WeakEntity<Self> {
 2018        self.weak_self.clone()
 2019    }
 2020
 2021    pub fn left_dock(&self) -> &Entity<Dock> {
 2022        &self.left_dock
 2023    }
 2024
 2025    pub fn bottom_dock(&self) -> &Entity<Dock> {
 2026        &self.bottom_dock
 2027    }
 2028
 2029    pub fn set_bottom_dock_layout(
 2030        &mut self,
 2031        layout: BottomDockLayout,
 2032        window: &mut Window,
 2033        cx: &mut Context<Self>,
 2034    ) {
 2035        let fs = self.project().read(cx).fs();
 2036        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 2037            content.workspace.bottom_dock_layout = Some(layout);
 2038        });
 2039
 2040        cx.notify();
 2041        self.serialize_workspace(window, cx);
 2042    }
 2043
 2044    pub fn right_dock(&self) -> &Entity<Dock> {
 2045        &self.right_dock
 2046    }
 2047
 2048    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 2049        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 2050    }
 2051
 2052    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 2053        let left_dock = self.left_dock.read(cx);
 2054        let left_visible = left_dock.is_open();
 2055        let left_active_panel = left_dock
 2056            .active_panel()
 2057            .map(|panel| panel.persistent_name().to_string());
 2058        // `zoomed_position` is kept in sync with individual panel zoom state
 2059        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2060        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2061
 2062        let right_dock = self.right_dock.read(cx);
 2063        let right_visible = right_dock.is_open();
 2064        let right_active_panel = right_dock
 2065            .active_panel()
 2066            .map(|panel| panel.persistent_name().to_string());
 2067        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2068
 2069        let bottom_dock = self.bottom_dock.read(cx);
 2070        let bottom_visible = bottom_dock.is_open();
 2071        let bottom_active_panel = bottom_dock
 2072            .active_panel()
 2073            .map(|panel| panel.persistent_name().to_string());
 2074        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2075
 2076        DockStructure {
 2077            left: DockData {
 2078                visible: left_visible,
 2079                active_panel: left_active_panel,
 2080                zoom: left_dock_zoom,
 2081            },
 2082            right: DockData {
 2083                visible: right_visible,
 2084                active_panel: right_active_panel,
 2085                zoom: right_dock_zoom,
 2086            },
 2087            bottom: DockData {
 2088                visible: bottom_visible,
 2089                active_panel: bottom_active_panel,
 2090                zoom: bottom_dock_zoom,
 2091            },
 2092        }
 2093    }
 2094
 2095    pub fn set_dock_structure(
 2096        &self,
 2097        docks: DockStructure,
 2098        window: &mut Window,
 2099        cx: &mut Context<Self>,
 2100    ) {
 2101        for (dock, data) in [
 2102            (&self.left_dock, docks.left),
 2103            (&self.bottom_dock, docks.bottom),
 2104            (&self.right_dock, docks.right),
 2105        ] {
 2106            dock.update(cx, |dock, cx| {
 2107                dock.serialized_dock = Some(data);
 2108                dock.restore_state(window, cx);
 2109            });
 2110        }
 2111    }
 2112
 2113    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2114        self.items(cx)
 2115            .filter_map(|item| {
 2116                let project_path = item.project_path(cx)?;
 2117                self.project.read(cx).absolute_path(&project_path, cx)
 2118            })
 2119            .collect()
 2120    }
 2121
 2122    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2123        match position {
 2124            DockPosition::Left => &self.left_dock,
 2125            DockPosition::Bottom => &self.bottom_dock,
 2126            DockPosition::Right => &self.right_dock,
 2127        }
 2128    }
 2129
 2130    pub fn is_edited(&self) -> bool {
 2131        self.window_edited
 2132    }
 2133
 2134    pub fn add_panel<T: Panel>(
 2135        &mut self,
 2136        panel: Entity<T>,
 2137        window: &mut Window,
 2138        cx: &mut Context<Self>,
 2139    ) {
 2140        let focus_handle = panel.panel_focus_handle(cx);
 2141        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2142            .detach();
 2143
 2144        let dock_position = panel.position(window, cx);
 2145        let dock = self.dock_at_position(dock_position);
 2146        let any_panel = panel.to_any();
 2147
 2148        dock.update(cx, |dock, cx| {
 2149            dock.add_panel(panel, self.weak_self.clone(), window, cx)
 2150        });
 2151
 2152        cx.emit(Event::PanelAdded(any_panel));
 2153    }
 2154
 2155    pub fn remove_panel<T: Panel>(
 2156        &mut self,
 2157        panel: &Entity<T>,
 2158        window: &mut Window,
 2159        cx: &mut Context<Self>,
 2160    ) {
 2161        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2162            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2163        }
 2164    }
 2165
 2166    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2167        &self.status_bar
 2168    }
 2169
 2170    pub fn set_workspace_sidebar_open(
 2171        &self,
 2172        open: bool,
 2173        has_notifications: bool,
 2174        show_toggle: bool,
 2175        cx: &mut App,
 2176    ) {
 2177        self.status_bar.update(cx, |status_bar, cx| {
 2178            status_bar.set_workspace_sidebar_open(open, cx);
 2179            status_bar.set_sidebar_has_notifications(has_notifications, cx);
 2180            status_bar.set_show_sidebar_toggle(show_toggle, cx);
 2181        });
 2182    }
 2183
 2184    pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
 2185        self.sidebar_focus_handle = handle;
 2186    }
 2187
 2188    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2189        StatusBarSettings::get_global(cx).show
 2190    }
 2191
 2192    pub fn app_state(&self) -> &Arc<AppState> {
 2193        &self.app_state
 2194    }
 2195
 2196    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2197        self._panels_task = Some(task);
 2198    }
 2199
 2200    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2201        self._panels_task.take()
 2202    }
 2203
 2204    pub fn user_store(&self) -> &Entity<UserStore> {
 2205        &self.app_state.user_store
 2206    }
 2207
 2208    pub fn project(&self) -> &Entity<Project> {
 2209        &self.project
 2210    }
 2211
 2212    pub fn path_style(&self, cx: &App) -> PathStyle {
 2213        self.project.read(cx).path_style(cx)
 2214    }
 2215
 2216    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2217        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2218
 2219        for pane_handle in &self.panes {
 2220            let pane = pane_handle.read(cx);
 2221
 2222            for entry in pane.activation_history() {
 2223                history.insert(
 2224                    entry.entity_id,
 2225                    history
 2226                        .get(&entry.entity_id)
 2227                        .cloned()
 2228                        .unwrap_or(0)
 2229                        .max(entry.timestamp),
 2230                );
 2231            }
 2232        }
 2233
 2234        history
 2235    }
 2236
 2237    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2238        let mut recent_item: Option<Entity<T>> = None;
 2239        let mut recent_timestamp = 0;
 2240        for pane_handle in &self.panes {
 2241            let pane = pane_handle.read(cx);
 2242            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2243                pane.items().map(|item| (item.item_id(), item)).collect();
 2244            for entry in pane.activation_history() {
 2245                if entry.timestamp > recent_timestamp
 2246                    && let Some(&item) = item_map.get(&entry.entity_id)
 2247                    && let Some(typed_item) = item.act_as::<T>(cx)
 2248                {
 2249                    recent_timestamp = entry.timestamp;
 2250                    recent_item = Some(typed_item);
 2251                }
 2252            }
 2253        }
 2254        recent_item
 2255    }
 2256
 2257    pub fn recent_navigation_history_iter(
 2258        &self,
 2259        cx: &App,
 2260    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2261        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2262        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2263
 2264        for pane in &self.panes {
 2265            let pane = pane.read(cx);
 2266
 2267            pane.nav_history()
 2268                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2269                    if let Some(fs_path) = &fs_path {
 2270                        abs_paths_opened
 2271                            .entry(fs_path.clone())
 2272                            .or_default()
 2273                            .insert(project_path.clone());
 2274                    }
 2275                    let timestamp = entry.timestamp;
 2276                    match history.entry(project_path) {
 2277                        hash_map::Entry::Occupied(mut entry) => {
 2278                            let (_, old_timestamp) = entry.get();
 2279                            if &timestamp > old_timestamp {
 2280                                entry.insert((fs_path, timestamp));
 2281                            }
 2282                        }
 2283                        hash_map::Entry::Vacant(entry) => {
 2284                            entry.insert((fs_path, timestamp));
 2285                        }
 2286                    }
 2287                });
 2288
 2289            if let Some(item) = pane.active_item()
 2290                && let Some(project_path) = item.project_path(cx)
 2291            {
 2292                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2293
 2294                if let Some(fs_path) = &fs_path {
 2295                    abs_paths_opened
 2296                        .entry(fs_path.clone())
 2297                        .or_default()
 2298                        .insert(project_path.clone());
 2299                }
 2300
 2301                history.insert(project_path, (fs_path, std::usize::MAX));
 2302            }
 2303        }
 2304
 2305        history
 2306            .into_iter()
 2307            .sorted_by_key(|(_, (_, order))| *order)
 2308            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2309            .rev()
 2310            .filter(move |(history_path, abs_path)| {
 2311                let latest_project_path_opened = abs_path
 2312                    .as_ref()
 2313                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2314                    .and_then(|project_paths| {
 2315                        project_paths
 2316                            .iter()
 2317                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2318                    });
 2319
 2320                latest_project_path_opened.is_none_or(|path| path == history_path)
 2321            })
 2322    }
 2323
 2324    pub fn recent_navigation_history(
 2325        &self,
 2326        limit: Option<usize>,
 2327        cx: &App,
 2328    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2329        self.recent_navigation_history_iter(cx)
 2330            .take(limit.unwrap_or(usize::MAX))
 2331            .collect()
 2332    }
 2333
 2334    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2335        for pane in &self.panes {
 2336            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2337        }
 2338    }
 2339
 2340    fn navigate_history(
 2341        &mut self,
 2342        pane: WeakEntity<Pane>,
 2343        mode: NavigationMode,
 2344        window: &mut Window,
 2345        cx: &mut Context<Workspace>,
 2346    ) -> Task<Result<()>> {
 2347        self.navigate_history_impl(
 2348            pane,
 2349            mode,
 2350            window,
 2351            &mut |history, cx| history.pop(mode, cx),
 2352            cx,
 2353        )
 2354    }
 2355
 2356    fn navigate_tag_history(
 2357        &mut self,
 2358        pane: WeakEntity<Pane>,
 2359        mode: TagNavigationMode,
 2360        window: &mut Window,
 2361        cx: &mut Context<Workspace>,
 2362    ) -> Task<Result<()>> {
 2363        self.navigate_history_impl(
 2364            pane,
 2365            NavigationMode::Normal,
 2366            window,
 2367            &mut |history, _cx| history.pop_tag(mode),
 2368            cx,
 2369        )
 2370    }
 2371
 2372    fn navigate_history_impl(
 2373        &mut self,
 2374        pane: WeakEntity<Pane>,
 2375        mode: NavigationMode,
 2376        window: &mut Window,
 2377        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2378        cx: &mut Context<Workspace>,
 2379    ) -> Task<Result<()>> {
 2380        let to_load = if let Some(pane) = pane.upgrade() {
 2381            pane.update(cx, |pane, cx| {
 2382                window.focus(&pane.focus_handle(cx), cx);
 2383                loop {
 2384                    // Retrieve the weak item handle from the history.
 2385                    let entry = cb(pane.nav_history_mut(), cx)?;
 2386
 2387                    // If the item is still present in this pane, then activate it.
 2388                    if let Some(index) = entry
 2389                        .item
 2390                        .upgrade()
 2391                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2392                    {
 2393                        let prev_active_item_index = pane.active_item_index();
 2394                        pane.nav_history_mut().set_mode(mode);
 2395                        pane.activate_item(index, true, true, window, cx);
 2396                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2397
 2398                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2399                        if let Some(data) = entry.data {
 2400                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2401                        }
 2402
 2403                        if navigated {
 2404                            break None;
 2405                        }
 2406                    } else {
 2407                        // If the item is no longer present in this pane, then retrieve its
 2408                        // path info in order to reopen it.
 2409                        break pane
 2410                            .nav_history()
 2411                            .path_for_item(entry.item.id())
 2412                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2413                    }
 2414                }
 2415            })
 2416        } else {
 2417            None
 2418        };
 2419
 2420        if let Some((project_path, abs_path, entry)) = to_load {
 2421            // If the item was no longer present, then load it again from its previous path, first try the local path
 2422            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2423
 2424            cx.spawn_in(window, async move  |workspace, cx| {
 2425                let open_by_project_path = open_by_project_path.await;
 2426                let mut navigated = false;
 2427                match open_by_project_path
 2428                    .with_context(|| format!("Navigating to {project_path:?}"))
 2429                {
 2430                    Ok((project_entry_id, build_item)) => {
 2431                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2432                            pane.nav_history_mut().set_mode(mode);
 2433                            pane.active_item().map(|p| p.item_id())
 2434                        })?;
 2435
 2436                        pane.update_in(cx, |pane, window, cx| {
 2437                            let item = pane.open_item(
 2438                                project_entry_id,
 2439                                project_path,
 2440                                true,
 2441                                entry.is_preview,
 2442                                true,
 2443                                None,
 2444                                window, cx,
 2445                                build_item,
 2446                            );
 2447                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2448                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2449                            if let Some(data) = entry.data {
 2450                                navigated |= item.navigate(data, window, cx);
 2451                            }
 2452                        })?;
 2453                    }
 2454                    Err(open_by_project_path_e) => {
 2455                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2456                        // and its worktree is now dropped
 2457                        if let Some(abs_path) = abs_path {
 2458                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2459                                pane.nav_history_mut().set_mode(mode);
 2460                                pane.active_item().map(|p| p.item_id())
 2461                            })?;
 2462                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2463                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2464                            })?;
 2465                            match open_by_abs_path
 2466                                .await
 2467                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2468                            {
 2469                                Ok(item) => {
 2470                                    pane.update_in(cx, |pane, window, cx| {
 2471                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2472                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2473                                        if let Some(data) = entry.data {
 2474                                            navigated |= item.navigate(data, window, cx);
 2475                                        }
 2476                                    })?;
 2477                                }
 2478                                Err(open_by_abs_path_e) => {
 2479                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2480                                }
 2481                            }
 2482                        }
 2483                    }
 2484                }
 2485
 2486                if !navigated {
 2487                    workspace
 2488                        .update_in(cx, |workspace, window, cx| {
 2489                            Self::navigate_history(workspace, pane, mode, window, cx)
 2490                        })?
 2491                        .await?;
 2492                }
 2493
 2494                Ok(())
 2495            })
 2496        } else {
 2497            Task::ready(Ok(()))
 2498        }
 2499    }
 2500
 2501    pub fn go_back(
 2502        &mut self,
 2503        pane: WeakEntity<Pane>,
 2504        window: &mut Window,
 2505        cx: &mut Context<Workspace>,
 2506    ) -> Task<Result<()>> {
 2507        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2508    }
 2509
 2510    pub fn go_forward(
 2511        &mut self,
 2512        pane: WeakEntity<Pane>,
 2513        window: &mut Window,
 2514        cx: &mut Context<Workspace>,
 2515    ) -> Task<Result<()>> {
 2516        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2517    }
 2518
 2519    pub fn reopen_closed_item(
 2520        &mut self,
 2521        window: &mut Window,
 2522        cx: &mut Context<Workspace>,
 2523    ) -> Task<Result<()>> {
 2524        self.navigate_history(
 2525            self.active_pane().downgrade(),
 2526            NavigationMode::ReopeningClosedItem,
 2527            window,
 2528            cx,
 2529        )
 2530    }
 2531
 2532    pub fn client(&self) -> &Arc<Client> {
 2533        &self.app_state.client
 2534    }
 2535
 2536    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2537        self.titlebar_item = Some(item);
 2538        cx.notify();
 2539    }
 2540
 2541    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2542        self.on_prompt_for_new_path = Some(prompt)
 2543    }
 2544
 2545    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2546        self.on_prompt_for_open_path = Some(prompt)
 2547    }
 2548
 2549    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2550        self.terminal_provider = Some(Box::new(provider));
 2551    }
 2552
 2553    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2554        self.debugger_provider = Some(Arc::new(provider));
 2555    }
 2556
 2557    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2558        self.debugger_provider.clone()
 2559    }
 2560
 2561    pub fn prompt_for_open_path(
 2562        &mut self,
 2563        path_prompt_options: PathPromptOptions,
 2564        lister: DirectoryLister,
 2565        window: &mut Window,
 2566        cx: &mut Context<Self>,
 2567    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2568        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2569            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2570            let rx = prompt(self, lister, window, cx);
 2571            self.on_prompt_for_open_path = Some(prompt);
 2572            rx
 2573        } else {
 2574            let (tx, rx) = oneshot::channel();
 2575            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2576
 2577            cx.spawn_in(window, async move |workspace, cx| {
 2578                let Ok(result) = abs_path.await else {
 2579                    return Ok(());
 2580                };
 2581
 2582                match result {
 2583                    Ok(result) => {
 2584                        tx.send(result).ok();
 2585                    }
 2586                    Err(err) => {
 2587                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2588                            workspace.show_portal_error(err.to_string(), cx);
 2589                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2590                            let rx = prompt(workspace, lister, window, cx);
 2591                            workspace.on_prompt_for_open_path = Some(prompt);
 2592                            rx
 2593                        })?;
 2594                        if let Ok(path) = rx.await {
 2595                            tx.send(path).ok();
 2596                        }
 2597                    }
 2598                };
 2599                anyhow::Ok(())
 2600            })
 2601            .detach();
 2602
 2603            rx
 2604        }
 2605    }
 2606
 2607    pub fn prompt_for_new_path(
 2608        &mut self,
 2609        lister: DirectoryLister,
 2610        suggested_name: Option<String>,
 2611        window: &mut Window,
 2612        cx: &mut Context<Self>,
 2613    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2614        if self.project.read(cx).is_via_collab()
 2615            || self.project.read(cx).is_via_remote_server()
 2616            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2617        {
 2618            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2619            let rx = prompt(self, lister, suggested_name, window, cx);
 2620            self.on_prompt_for_new_path = Some(prompt);
 2621            return rx;
 2622        }
 2623
 2624        let (tx, rx) = oneshot::channel();
 2625        cx.spawn_in(window, async move |workspace, cx| {
 2626            let abs_path = workspace.update(cx, |workspace, cx| {
 2627                let relative_to = workspace
 2628                    .most_recent_active_path(cx)
 2629                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2630                    .or_else(|| {
 2631                        let project = workspace.project.read(cx);
 2632                        project.visible_worktrees(cx).find_map(|worktree| {
 2633                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2634                        })
 2635                    })
 2636                    .or_else(std::env::home_dir)
 2637                    .unwrap_or_else(|| PathBuf::from(""));
 2638                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2639            })?;
 2640            let abs_path = match abs_path.await? {
 2641                Ok(path) => path,
 2642                Err(err) => {
 2643                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2644                        workspace.show_portal_error(err.to_string(), cx);
 2645
 2646                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2647                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2648                        workspace.on_prompt_for_new_path = Some(prompt);
 2649                        rx
 2650                    })?;
 2651                    if let Ok(path) = rx.await {
 2652                        tx.send(path).ok();
 2653                    }
 2654                    return anyhow::Ok(());
 2655                }
 2656            };
 2657
 2658            tx.send(abs_path.map(|path| vec![path])).ok();
 2659            anyhow::Ok(())
 2660        })
 2661        .detach();
 2662
 2663        rx
 2664    }
 2665
 2666    pub fn titlebar_item(&self) -> Option<AnyView> {
 2667        self.titlebar_item.clone()
 2668    }
 2669
 2670    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2671    /// When set, git-related operations should use this worktree instead of deriving
 2672    /// the active worktree from the focused file.
 2673    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2674        self.active_worktree_override
 2675    }
 2676
 2677    pub fn set_active_worktree_override(
 2678        &mut self,
 2679        worktree_id: Option<WorktreeId>,
 2680        cx: &mut Context<Self>,
 2681    ) {
 2682        self.active_worktree_override = worktree_id;
 2683        cx.notify();
 2684    }
 2685
 2686    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2687        self.active_worktree_override = None;
 2688        cx.notify();
 2689    }
 2690
 2691    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2692    ///
 2693    /// If the given workspace has a local project, then it will be passed
 2694    /// to the callback. Otherwise, a new empty window will be created.
 2695    pub fn with_local_workspace<T, F>(
 2696        &mut self,
 2697        window: &mut Window,
 2698        cx: &mut Context<Self>,
 2699        callback: F,
 2700    ) -> Task<Result<T>>
 2701    where
 2702        T: 'static,
 2703        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2704    {
 2705        if self.project.read(cx).is_local() {
 2706            Task::ready(Ok(callback(self, window, cx)))
 2707        } else {
 2708            let env = self.project.read(cx).cli_environment(cx);
 2709            let task = Self::new_local(
 2710                Vec::new(),
 2711                self.app_state.clone(),
 2712                None,
 2713                env,
 2714                None,
 2715                true,
 2716                cx,
 2717            );
 2718            cx.spawn_in(window, async move |_vh, cx| {
 2719                let OpenResult {
 2720                    window: multi_workspace_window,
 2721                    ..
 2722                } = task.await?;
 2723                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2724                    let workspace = multi_workspace.workspace().clone();
 2725                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2726                })
 2727            })
 2728        }
 2729    }
 2730
 2731    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2732    ///
 2733    /// If the given workspace has a local project, then it will be passed
 2734    /// to the callback. Otherwise, a new empty window will be created.
 2735    pub fn with_local_or_wsl_workspace<T, F>(
 2736        &mut self,
 2737        window: &mut Window,
 2738        cx: &mut Context<Self>,
 2739        callback: F,
 2740    ) -> Task<Result<T>>
 2741    where
 2742        T: 'static,
 2743        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2744    {
 2745        let project = self.project.read(cx);
 2746        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 2747            Task::ready(Ok(callback(self, window, cx)))
 2748        } else {
 2749            let env = self.project.read(cx).cli_environment(cx);
 2750            let task = Self::new_local(
 2751                Vec::new(),
 2752                self.app_state.clone(),
 2753                None,
 2754                env,
 2755                None,
 2756                true,
 2757                cx,
 2758            );
 2759            cx.spawn_in(window, async move |_vh, cx| {
 2760                let OpenResult {
 2761                    window: multi_workspace_window,
 2762                    ..
 2763                } = task.await?;
 2764                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2765                    let workspace = multi_workspace.workspace().clone();
 2766                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2767                })
 2768            })
 2769        }
 2770    }
 2771
 2772    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2773        self.project.read(cx).worktrees(cx)
 2774    }
 2775
 2776    pub fn visible_worktrees<'a>(
 2777        &self,
 2778        cx: &'a App,
 2779    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2780        self.project.read(cx).visible_worktrees(cx)
 2781    }
 2782
 2783    #[cfg(any(test, feature = "test-support"))]
 2784    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2785        let futures = self
 2786            .worktrees(cx)
 2787            .filter_map(|worktree| worktree.read(cx).as_local())
 2788            .map(|worktree| worktree.scan_complete())
 2789            .collect::<Vec<_>>();
 2790        async move {
 2791            for future in futures {
 2792                future.await;
 2793            }
 2794        }
 2795    }
 2796
 2797    pub fn close_global(cx: &mut App) {
 2798        cx.defer(|cx| {
 2799            cx.windows().iter().find(|window| {
 2800                window
 2801                    .update(cx, |_, window, _| {
 2802                        if window.is_window_active() {
 2803                            //This can only get called when the window's project connection has been lost
 2804                            //so we don't need to prompt the user for anything and instead just close the window
 2805                            window.remove_window();
 2806                            true
 2807                        } else {
 2808                            false
 2809                        }
 2810                    })
 2811                    .unwrap_or(false)
 2812            });
 2813        });
 2814    }
 2815
 2816    pub fn move_focused_panel_to_next_position(
 2817        &mut self,
 2818        _: &MoveFocusedPanelToNextPosition,
 2819        window: &mut Window,
 2820        cx: &mut Context<Self>,
 2821    ) {
 2822        let docks = self.all_docks();
 2823        let active_dock = docks
 2824            .into_iter()
 2825            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 2826
 2827        if let Some(dock) = active_dock {
 2828            dock.update(cx, |dock, cx| {
 2829                let active_panel = dock
 2830                    .active_panel()
 2831                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 2832
 2833                if let Some(panel) = active_panel {
 2834                    panel.move_to_next_position(window, cx);
 2835                }
 2836            })
 2837        }
 2838    }
 2839
 2840    pub fn prepare_to_close(
 2841        &mut self,
 2842        close_intent: CloseIntent,
 2843        window: &mut Window,
 2844        cx: &mut Context<Self>,
 2845    ) -> Task<Result<bool>> {
 2846        let active_call = self.active_global_call();
 2847
 2848        cx.spawn_in(window, async move |this, cx| {
 2849            this.update(cx, |this, _| {
 2850                if close_intent == CloseIntent::CloseWindow {
 2851                    this.removing = true;
 2852                }
 2853            })?;
 2854
 2855            let workspace_count = cx.update(|_window, cx| {
 2856                cx.windows()
 2857                    .iter()
 2858                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 2859                    .count()
 2860            })?;
 2861
 2862            #[cfg(target_os = "macos")]
 2863            let save_last_workspace = false;
 2864
 2865            // On Linux and Windows, closing the last window should restore the last workspace.
 2866            #[cfg(not(target_os = "macos"))]
 2867            let save_last_workspace = {
 2868                let remaining_workspaces = cx.update(|_window, cx| {
 2869                    cx.windows()
 2870                        .iter()
 2871                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 2872                        .filter_map(|multi_workspace| {
 2873                            multi_workspace
 2874                                .update(cx, |multi_workspace, _, cx| {
 2875                                    multi_workspace.workspace().read(cx).removing
 2876                                })
 2877                                .ok()
 2878                        })
 2879                        .filter(|removing| !removing)
 2880                        .count()
 2881                })?;
 2882
 2883                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 2884            };
 2885
 2886            if let Some(active_call) = active_call
 2887                && workspace_count == 1
 2888                && cx
 2889                    .update(|_window, cx| active_call.0.is_in_room(cx))
 2890                    .unwrap_or(false)
 2891            {
 2892                if close_intent == CloseIntent::CloseWindow {
 2893                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 2894                    let answer = cx.update(|window, cx| {
 2895                        window.prompt(
 2896                            PromptLevel::Warning,
 2897                            "Do you want to leave the current call?",
 2898                            None,
 2899                            &["Close window and hang up", "Cancel"],
 2900                            cx,
 2901                        )
 2902                    })?;
 2903
 2904                    if answer.await.log_err() == Some(1) {
 2905                        return anyhow::Ok(false);
 2906                    } else {
 2907                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 2908                            task.await.log_err();
 2909                        }
 2910                    }
 2911                }
 2912                if close_intent == CloseIntent::ReplaceWindow {
 2913                    _ = cx.update(|_window, cx| {
 2914                        let multi_workspace = cx
 2915                            .windows()
 2916                            .iter()
 2917                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 2918                            .next()
 2919                            .unwrap();
 2920                        let project = multi_workspace
 2921                            .read(cx)?
 2922                            .workspace()
 2923                            .read(cx)
 2924                            .project
 2925                            .clone();
 2926                        if project.read(cx).is_shared() {
 2927                            active_call.0.unshare_project(project, cx)?;
 2928                        }
 2929                        Ok::<_, anyhow::Error>(())
 2930                    });
 2931                }
 2932            }
 2933
 2934            let save_result = this
 2935                .update_in(cx, |this, window, cx| {
 2936                    this.save_all_internal(SaveIntent::Close, window, cx)
 2937                })?
 2938                .await;
 2939
 2940            // If we're not quitting, but closing, we remove the workspace from
 2941            // the current session.
 2942            if close_intent != CloseIntent::Quit
 2943                && !save_last_workspace
 2944                && save_result.as_ref().is_ok_and(|&res| res)
 2945            {
 2946                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 2947                    .await;
 2948            }
 2949
 2950            save_result
 2951        })
 2952    }
 2953
 2954    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 2955        self.save_all_internal(
 2956            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 2957            window,
 2958            cx,
 2959        )
 2960        .detach_and_log_err(cx);
 2961    }
 2962
 2963    fn send_keystrokes(
 2964        &mut self,
 2965        action: &SendKeystrokes,
 2966        window: &mut Window,
 2967        cx: &mut Context<Self>,
 2968    ) {
 2969        let keystrokes: Vec<Keystroke> = action
 2970            .0
 2971            .split(' ')
 2972            .flat_map(|k| Keystroke::parse(k).log_err())
 2973            .map(|k| {
 2974                cx.keyboard_mapper()
 2975                    .map_key_equivalent(k, false)
 2976                    .inner()
 2977                    .clone()
 2978            })
 2979            .collect();
 2980        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 2981    }
 2982
 2983    pub fn send_keystrokes_impl(
 2984        &mut self,
 2985        keystrokes: Vec<Keystroke>,
 2986        window: &mut Window,
 2987        cx: &mut Context<Self>,
 2988    ) -> Shared<Task<()>> {
 2989        let mut state = self.dispatching_keystrokes.borrow_mut();
 2990        if !state.dispatched.insert(keystrokes.clone()) {
 2991            cx.propagate();
 2992            return state.task.clone().unwrap();
 2993        }
 2994
 2995        state.queue.extend(keystrokes);
 2996
 2997        let keystrokes = self.dispatching_keystrokes.clone();
 2998        if state.task.is_none() {
 2999            state.task = Some(
 3000                window
 3001                    .spawn(cx, async move |cx| {
 3002                        // limit to 100 keystrokes to avoid infinite recursion.
 3003                        for _ in 0..100 {
 3004                            let keystroke = {
 3005                                let mut state = keystrokes.borrow_mut();
 3006                                let Some(keystroke) = state.queue.pop_front() else {
 3007                                    state.dispatched.clear();
 3008                                    state.task.take();
 3009                                    return;
 3010                                };
 3011                                keystroke
 3012                            };
 3013                            cx.update(|window, cx| {
 3014                                let focused = window.focused(cx);
 3015                                window.dispatch_keystroke(keystroke.clone(), cx);
 3016                                if window.focused(cx) != focused {
 3017                                    // dispatch_keystroke may cause the focus to change.
 3018                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3019                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 3020                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 3021                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3022                                    // )
 3023                                    window.draw(cx).clear();
 3024                                }
 3025                            })
 3026                            .ok();
 3027
 3028                            // Yield between synthetic keystrokes so deferred focus and
 3029                            // other effects can settle before dispatching the next key.
 3030                            yield_now().await;
 3031                        }
 3032
 3033                        *keystrokes.borrow_mut() = Default::default();
 3034                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3035                    })
 3036                    .shared(),
 3037            );
 3038        }
 3039        state.task.clone().unwrap()
 3040    }
 3041
 3042    fn save_all_internal(
 3043        &mut self,
 3044        mut save_intent: SaveIntent,
 3045        window: &mut Window,
 3046        cx: &mut Context<Self>,
 3047    ) -> Task<Result<bool>> {
 3048        if self.project.read(cx).is_disconnected(cx) {
 3049            return Task::ready(Ok(true));
 3050        }
 3051        let dirty_items = self
 3052            .panes
 3053            .iter()
 3054            .flat_map(|pane| {
 3055                pane.read(cx).items().filter_map(|item| {
 3056                    if item.is_dirty(cx) {
 3057                        item.tab_content_text(0, cx);
 3058                        Some((pane.downgrade(), item.boxed_clone()))
 3059                    } else {
 3060                        None
 3061                    }
 3062                })
 3063            })
 3064            .collect::<Vec<_>>();
 3065
 3066        let project = self.project.clone();
 3067        cx.spawn_in(window, async move |workspace, cx| {
 3068            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3069                let (serialize_tasks, remaining_dirty_items) =
 3070                    workspace.update_in(cx, |workspace, window, cx| {
 3071                        let mut remaining_dirty_items = Vec::new();
 3072                        let mut serialize_tasks = Vec::new();
 3073                        for (pane, item) in dirty_items {
 3074                            if let Some(task) = item
 3075                                .to_serializable_item_handle(cx)
 3076                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3077                            {
 3078                                serialize_tasks.push(task);
 3079                            } else {
 3080                                remaining_dirty_items.push((pane, item));
 3081                            }
 3082                        }
 3083                        (serialize_tasks, remaining_dirty_items)
 3084                    })?;
 3085
 3086                futures::future::try_join_all(serialize_tasks).await?;
 3087
 3088                if !remaining_dirty_items.is_empty() {
 3089                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3090                }
 3091
 3092                if remaining_dirty_items.len() > 1 {
 3093                    let answer = workspace.update_in(cx, |_, window, cx| {
 3094                        let detail = Pane::file_names_for_prompt(
 3095                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3096                            cx,
 3097                        );
 3098                        window.prompt(
 3099                            PromptLevel::Warning,
 3100                            "Do you want to save all changes in the following files?",
 3101                            Some(&detail),
 3102                            &["Save all", "Discard all", "Cancel"],
 3103                            cx,
 3104                        )
 3105                    })?;
 3106                    match answer.await.log_err() {
 3107                        Some(0) => save_intent = SaveIntent::SaveAll,
 3108                        Some(1) => save_intent = SaveIntent::Skip,
 3109                        Some(2) => return Ok(false),
 3110                        _ => {}
 3111                    }
 3112                }
 3113
 3114                remaining_dirty_items
 3115            } else {
 3116                dirty_items
 3117            };
 3118
 3119            for (pane, item) in dirty_items {
 3120                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3121                    (
 3122                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3123                        item.project_entry_ids(cx),
 3124                    )
 3125                })?;
 3126                if (singleton || !project_entry_ids.is_empty())
 3127                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3128                {
 3129                    return Ok(false);
 3130                }
 3131            }
 3132            Ok(true)
 3133        })
 3134    }
 3135
 3136    pub fn open_workspace_for_paths(
 3137        &mut self,
 3138        replace_current_window: bool,
 3139        paths: Vec<PathBuf>,
 3140        window: &mut Window,
 3141        cx: &mut Context<Self>,
 3142    ) -> Task<Result<Entity<Workspace>>> {
 3143        let window_handle = window.window_handle().downcast::<MultiWorkspace>();
 3144        let is_remote = self.project.read(cx).is_via_collab();
 3145        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3146        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3147
 3148        let window_to_replace = if replace_current_window {
 3149            window_handle
 3150        } else if is_remote || has_worktree || has_dirty_items {
 3151            None
 3152        } else {
 3153            window_handle
 3154        };
 3155        let app_state = self.app_state.clone();
 3156
 3157        cx.spawn(async move |_, cx| {
 3158            let OpenResult { workspace, .. } = cx
 3159                .update(|cx| {
 3160                    open_paths(
 3161                        &paths,
 3162                        app_state,
 3163                        OpenOptions {
 3164                            replace_window: window_to_replace,
 3165                            ..Default::default()
 3166                        },
 3167                        cx,
 3168                    )
 3169                })
 3170                .await?;
 3171            Ok(workspace)
 3172        })
 3173    }
 3174
 3175    #[allow(clippy::type_complexity)]
 3176    pub fn open_paths(
 3177        &mut self,
 3178        mut abs_paths: Vec<PathBuf>,
 3179        options: OpenOptions,
 3180        pane: Option<WeakEntity<Pane>>,
 3181        window: &mut Window,
 3182        cx: &mut Context<Self>,
 3183    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3184        let fs = self.app_state.fs.clone();
 3185
 3186        let caller_ordered_abs_paths = abs_paths.clone();
 3187
 3188        // Sort the paths to ensure we add worktrees for parents before their children.
 3189        abs_paths.sort_unstable();
 3190        cx.spawn_in(window, async move |this, cx| {
 3191            let mut tasks = Vec::with_capacity(abs_paths.len());
 3192
 3193            for abs_path in &abs_paths {
 3194                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3195                    OpenVisible::All => Some(true),
 3196                    OpenVisible::None => Some(false),
 3197                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3198                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3199                        Some(None) => Some(true),
 3200                        None => None,
 3201                    },
 3202                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3203                        Some(Some(metadata)) => Some(metadata.is_dir),
 3204                        Some(None) => Some(false),
 3205                        None => None,
 3206                    },
 3207                };
 3208                let project_path = match visible {
 3209                    Some(visible) => match this
 3210                        .update(cx, |this, cx| {
 3211                            Workspace::project_path_for_path(
 3212                                this.project.clone(),
 3213                                abs_path,
 3214                                visible,
 3215                                cx,
 3216                            )
 3217                        })
 3218                        .log_err()
 3219                    {
 3220                        Some(project_path) => project_path.await.log_err(),
 3221                        None => None,
 3222                    },
 3223                    None => None,
 3224                };
 3225
 3226                let this = this.clone();
 3227                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3228                let fs = fs.clone();
 3229                let pane = pane.clone();
 3230                let task = cx.spawn(async move |cx| {
 3231                    let (_worktree, project_path) = project_path?;
 3232                    if fs.is_dir(&abs_path).await {
 3233                        // Opening a directory should not race to update the active entry.
 3234                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3235                        None
 3236                    } else {
 3237                        Some(
 3238                            this.update_in(cx, |this, window, cx| {
 3239                                this.open_path(
 3240                                    project_path,
 3241                                    pane,
 3242                                    options.focus.unwrap_or(true),
 3243                                    window,
 3244                                    cx,
 3245                                )
 3246                            })
 3247                            .ok()?
 3248                            .await,
 3249                        )
 3250                    }
 3251                });
 3252                tasks.push(task);
 3253            }
 3254
 3255            let results = futures::future::join_all(tasks).await;
 3256
 3257            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3258            let mut winner: Option<(PathBuf, bool)> = None;
 3259            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3260                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3261                    if !metadata.is_dir {
 3262                        winner = Some((abs_path, false));
 3263                        break;
 3264                    }
 3265                    if winner.is_none() {
 3266                        winner = Some((abs_path, true));
 3267                    }
 3268                } else if winner.is_none() {
 3269                    winner = Some((abs_path, false));
 3270                }
 3271            }
 3272
 3273            // Compute the winner entry id on the foreground thread and emit once, after all
 3274            // paths finish opening. This avoids races between concurrently-opening paths
 3275            // (directories in particular) and makes the resulting project panel selection
 3276            // deterministic.
 3277            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3278                'emit_winner: {
 3279                    let winner_abs_path: Arc<Path> =
 3280                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3281
 3282                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3283                        OpenVisible::All => true,
 3284                        OpenVisible::None => false,
 3285                        OpenVisible::OnlyFiles => !winner_is_dir,
 3286                        OpenVisible::OnlyDirectories => winner_is_dir,
 3287                    };
 3288
 3289                    let Some(worktree_task) = this
 3290                        .update(cx, |workspace, cx| {
 3291                            workspace.project.update(cx, |project, cx| {
 3292                                project.find_or_create_worktree(
 3293                                    winner_abs_path.as_ref(),
 3294                                    visible,
 3295                                    cx,
 3296                                )
 3297                            })
 3298                        })
 3299                        .ok()
 3300                    else {
 3301                        break 'emit_winner;
 3302                    };
 3303
 3304                    let Ok((worktree, _)) = worktree_task.await else {
 3305                        break 'emit_winner;
 3306                    };
 3307
 3308                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3309                        let worktree = worktree.read(cx);
 3310                        let worktree_abs_path = worktree.abs_path();
 3311                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3312                            worktree.root_entry()
 3313                        } else {
 3314                            winner_abs_path
 3315                                .strip_prefix(worktree_abs_path.as_ref())
 3316                                .ok()
 3317                                .and_then(|relative_path| {
 3318                                    let relative_path =
 3319                                        RelPath::new(relative_path, PathStyle::local())
 3320                                            .log_err()?;
 3321                                    worktree.entry_for_path(&relative_path)
 3322                                })
 3323                        }?;
 3324                        Some(entry.id)
 3325                    }) else {
 3326                        break 'emit_winner;
 3327                    };
 3328
 3329                    this.update(cx, |workspace, cx| {
 3330                        workspace.project.update(cx, |_, cx| {
 3331                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3332                        });
 3333                    })
 3334                    .ok();
 3335                }
 3336            }
 3337
 3338            results
 3339        })
 3340    }
 3341
 3342    pub fn open_resolved_path(
 3343        &mut self,
 3344        path: ResolvedPath,
 3345        window: &mut Window,
 3346        cx: &mut Context<Self>,
 3347    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3348        match path {
 3349            ResolvedPath::ProjectPath { project_path, .. } => {
 3350                self.open_path(project_path, None, true, window, cx)
 3351            }
 3352            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3353                PathBuf::from(path),
 3354                OpenOptions {
 3355                    visible: Some(OpenVisible::None),
 3356                    ..Default::default()
 3357                },
 3358                window,
 3359                cx,
 3360            ),
 3361        }
 3362    }
 3363
 3364    pub fn absolute_path_of_worktree(
 3365        &self,
 3366        worktree_id: WorktreeId,
 3367        cx: &mut Context<Self>,
 3368    ) -> Option<PathBuf> {
 3369        self.project
 3370            .read(cx)
 3371            .worktree_for_id(worktree_id, cx)
 3372            // TODO: use `abs_path` or `root_dir`
 3373            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3374    }
 3375
 3376    pub fn add_folder_to_project(
 3377        &mut self,
 3378        _: &AddFolderToProject,
 3379        window: &mut Window,
 3380        cx: &mut Context<Self>,
 3381    ) {
 3382        let project = self.project.read(cx);
 3383        if project.is_via_collab() {
 3384            self.show_error(
 3385                &anyhow!("You cannot add folders to someone else's project"),
 3386                cx,
 3387            );
 3388            return;
 3389        }
 3390        let paths = self.prompt_for_open_path(
 3391            PathPromptOptions {
 3392                files: false,
 3393                directories: true,
 3394                multiple: true,
 3395                prompt: None,
 3396            },
 3397            DirectoryLister::Project(self.project.clone()),
 3398            window,
 3399            cx,
 3400        );
 3401        cx.spawn_in(window, async move |this, cx| {
 3402            if let Some(paths) = paths.await.log_err().flatten() {
 3403                let results = this
 3404                    .update_in(cx, |this, window, cx| {
 3405                        this.open_paths(
 3406                            paths,
 3407                            OpenOptions {
 3408                                visible: Some(OpenVisible::All),
 3409                                ..Default::default()
 3410                            },
 3411                            None,
 3412                            window,
 3413                            cx,
 3414                        )
 3415                    })?
 3416                    .await;
 3417                for result in results.into_iter().flatten() {
 3418                    result.log_err();
 3419                }
 3420            }
 3421            anyhow::Ok(())
 3422        })
 3423        .detach_and_log_err(cx);
 3424    }
 3425
 3426    pub fn project_path_for_path(
 3427        project: Entity<Project>,
 3428        abs_path: &Path,
 3429        visible: bool,
 3430        cx: &mut App,
 3431    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3432        let entry = project.update(cx, |project, cx| {
 3433            project.find_or_create_worktree(abs_path, visible, cx)
 3434        });
 3435        cx.spawn(async move |cx| {
 3436            let (worktree, path) = entry.await?;
 3437            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3438            Ok((worktree, ProjectPath { worktree_id, path }))
 3439        })
 3440    }
 3441
 3442    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3443        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3444    }
 3445
 3446    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3447        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3448    }
 3449
 3450    pub fn items_of_type<'a, T: Item>(
 3451        &'a self,
 3452        cx: &'a App,
 3453    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3454        self.panes
 3455            .iter()
 3456            .flat_map(|pane| pane.read(cx).items_of_type())
 3457    }
 3458
 3459    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3460        self.active_pane().read(cx).active_item()
 3461    }
 3462
 3463    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3464        let item = self.active_item(cx)?;
 3465        item.to_any_view().downcast::<I>().ok()
 3466    }
 3467
 3468    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3469        self.active_item(cx).and_then(|item| item.project_path(cx))
 3470    }
 3471
 3472    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3473        self.recent_navigation_history_iter(cx)
 3474            .filter_map(|(path, abs_path)| {
 3475                let worktree = self
 3476                    .project
 3477                    .read(cx)
 3478                    .worktree_for_id(path.worktree_id, cx)?;
 3479                if worktree.read(cx).is_visible() {
 3480                    abs_path
 3481                } else {
 3482                    None
 3483                }
 3484            })
 3485            .next()
 3486    }
 3487
 3488    pub fn save_active_item(
 3489        &mut self,
 3490        save_intent: SaveIntent,
 3491        window: &mut Window,
 3492        cx: &mut App,
 3493    ) -> Task<Result<()>> {
 3494        let project = self.project.clone();
 3495        let pane = self.active_pane();
 3496        let item = pane.read(cx).active_item();
 3497        let pane = pane.downgrade();
 3498
 3499        window.spawn(cx, async move |cx| {
 3500            if let Some(item) = item {
 3501                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3502                    .await
 3503                    .map(|_| ())
 3504            } else {
 3505                Ok(())
 3506            }
 3507        })
 3508    }
 3509
 3510    pub fn close_inactive_items_and_panes(
 3511        &mut self,
 3512        action: &CloseInactiveTabsAndPanes,
 3513        window: &mut Window,
 3514        cx: &mut Context<Self>,
 3515    ) {
 3516        if let Some(task) = self.close_all_internal(
 3517            true,
 3518            action.save_intent.unwrap_or(SaveIntent::Close),
 3519            window,
 3520            cx,
 3521        ) {
 3522            task.detach_and_log_err(cx)
 3523        }
 3524    }
 3525
 3526    pub fn close_all_items_and_panes(
 3527        &mut self,
 3528        action: &CloseAllItemsAndPanes,
 3529        window: &mut Window,
 3530        cx: &mut Context<Self>,
 3531    ) {
 3532        if let Some(task) = self.close_all_internal(
 3533            false,
 3534            action.save_intent.unwrap_or(SaveIntent::Close),
 3535            window,
 3536            cx,
 3537        ) {
 3538            task.detach_and_log_err(cx)
 3539        }
 3540    }
 3541
 3542    /// Closes the active item across all panes.
 3543    pub fn close_item_in_all_panes(
 3544        &mut self,
 3545        action: &CloseItemInAllPanes,
 3546        window: &mut Window,
 3547        cx: &mut Context<Self>,
 3548    ) {
 3549        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3550            return;
 3551        };
 3552
 3553        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3554        let close_pinned = action.close_pinned;
 3555
 3556        if let Some(project_path) = active_item.project_path(cx) {
 3557            self.close_items_with_project_path(
 3558                &project_path,
 3559                save_intent,
 3560                close_pinned,
 3561                window,
 3562                cx,
 3563            );
 3564        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3565            let item_id = active_item.item_id();
 3566            self.active_pane().update(cx, |pane, cx| {
 3567                pane.close_item_by_id(item_id, save_intent, window, cx)
 3568                    .detach_and_log_err(cx);
 3569            });
 3570        }
 3571    }
 3572
 3573    /// Closes all items with the given project path across all panes.
 3574    pub fn close_items_with_project_path(
 3575        &mut self,
 3576        project_path: &ProjectPath,
 3577        save_intent: SaveIntent,
 3578        close_pinned: bool,
 3579        window: &mut Window,
 3580        cx: &mut Context<Self>,
 3581    ) {
 3582        let panes = self.panes().to_vec();
 3583        for pane in panes {
 3584            pane.update(cx, |pane, cx| {
 3585                pane.close_items_for_project_path(
 3586                    project_path,
 3587                    save_intent,
 3588                    close_pinned,
 3589                    window,
 3590                    cx,
 3591                )
 3592                .detach_and_log_err(cx);
 3593            });
 3594        }
 3595    }
 3596
 3597    fn close_all_internal(
 3598        &mut self,
 3599        retain_active_pane: bool,
 3600        save_intent: SaveIntent,
 3601        window: &mut Window,
 3602        cx: &mut Context<Self>,
 3603    ) -> Option<Task<Result<()>>> {
 3604        let current_pane = self.active_pane();
 3605
 3606        let mut tasks = Vec::new();
 3607
 3608        if retain_active_pane {
 3609            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3610                pane.close_other_items(
 3611                    &CloseOtherItems {
 3612                        save_intent: None,
 3613                        close_pinned: false,
 3614                    },
 3615                    None,
 3616                    window,
 3617                    cx,
 3618                )
 3619            });
 3620
 3621            tasks.push(current_pane_close);
 3622        }
 3623
 3624        for pane in self.panes() {
 3625            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3626                continue;
 3627            }
 3628
 3629            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3630                pane.close_all_items(
 3631                    &CloseAllItems {
 3632                        save_intent: Some(save_intent),
 3633                        close_pinned: false,
 3634                    },
 3635                    window,
 3636                    cx,
 3637                )
 3638            });
 3639
 3640            tasks.push(close_pane_items)
 3641        }
 3642
 3643        if tasks.is_empty() {
 3644            None
 3645        } else {
 3646            Some(cx.spawn_in(window, async move |_, _| {
 3647                for task in tasks {
 3648                    task.await?
 3649                }
 3650                Ok(())
 3651            }))
 3652        }
 3653    }
 3654
 3655    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3656        self.dock_at_position(position).read(cx).is_open()
 3657    }
 3658
 3659    pub fn toggle_dock(
 3660        &mut self,
 3661        dock_side: DockPosition,
 3662        window: &mut Window,
 3663        cx: &mut Context<Self>,
 3664    ) {
 3665        let mut focus_center = false;
 3666        let mut reveal_dock = false;
 3667
 3668        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3669        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3670
 3671        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3672            telemetry::event!(
 3673                "Panel Button Clicked",
 3674                name = panel.persistent_name(),
 3675                toggle_state = !was_visible
 3676            );
 3677        }
 3678        if was_visible {
 3679            self.save_open_dock_positions(cx);
 3680        }
 3681
 3682        let dock = self.dock_at_position(dock_side);
 3683        dock.update(cx, |dock, cx| {
 3684            dock.set_open(!was_visible, window, cx);
 3685
 3686            if dock.active_panel().is_none() {
 3687                let Some(panel_ix) = dock
 3688                    .first_enabled_panel_idx(cx)
 3689                    .log_with_level(log::Level::Info)
 3690                else {
 3691                    return;
 3692                };
 3693                dock.activate_panel(panel_ix, window, cx);
 3694            }
 3695
 3696            if let Some(active_panel) = dock.active_panel() {
 3697                if was_visible {
 3698                    if active_panel
 3699                        .panel_focus_handle(cx)
 3700                        .contains_focused(window, cx)
 3701                    {
 3702                        focus_center = true;
 3703                    }
 3704                } else {
 3705                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3706                    window.focus(focus_handle, cx);
 3707                    reveal_dock = true;
 3708                }
 3709            }
 3710        });
 3711
 3712        if reveal_dock {
 3713            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3714        }
 3715
 3716        if focus_center {
 3717            self.active_pane
 3718                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3719        }
 3720
 3721        cx.notify();
 3722        self.serialize_workspace(window, cx);
 3723    }
 3724
 3725    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3726        self.all_docks().into_iter().find(|&dock| {
 3727            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3728        })
 3729    }
 3730
 3731    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3732        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3733            self.save_open_dock_positions(cx);
 3734            dock.update(cx, |dock, cx| {
 3735                dock.set_open(false, window, cx);
 3736            });
 3737            return true;
 3738        }
 3739        false
 3740    }
 3741
 3742    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3743        self.save_open_dock_positions(cx);
 3744        for dock in self.all_docks() {
 3745            dock.update(cx, |dock, cx| {
 3746                dock.set_open(false, window, cx);
 3747            });
 3748        }
 3749
 3750        cx.focus_self(window);
 3751        cx.notify();
 3752        self.serialize_workspace(window, cx);
 3753    }
 3754
 3755    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 3756        self.all_docks()
 3757            .into_iter()
 3758            .filter_map(|dock| {
 3759                let dock_ref = dock.read(cx);
 3760                if dock_ref.is_open() {
 3761                    Some(dock_ref.position())
 3762                } else {
 3763                    None
 3764                }
 3765            })
 3766            .collect()
 3767    }
 3768
 3769    /// Saves the positions of currently open docks.
 3770    ///
 3771    /// Updates `last_open_dock_positions` with positions of all currently open
 3772    /// docks, to later be restored by the 'Toggle All Docks' action.
 3773    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 3774        let open_dock_positions = self.get_open_dock_positions(cx);
 3775        if !open_dock_positions.is_empty() {
 3776            self.last_open_dock_positions = open_dock_positions;
 3777        }
 3778    }
 3779
 3780    /// Toggles all docks between open and closed states.
 3781    ///
 3782    /// If any docks are open, closes all and remembers their positions. If all
 3783    /// docks are closed, restores the last remembered dock configuration.
 3784    fn toggle_all_docks(
 3785        &mut self,
 3786        _: &ToggleAllDocks,
 3787        window: &mut Window,
 3788        cx: &mut Context<Self>,
 3789    ) {
 3790        let open_dock_positions = self.get_open_dock_positions(cx);
 3791
 3792        if !open_dock_positions.is_empty() {
 3793            self.close_all_docks(window, cx);
 3794        } else if !self.last_open_dock_positions.is_empty() {
 3795            self.restore_last_open_docks(window, cx);
 3796        }
 3797    }
 3798
 3799    /// Reopens docks from the most recently remembered configuration.
 3800    ///
 3801    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 3802    /// and clears the stored positions.
 3803    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3804        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 3805
 3806        for position in positions_to_open {
 3807            let dock = self.dock_at_position(position);
 3808            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 3809        }
 3810
 3811        cx.focus_self(window);
 3812        cx.notify();
 3813        self.serialize_workspace(window, cx);
 3814    }
 3815
 3816    /// Transfer focus to the panel of the given type.
 3817    pub fn focus_panel<T: Panel>(
 3818        &mut self,
 3819        window: &mut Window,
 3820        cx: &mut Context<Self>,
 3821    ) -> Option<Entity<T>> {
 3822        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 3823        panel.to_any().downcast().ok()
 3824    }
 3825
 3826    /// Focus the panel of the given type if it isn't already focused. If it is
 3827    /// already focused, then transfer focus back to the workspace center.
 3828    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 3829    /// panel when transferring focus back to the center.
 3830    pub fn toggle_panel_focus<T: Panel>(
 3831        &mut self,
 3832        window: &mut Window,
 3833        cx: &mut Context<Self>,
 3834    ) -> bool {
 3835        let mut did_focus_panel = false;
 3836        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 3837            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 3838            did_focus_panel
 3839        });
 3840
 3841        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 3842            self.close_panel::<T>(window, cx);
 3843        }
 3844
 3845        telemetry::event!(
 3846            "Panel Button Clicked",
 3847            name = T::persistent_name(),
 3848            toggle_state = did_focus_panel
 3849        );
 3850
 3851        did_focus_panel
 3852    }
 3853
 3854    pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3855        if let Some(item) = self.active_item(cx) {
 3856            item.item_focus_handle(cx).focus(window, cx);
 3857        } else {
 3858            log::error!("Could not find a focus target when switching focus to the center panes",);
 3859        }
 3860    }
 3861
 3862    pub fn activate_panel_for_proto_id(
 3863        &mut self,
 3864        panel_id: PanelId,
 3865        window: &mut Window,
 3866        cx: &mut Context<Self>,
 3867    ) -> Option<Arc<dyn PanelHandle>> {
 3868        let mut panel = None;
 3869        for dock in self.all_docks() {
 3870            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 3871                panel = dock.update(cx, |dock, cx| {
 3872                    dock.activate_panel(panel_index, window, cx);
 3873                    dock.set_open(true, window, cx);
 3874                    dock.active_panel().cloned()
 3875                });
 3876                break;
 3877            }
 3878        }
 3879
 3880        if panel.is_some() {
 3881            cx.notify();
 3882            self.serialize_workspace(window, cx);
 3883        }
 3884
 3885        panel
 3886    }
 3887
 3888    /// Focus or unfocus the given panel type, depending on the given callback.
 3889    fn focus_or_unfocus_panel<T: Panel>(
 3890        &mut self,
 3891        window: &mut Window,
 3892        cx: &mut Context<Self>,
 3893        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 3894    ) -> Option<Arc<dyn PanelHandle>> {
 3895        let mut result_panel = None;
 3896        let mut serialize = false;
 3897        for dock in self.all_docks() {
 3898            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3899                let mut focus_center = false;
 3900                let panel = dock.update(cx, |dock, cx| {
 3901                    dock.activate_panel(panel_index, window, cx);
 3902
 3903                    let panel = dock.active_panel().cloned();
 3904                    if let Some(panel) = panel.as_ref() {
 3905                        if should_focus(&**panel, window, cx) {
 3906                            dock.set_open(true, window, cx);
 3907                            panel.panel_focus_handle(cx).focus(window, cx);
 3908                        } else {
 3909                            focus_center = true;
 3910                        }
 3911                    }
 3912                    panel
 3913                });
 3914
 3915                if focus_center {
 3916                    self.active_pane
 3917                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3918                }
 3919
 3920                result_panel = panel;
 3921                serialize = true;
 3922                break;
 3923            }
 3924        }
 3925
 3926        if serialize {
 3927            self.serialize_workspace(window, cx);
 3928        }
 3929
 3930        cx.notify();
 3931        result_panel
 3932    }
 3933
 3934    /// Open the panel of the given type
 3935    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3936        for dock in self.all_docks() {
 3937            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3938                dock.update(cx, |dock, cx| {
 3939                    dock.activate_panel(panel_index, window, cx);
 3940                    dock.set_open(true, window, cx);
 3941                });
 3942            }
 3943        }
 3944    }
 3945
 3946    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 3947        for dock in self.all_docks().iter() {
 3948            dock.update(cx, |dock, cx| {
 3949                if dock.panel::<T>().is_some() {
 3950                    dock.set_open(false, window, cx)
 3951                }
 3952            })
 3953        }
 3954    }
 3955
 3956    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 3957        self.all_docks()
 3958            .iter()
 3959            .find_map(|dock| dock.read(cx).panel::<T>())
 3960    }
 3961
 3962    fn dismiss_zoomed_items_to_reveal(
 3963        &mut self,
 3964        dock_to_reveal: Option<DockPosition>,
 3965        window: &mut Window,
 3966        cx: &mut Context<Self>,
 3967    ) {
 3968        // If a center pane is zoomed, unzoom it.
 3969        for pane in &self.panes {
 3970            if pane != &self.active_pane || dock_to_reveal.is_some() {
 3971                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 3972            }
 3973        }
 3974
 3975        // If another dock is zoomed, hide it.
 3976        let mut focus_center = false;
 3977        for dock in self.all_docks() {
 3978            dock.update(cx, |dock, cx| {
 3979                if Some(dock.position()) != dock_to_reveal
 3980                    && let Some(panel) = dock.active_panel()
 3981                    && panel.is_zoomed(window, cx)
 3982                {
 3983                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 3984                    dock.set_open(false, window, cx);
 3985                }
 3986            });
 3987        }
 3988
 3989        if focus_center {
 3990            self.active_pane
 3991                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3992        }
 3993
 3994        if self.zoomed_position != dock_to_reveal {
 3995            self.zoomed = None;
 3996            self.zoomed_position = None;
 3997            cx.emit(Event::ZoomChanged);
 3998        }
 3999
 4000        cx.notify();
 4001    }
 4002
 4003    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4004        let pane = cx.new(|cx| {
 4005            let mut pane = Pane::new(
 4006                self.weak_handle(),
 4007                self.project.clone(),
 4008                self.pane_history_timestamp.clone(),
 4009                None,
 4010                NewFile.boxed_clone(),
 4011                true,
 4012                window,
 4013                cx,
 4014            );
 4015            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4016            pane
 4017        });
 4018        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4019            .detach();
 4020        self.panes.push(pane.clone());
 4021
 4022        window.focus(&pane.focus_handle(cx), cx);
 4023
 4024        cx.emit(Event::PaneAdded(pane.clone()));
 4025        pane
 4026    }
 4027
 4028    pub fn add_item_to_center(
 4029        &mut self,
 4030        item: Box<dyn ItemHandle>,
 4031        window: &mut Window,
 4032        cx: &mut Context<Self>,
 4033    ) -> bool {
 4034        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4035            if let Some(center_pane) = center_pane.upgrade() {
 4036                center_pane.update(cx, |pane, cx| {
 4037                    pane.add_item(item, true, true, None, window, cx)
 4038                });
 4039                true
 4040            } else {
 4041                false
 4042            }
 4043        } else {
 4044            false
 4045        }
 4046    }
 4047
 4048    pub fn add_item_to_active_pane(
 4049        &mut self,
 4050        item: Box<dyn ItemHandle>,
 4051        destination_index: Option<usize>,
 4052        focus_item: bool,
 4053        window: &mut Window,
 4054        cx: &mut App,
 4055    ) {
 4056        self.add_item(
 4057            self.active_pane.clone(),
 4058            item,
 4059            destination_index,
 4060            false,
 4061            focus_item,
 4062            window,
 4063            cx,
 4064        )
 4065    }
 4066
 4067    pub fn add_item(
 4068        &mut self,
 4069        pane: Entity<Pane>,
 4070        item: Box<dyn ItemHandle>,
 4071        destination_index: Option<usize>,
 4072        activate_pane: bool,
 4073        focus_item: bool,
 4074        window: &mut Window,
 4075        cx: &mut App,
 4076    ) {
 4077        pane.update(cx, |pane, cx| {
 4078            pane.add_item(
 4079                item,
 4080                activate_pane,
 4081                focus_item,
 4082                destination_index,
 4083                window,
 4084                cx,
 4085            )
 4086        });
 4087    }
 4088
 4089    pub fn split_item(
 4090        &mut self,
 4091        split_direction: SplitDirection,
 4092        item: Box<dyn ItemHandle>,
 4093        window: &mut Window,
 4094        cx: &mut Context<Self>,
 4095    ) {
 4096        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4097        self.add_item(new_pane, item, None, true, true, window, cx);
 4098    }
 4099
 4100    pub fn open_abs_path(
 4101        &mut self,
 4102        abs_path: PathBuf,
 4103        options: OpenOptions,
 4104        window: &mut Window,
 4105        cx: &mut Context<Self>,
 4106    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4107        cx.spawn_in(window, async move |workspace, cx| {
 4108            let open_paths_task_result = workspace
 4109                .update_in(cx, |workspace, window, cx| {
 4110                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4111                })
 4112                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4113                .await;
 4114            anyhow::ensure!(
 4115                open_paths_task_result.len() == 1,
 4116                "open abs path {abs_path:?} task returned incorrect number of results"
 4117            );
 4118            match open_paths_task_result
 4119                .into_iter()
 4120                .next()
 4121                .expect("ensured single task result")
 4122            {
 4123                Some(open_result) => {
 4124                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4125                }
 4126                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4127            }
 4128        })
 4129    }
 4130
 4131    pub fn split_abs_path(
 4132        &mut self,
 4133        abs_path: PathBuf,
 4134        visible: bool,
 4135        window: &mut Window,
 4136        cx: &mut Context<Self>,
 4137    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4138        let project_path_task =
 4139            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4140        cx.spawn_in(window, async move |this, cx| {
 4141            let (_, path) = project_path_task.await?;
 4142            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4143                .await
 4144        })
 4145    }
 4146
 4147    pub fn open_path(
 4148        &mut self,
 4149        path: impl Into<ProjectPath>,
 4150        pane: Option<WeakEntity<Pane>>,
 4151        focus_item: bool,
 4152        window: &mut Window,
 4153        cx: &mut App,
 4154    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4155        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4156    }
 4157
 4158    pub fn open_path_preview(
 4159        &mut self,
 4160        path: impl Into<ProjectPath>,
 4161        pane: Option<WeakEntity<Pane>>,
 4162        focus_item: bool,
 4163        allow_preview: bool,
 4164        activate: bool,
 4165        window: &mut Window,
 4166        cx: &mut App,
 4167    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4168        let pane = pane.unwrap_or_else(|| {
 4169            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4170                self.panes
 4171                    .first()
 4172                    .expect("There must be an active pane")
 4173                    .downgrade()
 4174            })
 4175        });
 4176
 4177        let project_path = path.into();
 4178        let task = self.load_path(project_path.clone(), window, cx);
 4179        window.spawn(cx, async move |cx| {
 4180            let (project_entry_id, build_item) = task.await?;
 4181
 4182            pane.update_in(cx, |pane, window, cx| {
 4183                pane.open_item(
 4184                    project_entry_id,
 4185                    project_path,
 4186                    focus_item,
 4187                    allow_preview,
 4188                    activate,
 4189                    None,
 4190                    window,
 4191                    cx,
 4192                    build_item,
 4193                )
 4194            })
 4195        })
 4196    }
 4197
 4198    pub fn split_path(
 4199        &mut self,
 4200        path: impl Into<ProjectPath>,
 4201        window: &mut Window,
 4202        cx: &mut Context<Self>,
 4203    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4204        self.split_path_preview(path, false, None, window, cx)
 4205    }
 4206
 4207    pub fn split_path_preview(
 4208        &mut self,
 4209        path: impl Into<ProjectPath>,
 4210        allow_preview: bool,
 4211        split_direction: Option<SplitDirection>,
 4212        window: &mut Window,
 4213        cx: &mut Context<Self>,
 4214    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4215        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4216            self.panes
 4217                .first()
 4218                .expect("There must be an active pane")
 4219                .downgrade()
 4220        });
 4221
 4222        if let Member::Pane(center_pane) = &self.center.root
 4223            && center_pane.read(cx).items_len() == 0
 4224        {
 4225            return self.open_path(path, Some(pane), true, window, cx);
 4226        }
 4227
 4228        let project_path = path.into();
 4229        let task = self.load_path(project_path.clone(), window, cx);
 4230        cx.spawn_in(window, async move |this, cx| {
 4231            let (project_entry_id, build_item) = task.await?;
 4232            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4233                let pane = pane.upgrade()?;
 4234                let new_pane = this.split_pane(
 4235                    pane,
 4236                    split_direction.unwrap_or(SplitDirection::Right),
 4237                    window,
 4238                    cx,
 4239                );
 4240                new_pane.update(cx, |new_pane, cx| {
 4241                    Some(new_pane.open_item(
 4242                        project_entry_id,
 4243                        project_path,
 4244                        true,
 4245                        allow_preview,
 4246                        true,
 4247                        None,
 4248                        window,
 4249                        cx,
 4250                        build_item,
 4251                    ))
 4252                })
 4253            })
 4254            .map(|option| option.context("pane was dropped"))?
 4255        })
 4256    }
 4257
 4258    fn load_path(
 4259        &mut self,
 4260        path: ProjectPath,
 4261        window: &mut Window,
 4262        cx: &mut App,
 4263    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4264        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4265        registry.open_path(self.project(), &path, window, cx)
 4266    }
 4267
 4268    pub fn find_project_item<T>(
 4269        &self,
 4270        pane: &Entity<Pane>,
 4271        project_item: &Entity<T::Item>,
 4272        cx: &App,
 4273    ) -> Option<Entity<T>>
 4274    where
 4275        T: ProjectItem,
 4276    {
 4277        use project::ProjectItem as _;
 4278        let project_item = project_item.read(cx);
 4279        let entry_id = project_item.entry_id(cx);
 4280        let project_path = project_item.project_path(cx);
 4281
 4282        let mut item = None;
 4283        if let Some(entry_id) = entry_id {
 4284            item = pane.read(cx).item_for_entry(entry_id, cx);
 4285        }
 4286        if item.is_none()
 4287            && let Some(project_path) = project_path
 4288        {
 4289            item = pane.read(cx).item_for_path(project_path, cx);
 4290        }
 4291
 4292        item.and_then(|item| item.downcast::<T>())
 4293    }
 4294
 4295    pub fn is_project_item_open<T>(
 4296        &self,
 4297        pane: &Entity<Pane>,
 4298        project_item: &Entity<T::Item>,
 4299        cx: &App,
 4300    ) -> bool
 4301    where
 4302        T: ProjectItem,
 4303    {
 4304        self.find_project_item::<T>(pane, project_item, cx)
 4305            .is_some()
 4306    }
 4307
 4308    pub fn open_project_item<T>(
 4309        &mut self,
 4310        pane: Entity<Pane>,
 4311        project_item: Entity<T::Item>,
 4312        activate_pane: bool,
 4313        focus_item: bool,
 4314        keep_old_preview: bool,
 4315        allow_new_preview: bool,
 4316        window: &mut Window,
 4317        cx: &mut Context<Self>,
 4318    ) -> Entity<T>
 4319    where
 4320        T: ProjectItem,
 4321    {
 4322        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4323
 4324        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4325            if !keep_old_preview
 4326                && let Some(old_id) = old_item_id
 4327                && old_id != item.item_id()
 4328            {
 4329                // switching to a different item, so unpreview old active item
 4330                pane.update(cx, |pane, _| {
 4331                    pane.unpreview_item_if_preview(old_id);
 4332                });
 4333            }
 4334
 4335            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4336            if !allow_new_preview {
 4337                pane.update(cx, |pane, _| {
 4338                    pane.unpreview_item_if_preview(item.item_id());
 4339                });
 4340            }
 4341            return item;
 4342        }
 4343
 4344        let item = pane.update(cx, |pane, cx| {
 4345            cx.new(|cx| {
 4346                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4347            })
 4348        });
 4349        let mut destination_index = None;
 4350        pane.update(cx, |pane, cx| {
 4351            if !keep_old_preview && let Some(old_id) = old_item_id {
 4352                pane.unpreview_item_if_preview(old_id);
 4353            }
 4354            if allow_new_preview {
 4355                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4356            }
 4357        });
 4358
 4359        self.add_item(
 4360            pane,
 4361            Box::new(item.clone()),
 4362            destination_index,
 4363            activate_pane,
 4364            focus_item,
 4365            window,
 4366            cx,
 4367        );
 4368        item
 4369    }
 4370
 4371    pub fn open_shared_screen(
 4372        &mut self,
 4373        peer_id: PeerId,
 4374        window: &mut Window,
 4375        cx: &mut Context<Self>,
 4376    ) {
 4377        if let Some(shared_screen) =
 4378            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4379        {
 4380            self.active_pane.update(cx, |pane, cx| {
 4381                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4382            });
 4383        }
 4384    }
 4385
 4386    pub fn activate_item(
 4387        &mut self,
 4388        item: &dyn ItemHandle,
 4389        activate_pane: bool,
 4390        focus_item: bool,
 4391        window: &mut Window,
 4392        cx: &mut App,
 4393    ) -> bool {
 4394        let result = self.panes.iter().find_map(|pane| {
 4395            pane.read(cx)
 4396                .index_for_item(item)
 4397                .map(|ix| (pane.clone(), ix))
 4398        });
 4399        if let Some((pane, ix)) = result {
 4400            pane.update(cx, |pane, cx| {
 4401                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4402            });
 4403            true
 4404        } else {
 4405            false
 4406        }
 4407    }
 4408
 4409    fn activate_pane_at_index(
 4410        &mut self,
 4411        action: &ActivatePane,
 4412        window: &mut Window,
 4413        cx: &mut Context<Self>,
 4414    ) {
 4415        let panes = self.center.panes();
 4416        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4417            window.focus(&pane.focus_handle(cx), cx);
 4418        } else {
 4419            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4420                .detach();
 4421        }
 4422    }
 4423
 4424    fn move_item_to_pane_at_index(
 4425        &mut self,
 4426        action: &MoveItemToPane,
 4427        window: &mut Window,
 4428        cx: &mut Context<Self>,
 4429    ) {
 4430        let panes = self.center.panes();
 4431        let destination = match panes.get(action.destination) {
 4432            Some(&destination) => destination.clone(),
 4433            None => {
 4434                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4435                    return;
 4436                }
 4437                let direction = SplitDirection::Right;
 4438                let split_off_pane = self
 4439                    .find_pane_in_direction(direction, cx)
 4440                    .unwrap_or_else(|| self.active_pane.clone());
 4441                let new_pane = self.add_pane(window, cx);
 4442                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4443                new_pane
 4444            }
 4445        };
 4446
 4447        if action.clone {
 4448            if self
 4449                .active_pane
 4450                .read(cx)
 4451                .active_item()
 4452                .is_some_and(|item| item.can_split(cx))
 4453            {
 4454                clone_active_item(
 4455                    self.database_id(),
 4456                    &self.active_pane,
 4457                    &destination,
 4458                    action.focus,
 4459                    window,
 4460                    cx,
 4461                );
 4462                return;
 4463            }
 4464        }
 4465        move_active_item(
 4466            &self.active_pane,
 4467            &destination,
 4468            action.focus,
 4469            true,
 4470            window,
 4471            cx,
 4472        )
 4473    }
 4474
 4475    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4476        let panes = self.center.panes();
 4477        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4478            let next_ix = (ix + 1) % panes.len();
 4479            let next_pane = panes[next_ix].clone();
 4480            window.focus(&next_pane.focus_handle(cx), cx);
 4481        }
 4482    }
 4483
 4484    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4485        let panes = self.center.panes();
 4486        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4487            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4488            let prev_pane = panes[prev_ix].clone();
 4489            window.focus(&prev_pane.focus_handle(cx), cx);
 4490        }
 4491    }
 4492
 4493    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4494        let last_pane = self.center.last_pane();
 4495        window.focus(&last_pane.focus_handle(cx), cx);
 4496    }
 4497
 4498    pub fn activate_pane_in_direction(
 4499        &mut self,
 4500        direction: SplitDirection,
 4501        window: &mut Window,
 4502        cx: &mut App,
 4503    ) {
 4504        use ActivateInDirectionTarget as Target;
 4505        enum Origin {
 4506            Sidebar,
 4507            LeftDock,
 4508            RightDock,
 4509            BottomDock,
 4510            Center,
 4511        }
 4512
 4513        let origin: Origin = if self
 4514            .sidebar_focus_handle
 4515            .as_ref()
 4516            .is_some_and(|h| h.contains_focused(window, cx))
 4517        {
 4518            Origin::Sidebar
 4519        } else {
 4520            [
 4521                (&self.left_dock, Origin::LeftDock),
 4522                (&self.right_dock, Origin::RightDock),
 4523                (&self.bottom_dock, Origin::BottomDock),
 4524            ]
 4525            .into_iter()
 4526            .find_map(|(dock, origin)| {
 4527                if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4528                    Some(origin)
 4529                } else {
 4530                    None
 4531                }
 4532            })
 4533            .unwrap_or(Origin::Center)
 4534        };
 4535
 4536        let get_last_active_pane = || {
 4537            let pane = self
 4538                .last_active_center_pane
 4539                .clone()
 4540                .unwrap_or_else(|| {
 4541                    self.panes
 4542                        .first()
 4543                        .expect("There must be an active pane")
 4544                        .downgrade()
 4545                })
 4546                .upgrade()?;
 4547            (pane.read(cx).items_len() != 0).then_some(pane)
 4548        };
 4549
 4550        let try_dock =
 4551            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4552
 4553        let sidebar_target = self
 4554            .sidebar_focus_handle
 4555            .as_ref()
 4556            .map(|h| Target::Sidebar(h.clone()));
 4557
 4558        let target = match (origin, direction) {
 4559            // From the sidebar, only Right navigates into the workspace.
 4560            (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
 4561                .or_else(|| get_last_active_pane().map(Target::Pane))
 4562                .or_else(|| try_dock(&self.bottom_dock))
 4563                .or_else(|| try_dock(&self.right_dock)),
 4564
 4565            (Origin::Sidebar, _) => None,
 4566
 4567            // We're in the center, so we first try to go to a different pane,
 4568            // otherwise try to go to a dock.
 4569            (Origin::Center, direction) => {
 4570                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4571                    Some(Target::Pane(pane))
 4572                } else {
 4573                    match direction {
 4574                        SplitDirection::Up => None,
 4575                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4576                        SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
 4577                        SplitDirection::Right => try_dock(&self.right_dock),
 4578                    }
 4579                }
 4580            }
 4581
 4582            (Origin::LeftDock, SplitDirection::Right) => {
 4583                if let Some(last_active_pane) = get_last_active_pane() {
 4584                    Some(Target::Pane(last_active_pane))
 4585                } else {
 4586                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4587                }
 4588            }
 4589
 4590            (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
 4591
 4592            (Origin::LeftDock, SplitDirection::Down)
 4593            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4594
 4595            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4596            (Origin::BottomDock, SplitDirection::Left) => {
 4597                try_dock(&self.left_dock).or(sidebar_target)
 4598            }
 4599            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4600
 4601            (Origin::RightDock, SplitDirection::Left) => {
 4602                if let Some(last_active_pane) = get_last_active_pane() {
 4603                    Some(Target::Pane(last_active_pane))
 4604                } else {
 4605                    try_dock(&self.bottom_dock)
 4606                        .or_else(|| try_dock(&self.left_dock))
 4607                        .or(sidebar_target)
 4608                }
 4609            }
 4610
 4611            _ => None,
 4612        };
 4613
 4614        match target {
 4615            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4616                let pane = pane.read(cx);
 4617                if let Some(item) = pane.active_item() {
 4618                    item.item_focus_handle(cx).focus(window, cx);
 4619                } else {
 4620                    log::error!(
 4621                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4622                    );
 4623                }
 4624            }
 4625            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4626                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4627                window.defer(cx, move |window, cx| {
 4628                    let dock = dock.read(cx);
 4629                    if let Some(panel) = dock.active_panel() {
 4630                        panel.panel_focus_handle(cx).focus(window, cx);
 4631                    } else {
 4632                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4633                    }
 4634                })
 4635            }
 4636            Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
 4637                focus_handle.focus(window, cx);
 4638            }
 4639            None => {}
 4640        }
 4641    }
 4642
 4643    pub fn move_item_to_pane_in_direction(
 4644        &mut self,
 4645        action: &MoveItemToPaneInDirection,
 4646        window: &mut Window,
 4647        cx: &mut Context<Self>,
 4648    ) {
 4649        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4650            Some(destination) => destination,
 4651            None => {
 4652                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4653                    return;
 4654                }
 4655                let new_pane = self.add_pane(window, cx);
 4656                self.center
 4657                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4658                new_pane
 4659            }
 4660        };
 4661
 4662        if action.clone {
 4663            if self
 4664                .active_pane
 4665                .read(cx)
 4666                .active_item()
 4667                .is_some_and(|item| item.can_split(cx))
 4668            {
 4669                clone_active_item(
 4670                    self.database_id(),
 4671                    &self.active_pane,
 4672                    &destination,
 4673                    action.focus,
 4674                    window,
 4675                    cx,
 4676                );
 4677                return;
 4678            }
 4679        }
 4680        move_active_item(
 4681            &self.active_pane,
 4682            &destination,
 4683            action.focus,
 4684            true,
 4685            window,
 4686            cx,
 4687        );
 4688    }
 4689
 4690    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4691        self.center.bounding_box_for_pane(pane)
 4692    }
 4693
 4694    pub fn find_pane_in_direction(
 4695        &mut self,
 4696        direction: SplitDirection,
 4697        cx: &App,
 4698    ) -> Option<Entity<Pane>> {
 4699        self.center
 4700            .find_pane_in_direction(&self.active_pane, direction, cx)
 4701            .cloned()
 4702    }
 4703
 4704    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4705        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4706            self.center.swap(&self.active_pane, &to, cx);
 4707            cx.notify();
 4708        }
 4709    }
 4710
 4711    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4712        if self
 4713            .center
 4714            .move_to_border(&self.active_pane, direction, cx)
 4715            .unwrap()
 4716        {
 4717            cx.notify();
 4718        }
 4719    }
 4720
 4721    pub fn resize_pane(
 4722        &mut self,
 4723        axis: gpui::Axis,
 4724        amount: Pixels,
 4725        window: &mut Window,
 4726        cx: &mut Context<Self>,
 4727    ) {
 4728        let docks = self.all_docks();
 4729        let active_dock = docks
 4730            .into_iter()
 4731            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4732
 4733        if let Some(dock) = active_dock {
 4734            let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
 4735                return;
 4736            };
 4737            match dock.read(cx).position() {
 4738                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4739                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4740                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4741            }
 4742        } else {
 4743            self.center
 4744                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 4745        }
 4746        cx.notify();
 4747    }
 4748
 4749    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 4750        self.center.reset_pane_sizes(cx);
 4751        cx.notify();
 4752    }
 4753
 4754    fn handle_pane_focused(
 4755        &mut self,
 4756        pane: Entity<Pane>,
 4757        window: &mut Window,
 4758        cx: &mut Context<Self>,
 4759    ) {
 4760        // This is explicitly hoisted out of the following check for pane identity as
 4761        // terminal panel panes are not registered as a center panes.
 4762        self.status_bar.update(cx, |status_bar, cx| {
 4763            status_bar.set_active_pane(&pane, window, cx);
 4764        });
 4765        if self.active_pane != pane {
 4766            self.set_active_pane(&pane, window, cx);
 4767        }
 4768
 4769        if self.last_active_center_pane.is_none() {
 4770            self.last_active_center_pane = Some(pane.downgrade());
 4771        }
 4772
 4773        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 4774        // This prevents the dock from closing when focus events fire during window activation.
 4775        // We also preserve any dock whose active panel itself has focus — this covers
 4776        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 4777        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 4778            let dock_read = dock.read(cx);
 4779            if let Some(panel) = dock_read.active_panel() {
 4780                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 4781                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 4782                {
 4783                    return Some(dock_read.position());
 4784                }
 4785            }
 4786            None
 4787        });
 4788
 4789        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 4790        if pane.read(cx).is_zoomed() {
 4791            self.zoomed = Some(pane.downgrade().into());
 4792        } else {
 4793            self.zoomed = None;
 4794        }
 4795        self.zoomed_position = None;
 4796        cx.emit(Event::ZoomChanged);
 4797        self.update_active_view_for_followers(window, cx);
 4798        pane.update(cx, |pane, _| {
 4799            pane.track_alternate_file_items();
 4800        });
 4801
 4802        cx.notify();
 4803    }
 4804
 4805    fn set_active_pane(
 4806        &mut self,
 4807        pane: &Entity<Pane>,
 4808        window: &mut Window,
 4809        cx: &mut Context<Self>,
 4810    ) {
 4811        self.active_pane = pane.clone();
 4812        self.active_item_path_changed(true, window, cx);
 4813        self.last_active_center_pane = Some(pane.downgrade());
 4814    }
 4815
 4816    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4817        self.update_active_view_for_followers(window, cx);
 4818    }
 4819
 4820    fn handle_pane_event(
 4821        &mut self,
 4822        pane: &Entity<Pane>,
 4823        event: &pane::Event,
 4824        window: &mut Window,
 4825        cx: &mut Context<Self>,
 4826    ) {
 4827        let mut serialize_workspace = true;
 4828        match event {
 4829            pane::Event::AddItem { item } => {
 4830                item.added_to_pane(self, pane.clone(), window, cx);
 4831                cx.emit(Event::ItemAdded {
 4832                    item: item.boxed_clone(),
 4833                });
 4834            }
 4835            pane::Event::Split { direction, mode } => {
 4836                match mode {
 4837                    SplitMode::ClonePane => {
 4838                        self.split_and_clone(pane.clone(), *direction, window, cx)
 4839                            .detach();
 4840                    }
 4841                    SplitMode::EmptyPane => {
 4842                        self.split_pane(pane.clone(), *direction, window, cx);
 4843                    }
 4844                    SplitMode::MovePane => {
 4845                        self.split_and_move(pane.clone(), *direction, window, cx);
 4846                    }
 4847                };
 4848            }
 4849            pane::Event::JoinIntoNext => {
 4850                self.join_pane_into_next(pane.clone(), window, cx);
 4851            }
 4852            pane::Event::JoinAll => {
 4853                self.join_all_panes(window, cx);
 4854            }
 4855            pane::Event::Remove { focus_on_pane } => {
 4856                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 4857            }
 4858            pane::Event::ActivateItem {
 4859                local,
 4860                focus_changed,
 4861            } => {
 4862                window.invalidate_character_coordinates();
 4863
 4864                pane.update(cx, |pane, _| {
 4865                    pane.track_alternate_file_items();
 4866                });
 4867                if *local {
 4868                    self.unfollow_in_pane(pane, window, cx);
 4869                }
 4870                serialize_workspace = *focus_changed || pane != self.active_pane();
 4871                if pane == self.active_pane() {
 4872                    self.active_item_path_changed(*focus_changed, window, cx);
 4873                    self.update_active_view_for_followers(window, cx);
 4874                } else if *local {
 4875                    self.set_active_pane(pane, window, cx);
 4876                }
 4877            }
 4878            pane::Event::UserSavedItem { item, save_intent } => {
 4879                cx.emit(Event::UserSavedItem {
 4880                    pane: pane.downgrade(),
 4881                    item: item.boxed_clone(),
 4882                    save_intent: *save_intent,
 4883                });
 4884                serialize_workspace = false;
 4885            }
 4886            pane::Event::ChangeItemTitle => {
 4887                if *pane == self.active_pane {
 4888                    self.active_item_path_changed(false, window, cx);
 4889                }
 4890                serialize_workspace = false;
 4891            }
 4892            pane::Event::RemovedItem { item } => {
 4893                cx.emit(Event::ActiveItemChanged);
 4894                self.update_window_edited(window, cx);
 4895                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 4896                    && entry.get().entity_id() == pane.entity_id()
 4897                {
 4898                    entry.remove();
 4899                }
 4900                cx.emit(Event::ItemRemoved {
 4901                    item_id: item.item_id(),
 4902                });
 4903            }
 4904            pane::Event::Focus => {
 4905                window.invalidate_character_coordinates();
 4906                self.handle_pane_focused(pane.clone(), window, cx);
 4907            }
 4908            pane::Event::ZoomIn => {
 4909                if *pane == self.active_pane {
 4910                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 4911                    if pane.read(cx).has_focus(window, cx) {
 4912                        self.zoomed = Some(pane.downgrade().into());
 4913                        self.zoomed_position = None;
 4914                        cx.emit(Event::ZoomChanged);
 4915                    }
 4916                    cx.notify();
 4917                }
 4918            }
 4919            pane::Event::ZoomOut => {
 4920                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4921                if self.zoomed_position.is_none() {
 4922                    self.zoomed = None;
 4923                    cx.emit(Event::ZoomChanged);
 4924                }
 4925                cx.notify();
 4926            }
 4927            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 4928        }
 4929
 4930        if serialize_workspace {
 4931            self.serialize_workspace(window, cx);
 4932        }
 4933    }
 4934
 4935    pub fn unfollow_in_pane(
 4936        &mut self,
 4937        pane: &Entity<Pane>,
 4938        window: &mut Window,
 4939        cx: &mut Context<Workspace>,
 4940    ) -> Option<CollaboratorId> {
 4941        let leader_id = self.leader_for_pane(pane)?;
 4942        self.unfollow(leader_id, window, cx);
 4943        Some(leader_id)
 4944    }
 4945
 4946    pub fn split_pane(
 4947        &mut self,
 4948        pane_to_split: Entity<Pane>,
 4949        split_direction: SplitDirection,
 4950        window: &mut Window,
 4951        cx: &mut Context<Self>,
 4952    ) -> Entity<Pane> {
 4953        let new_pane = self.add_pane(window, cx);
 4954        self.center
 4955            .split(&pane_to_split, &new_pane, split_direction, cx);
 4956        cx.notify();
 4957        new_pane
 4958    }
 4959
 4960    pub fn split_and_move(
 4961        &mut self,
 4962        pane: Entity<Pane>,
 4963        direction: SplitDirection,
 4964        window: &mut Window,
 4965        cx: &mut Context<Self>,
 4966    ) {
 4967        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 4968            return;
 4969        };
 4970        let new_pane = self.add_pane(window, cx);
 4971        new_pane.update(cx, |pane, cx| {
 4972            pane.add_item(item, true, true, None, window, cx)
 4973        });
 4974        self.center.split(&pane, &new_pane, direction, cx);
 4975        cx.notify();
 4976    }
 4977
 4978    pub fn split_and_clone(
 4979        &mut self,
 4980        pane: Entity<Pane>,
 4981        direction: SplitDirection,
 4982        window: &mut Window,
 4983        cx: &mut Context<Self>,
 4984    ) -> Task<Option<Entity<Pane>>> {
 4985        let Some(item) = pane.read(cx).active_item() else {
 4986            return Task::ready(None);
 4987        };
 4988        if !item.can_split(cx) {
 4989            return Task::ready(None);
 4990        }
 4991        let task = item.clone_on_split(self.database_id(), window, cx);
 4992        cx.spawn_in(window, async move |this, cx| {
 4993            if let Some(clone) = task.await {
 4994                this.update_in(cx, |this, window, cx| {
 4995                    let new_pane = this.add_pane(window, cx);
 4996                    let nav_history = pane.read(cx).fork_nav_history();
 4997                    new_pane.update(cx, |pane, cx| {
 4998                        pane.set_nav_history(nav_history, cx);
 4999                        pane.add_item(clone, true, true, None, window, cx)
 5000                    });
 5001                    this.center.split(&pane, &new_pane, direction, cx);
 5002                    cx.notify();
 5003                    new_pane
 5004                })
 5005                .ok()
 5006            } else {
 5007                None
 5008            }
 5009        })
 5010    }
 5011
 5012    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5013        let active_item = self.active_pane.read(cx).active_item();
 5014        for pane in &self.panes {
 5015            join_pane_into_active(&self.active_pane, pane, window, cx);
 5016        }
 5017        if let Some(active_item) = active_item {
 5018            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5019        }
 5020        cx.notify();
 5021    }
 5022
 5023    pub fn join_pane_into_next(
 5024        &mut self,
 5025        pane: Entity<Pane>,
 5026        window: &mut Window,
 5027        cx: &mut Context<Self>,
 5028    ) {
 5029        let next_pane = self
 5030            .find_pane_in_direction(SplitDirection::Right, cx)
 5031            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5032            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5033            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5034        let Some(next_pane) = next_pane else {
 5035            return;
 5036        };
 5037        move_all_items(&pane, &next_pane, window, cx);
 5038        cx.notify();
 5039    }
 5040
 5041    fn remove_pane(
 5042        &mut self,
 5043        pane: Entity<Pane>,
 5044        focus_on: Option<Entity<Pane>>,
 5045        window: &mut Window,
 5046        cx: &mut Context<Self>,
 5047    ) {
 5048        if self.center.remove(&pane, cx).unwrap() {
 5049            self.force_remove_pane(&pane, &focus_on, window, cx);
 5050            self.unfollow_in_pane(&pane, window, cx);
 5051            self.last_leaders_by_pane.remove(&pane.downgrade());
 5052            for removed_item in pane.read(cx).items() {
 5053                self.panes_by_item.remove(&removed_item.item_id());
 5054            }
 5055
 5056            cx.notify();
 5057        } else {
 5058            self.active_item_path_changed(true, window, cx);
 5059        }
 5060        cx.emit(Event::PaneRemoved);
 5061    }
 5062
 5063    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5064        &mut self.panes
 5065    }
 5066
 5067    pub fn panes(&self) -> &[Entity<Pane>] {
 5068        &self.panes
 5069    }
 5070
 5071    pub fn active_pane(&self) -> &Entity<Pane> {
 5072        &self.active_pane
 5073    }
 5074
 5075    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5076        for dock in self.all_docks() {
 5077            if dock.focus_handle(cx).contains_focused(window, cx)
 5078                && let Some(pane) = dock
 5079                    .read(cx)
 5080                    .active_panel()
 5081                    .and_then(|panel| panel.pane(cx))
 5082            {
 5083                return pane;
 5084            }
 5085        }
 5086        self.active_pane().clone()
 5087    }
 5088
 5089    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5090        self.find_pane_in_direction(SplitDirection::Right, cx)
 5091            .unwrap_or_else(|| {
 5092                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5093            })
 5094    }
 5095
 5096    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5097        self.pane_for_item_id(handle.item_id())
 5098    }
 5099
 5100    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5101        let weak_pane = self.panes_by_item.get(&item_id)?;
 5102        weak_pane.upgrade()
 5103    }
 5104
 5105    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5106        self.panes
 5107            .iter()
 5108            .find(|pane| pane.entity_id() == entity_id)
 5109            .cloned()
 5110    }
 5111
 5112    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5113        self.follower_states.retain(|leader_id, state| {
 5114            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5115                for item in state.items_by_leader_view_id.values() {
 5116                    item.view.set_leader_id(None, window, cx);
 5117                }
 5118                false
 5119            } else {
 5120                true
 5121            }
 5122        });
 5123        cx.notify();
 5124    }
 5125
 5126    pub fn start_following(
 5127        &mut self,
 5128        leader_id: impl Into<CollaboratorId>,
 5129        window: &mut Window,
 5130        cx: &mut Context<Self>,
 5131    ) -> Option<Task<Result<()>>> {
 5132        let leader_id = leader_id.into();
 5133        let pane = self.active_pane().clone();
 5134
 5135        self.last_leaders_by_pane
 5136            .insert(pane.downgrade(), leader_id);
 5137        self.unfollow(leader_id, window, cx);
 5138        self.unfollow_in_pane(&pane, window, cx);
 5139        self.follower_states.insert(
 5140            leader_id,
 5141            FollowerState {
 5142                center_pane: pane.clone(),
 5143                dock_pane: None,
 5144                active_view_id: None,
 5145                items_by_leader_view_id: Default::default(),
 5146            },
 5147        );
 5148        cx.notify();
 5149
 5150        match leader_id {
 5151            CollaboratorId::PeerId(leader_peer_id) => {
 5152                let room_id = self.active_call()?.room_id(cx)?;
 5153                let project_id = self.project.read(cx).remote_id();
 5154                let request = self.app_state.client.request(proto::Follow {
 5155                    room_id,
 5156                    project_id,
 5157                    leader_id: Some(leader_peer_id),
 5158                });
 5159
 5160                Some(cx.spawn_in(window, async move |this, cx| {
 5161                    let response = request.await?;
 5162                    this.update(cx, |this, _| {
 5163                        let state = this
 5164                            .follower_states
 5165                            .get_mut(&leader_id)
 5166                            .context("following interrupted")?;
 5167                        state.active_view_id = response
 5168                            .active_view
 5169                            .as_ref()
 5170                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5171                        anyhow::Ok(())
 5172                    })??;
 5173                    if let Some(view) = response.active_view {
 5174                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5175                    }
 5176                    this.update_in(cx, |this, window, cx| {
 5177                        this.leader_updated(leader_id, window, cx)
 5178                    })?;
 5179                    Ok(())
 5180                }))
 5181            }
 5182            CollaboratorId::Agent => {
 5183                self.leader_updated(leader_id, window, cx)?;
 5184                Some(Task::ready(Ok(())))
 5185            }
 5186        }
 5187    }
 5188
 5189    pub fn follow_next_collaborator(
 5190        &mut self,
 5191        _: &FollowNextCollaborator,
 5192        window: &mut Window,
 5193        cx: &mut Context<Self>,
 5194    ) {
 5195        let collaborators = self.project.read(cx).collaborators();
 5196        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5197            let mut collaborators = collaborators.keys().copied();
 5198            for peer_id in collaborators.by_ref() {
 5199                if CollaboratorId::PeerId(peer_id) == leader_id {
 5200                    break;
 5201                }
 5202            }
 5203            collaborators.next().map(CollaboratorId::PeerId)
 5204        } else if let Some(last_leader_id) =
 5205            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5206        {
 5207            match last_leader_id {
 5208                CollaboratorId::PeerId(peer_id) => {
 5209                    if collaborators.contains_key(peer_id) {
 5210                        Some(*last_leader_id)
 5211                    } else {
 5212                        None
 5213                    }
 5214                }
 5215                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5216            }
 5217        } else {
 5218            None
 5219        };
 5220
 5221        let pane = self.active_pane.clone();
 5222        let Some(leader_id) = next_leader_id.or_else(|| {
 5223            Some(CollaboratorId::PeerId(
 5224                collaborators.keys().copied().next()?,
 5225            ))
 5226        }) else {
 5227            return;
 5228        };
 5229        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5230            return;
 5231        }
 5232        if let Some(task) = self.start_following(leader_id, window, cx) {
 5233            task.detach_and_log_err(cx)
 5234        }
 5235    }
 5236
 5237    pub fn follow(
 5238        &mut self,
 5239        leader_id: impl Into<CollaboratorId>,
 5240        window: &mut Window,
 5241        cx: &mut Context<Self>,
 5242    ) {
 5243        let leader_id = leader_id.into();
 5244
 5245        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5246            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5247                return;
 5248            };
 5249            let Some(remote_participant) =
 5250                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5251            else {
 5252                return;
 5253            };
 5254
 5255            let project = self.project.read(cx);
 5256
 5257            let other_project_id = match remote_participant.location {
 5258                ParticipantLocation::External => None,
 5259                ParticipantLocation::UnsharedProject => None,
 5260                ParticipantLocation::SharedProject { project_id } => {
 5261                    if Some(project_id) == project.remote_id() {
 5262                        None
 5263                    } else {
 5264                        Some(project_id)
 5265                    }
 5266                }
 5267            };
 5268
 5269            // if they are active in another project, follow there.
 5270            if let Some(project_id) = other_project_id {
 5271                let app_state = self.app_state.clone();
 5272                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5273                    .detach_and_log_err(cx);
 5274            }
 5275        }
 5276
 5277        // if you're already following, find the right pane and focus it.
 5278        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5279            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5280
 5281            return;
 5282        }
 5283
 5284        // Otherwise, follow.
 5285        if let Some(task) = self.start_following(leader_id, window, cx) {
 5286            task.detach_and_log_err(cx)
 5287        }
 5288    }
 5289
 5290    pub fn unfollow(
 5291        &mut self,
 5292        leader_id: impl Into<CollaboratorId>,
 5293        window: &mut Window,
 5294        cx: &mut Context<Self>,
 5295    ) -> Option<()> {
 5296        cx.notify();
 5297
 5298        let leader_id = leader_id.into();
 5299        let state = self.follower_states.remove(&leader_id)?;
 5300        for (_, item) in state.items_by_leader_view_id {
 5301            item.view.set_leader_id(None, window, cx);
 5302        }
 5303
 5304        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5305            let project_id = self.project.read(cx).remote_id();
 5306            let room_id = self.active_call()?.room_id(cx)?;
 5307            self.app_state
 5308                .client
 5309                .send(proto::Unfollow {
 5310                    room_id,
 5311                    project_id,
 5312                    leader_id: Some(leader_peer_id),
 5313                })
 5314                .log_err();
 5315        }
 5316
 5317        Some(())
 5318    }
 5319
 5320    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5321        self.follower_states.contains_key(&id.into())
 5322    }
 5323
 5324    fn active_item_path_changed(
 5325        &mut self,
 5326        focus_changed: bool,
 5327        window: &mut Window,
 5328        cx: &mut Context<Self>,
 5329    ) {
 5330        cx.emit(Event::ActiveItemChanged);
 5331        let active_entry = self.active_project_path(cx);
 5332        self.project.update(cx, |project, cx| {
 5333            project.set_active_path(active_entry.clone(), cx)
 5334        });
 5335
 5336        if focus_changed && let Some(project_path) = &active_entry {
 5337            let git_store_entity = self.project.read(cx).git_store().clone();
 5338            git_store_entity.update(cx, |git_store, cx| {
 5339                git_store.set_active_repo_for_path(project_path, cx);
 5340            });
 5341        }
 5342
 5343        self.update_window_title(window, cx);
 5344    }
 5345
 5346    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5347        let project = self.project().read(cx);
 5348        let mut title = String::new();
 5349
 5350        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5351            let name = {
 5352                let settings_location = SettingsLocation {
 5353                    worktree_id: worktree.read(cx).id(),
 5354                    path: RelPath::empty(),
 5355                };
 5356
 5357                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5358                match &settings.project_name {
 5359                    Some(name) => name.as_str(),
 5360                    None => worktree.read(cx).root_name_str(),
 5361                }
 5362            };
 5363            if i > 0 {
 5364                title.push_str(", ");
 5365            }
 5366            title.push_str(name);
 5367        }
 5368
 5369        if title.is_empty() {
 5370            title = "empty project".to_string();
 5371        }
 5372
 5373        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5374            let filename = path.path.file_name().or_else(|| {
 5375                Some(
 5376                    project
 5377                        .worktree_for_id(path.worktree_id, cx)?
 5378                        .read(cx)
 5379                        .root_name_str(),
 5380                )
 5381            });
 5382
 5383            if let Some(filename) = filename {
 5384                title.push_str("");
 5385                title.push_str(filename.as_ref());
 5386            }
 5387        }
 5388
 5389        if project.is_via_collab() {
 5390            title.push_str("");
 5391        } else if project.is_shared() {
 5392            title.push_str("");
 5393        }
 5394
 5395        if let Some(last_title) = self.last_window_title.as_ref()
 5396            && &title == last_title
 5397        {
 5398            return;
 5399        }
 5400        window.set_window_title(&title);
 5401        SystemWindowTabController::update_tab_title(
 5402            cx,
 5403            window.window_handle().window_id(),
 5404            SharedString::from(&title),
 5405        );
 5406        self.last_window_title = Some(title);
 5407    }
 5408
 5409    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5410        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5411        if is_edited != self.window_edited {
 5412            self.window_edited = is_edited;
 5413            window.set_window_edited(self.window_edited)
 5414        }
 5415    }
 5416
 5417    fn update_item_dirty_state(
 5418        &mut self,
 5419        item: &dyn ItemHandle,
 5420        window: &mut Window,
 5421        cx: &mut App,
 5422    ) {
 5423        let is_dirty = item.is_dirty(cx);
 5424        let item_id = item.item_id();
 5425        let was_dirty = self.dirty_items.contains_key(&item_id);
 5426        if is_dirty == was_dirty {
 5427            return;
 5428        }
 5429        if was_dirty {
 5430            self.dirty_items.remove(&item_id);
 5431            self.update_window_edited(window, cx);
 5432            return;
 5433        }
 5434
 5435        let workspace = self.weak_handle();
 5436        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5437            return;
 5438        };
 5439        let on_release_callback = Box::new(move |cx: &mut App| {
 5440            window_handle
 5441                .update(cx, |_, window, cx| {
 5442                    workspace
 5443                        .update(cx, |workspace, cx| {
 5444                            workspace.dirty_items.remove(&item_id);
 5445                            workspace.update_window_edited(window, cx)
 5446                        })
 5447                        .ok();
 5448                })
 5449                .ok();
 5450        });
 5451
 5452        let s = item.on_release(cx, on_release_callback);
 5453        self.dirty_items.insert(item_id, s);
 5454        self.update_window_edited(window, cx);
 5455    }
 5456
 5457    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5458        if self.notifications.is_empty() {
 5459            None
 5460        } else {
 5461            Some(
 5462                div()
 5463                    .absolute()
 5464                    .right_3()
 5465                    .bottom_3()
 5466                    .w_112()
 5467                    .h_full()
 5468                    .flex()
 5469                    .flex_col()
 5470                    .justify_end()
 5471                    .gap_2()
 5472                    .children(
 5473                        self.notifications
 5474                            .iter()
 5475                            .map(|(_, notification)| notification.clone().into_any()),
 5476                    ),
 5477            )
 5478        }
 5479    }
 5480
 5481    // RPC handlers
 5482
 5483    fn active_view_for_follower(
 5484        &self,
 5485        follower_project_id: Option<u64>,
 5486        window: &mut Window,
 5487        cx: &mut Context<Self>,
 5488    ) -> Option<proto::View> {
 5489        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5490        let item = item?;
 5491        let leader_id = self
 5492            .pane_for(&*item)
 5493            .and_then(|pane| self.leader_for_pane(&pane));
 5494        let leader_peer_id = match leader_id {
 5495            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5496            Some(CollaboratorId::Agent) | None => None,
 5497        };
 5498
 5499        let item_handle = item.to_followable_item_handle(cx)?;
 5500        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5501        let variant = item_handle.to_state_proto(window, cx)?;
 5502
 5503        if item_handle.is_project_item(window, cx)
 5504            && (follower_project_id.is_none()
 5505                || follower_project_id != self.project.read(cx).remote_id())
 5506        {
 5507            return None;
 5508        }
 5509
 5510        Some(proto::View {
 5511            id: id.to_proto(),
 5512            leader_id: leader_peer_id,
 5513            variant: Some(variant),
 5514            panel_id: panel_id.map(|id| id as i32),
 5515        })
 5516    }
 5517
 5518    fn handle_follow(
 5519        &mut self,
 5520        follower_project_id: Option<u64>,
 5521        window: &mut Window,
 5522        cx: &mut Context<Self>,
 5523    ) -> proto::FollowResponse {
 5524        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5525
 5526        cx.notify();
 5527        proto::FollowResponse {
 5528            views: active_view.iter().cloned().collect(),
 5529            active_view,
 5530        }
 5531    }
 5532
 5533    fn handle_update_followers(
 5534        &mut self,
 5535        leader_id: PeerId,
 5536        message: proto::UpdateFollowers,
 5537        _window: &mut Window,
 5538        _cx: &mut Context<Self>,
 5539    ) {
 5540        self.leader_updates_tx
 5541            .unbounded_send((leader_id, message))
 5542            .ok();
 5543    }
 5544
 5545    async fn process_leader_update(
 5546        this: &WeakEntity<Self>,
 5547        leader_id: PeerId,
 5548        update: proto::UpdateFollowers,
 5549        cx: &mut AsyncWindowContext,
 5550    ) -> Result<()> {
 5551        match update.variant.context("invalid update")? {
 5552            proto::update_followers::Variant::CreateView(view) => {
 5553                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5554                let should_add_view = this.update(cx, |this, _| {
 5555                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5556                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5557                    } else {
 5558                        anyhow::Ok(false)
 5559                    }
 5560                })??;
 5561
 5562                if should_add_view {
 5563                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5564                }
 5565            }
 5566            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5567                let should_add_view = this.update(cx, |this, _| {
 5568                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5569                        state.active_view_id = update_active_view
 5570                            .view
 5571                            .as_ref()
 5572                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5573
 5574                        if state.active_view_id.is_some_and(|view_id| {
 5575                            !state.items_by_leader_view_id.contains_key(&view_id)
 5576                        }) {
 5577                            anyhow::Ok(true)
 5578                        } else {
 5579                            anyhow::Ok(false)
 5580                        }
 5581                    } else {
 5582                        anyhow::Ok(false)
 5583                    }
 5584                })??;
 5585
 5586                if should_add_view && let Some(view) = update_active_view.view {
 5587                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5588                }
 5589            }
 5590            proto::update_followers::Variant::UpdateView(update_view) => {
 5591                let variant = update_view.variant.context("missing update view variant")?;
 5592                let id = update_view.id.context("missing update view id")?;
 5593                let mut tasks = Vec::new();
 5594                this.update_in(cx, |this, window, cx| {
 5595                    let project = this.project.clone();
 5596                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5597                        let view_id = ViewId::from_proto(id.clone())?;
 5598                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5599                            tasks.push(item.view.apply_update_proto(
 5600                                &project,
 5601                                variant.clone(),
 5602                                window,
 5603                                cx,
 5604                            ));
 5605                        }
 5606                    }
 5607                    anyhow::Ok(())
 5608                })??;
 5609                try_join_all(tasks).await.log_err();
 5610            }
 5611        }
 5612        this.update_in(cx, |this, window, cx| {
 5613            this.leader_updated(leader_id, window, cx)
 5614        })?;
 5615        Ok(())
 5616    }
 5617
 5618    async fn add_view_from_leader(
 5619        this: WeakEntity<Self>,
 5620        leader_id: PeerId,
 5621        view: &proto::View,
 5622        cx: &mut AsyncWindowContext,
 5623    ) -> Result<()> {
 5624        let this = this.upgrade().context("workspace dropped")?;
 5625
 5626        let Some(id) = view.id.clone() else {
 5627            anyhow::bail!("no id for view");
 5628        };
 5629        let id = ViewId::from_proto(id)?;
 5630        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5631
 5632        let pane = this.update(cx, |this, _cx| {
 5633            let state = this
 5634                .follower_states
 5635                .get(&leader_id.into())
 5636                .context("stopped following")?;
 5637            anyhow::Ok(state.pane().clone())
 5638        })?;
 5639        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5640            let client = this.read(cx).client().clone();
 5641            pane.items().find_map(|item| {
 5642                let item = item.to_followable_item_handle(cx)?;
 5643                if item.remote_id(&client, window, cx) == Some(id) {
 5644                    Some(item)
 5645                } else {
 5646                    None
 5647                }
 5648            })
 5649        })?;
 5650        let item = if let Some(existing_item) = existing_item {
 5651            existing_item
 5652        } else {
 5653            let variant = view.variant.clone();
 5654            anyhow::ensure!(variant.is_some(), "missing view variant");
 5655
 5656            let task = cx.update(|window, cx| {
 5657                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5658            })?;
 5659
 5660            let Some(task) = task else {
 5661                anyhow::bail!(
 5662                    "failed to construct view from leader (maybe from a different version of zed?)"
 5663                );
 5664            };
 5665
 5666            let mut new_item = task.await?;
 5667            pane.update_in(cx, |pane, window, cx| {
 5668                let mut item_to_remove = None;
 5669                for (ix, item) in pane.items().enumerate() {
 5670                    if let Some(item) = item.to_followable_item_handle(cx) {
 5671                        match new_item.dedup(item.as_ref(), window, cx) {
 5672                            Some(item::Dedup::KeepExisting) => {
 5673                                new_item =
 5674                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5675                                break;
 5676                            }
 5677                            Some(item::Dedup::ReplaceExisting) => {
 5678                                item_to_remove = Some((ix, item.item_id()));
 5679                                break;
 5680                            }
 5681                            None => {}
 5682                        }
 5683                    }
 5684                }
 5685
 5686                if let Some((ix, id)) = item_to_remove {
 5687                    pane.remove_item(id, false, false, window, cx);
 5688                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5689                }
 5690            })?;
 5691
 5692            new_item
 5693        };
 5694
 5695        this.update_in(cx, |this, window, cx| {
 5696            let state = this.follower_states.get_mut(&leader_id.into())?;
 5697            item.set_leader_id(Some(leader_id.into()), window, cx);
 5698            state.items_by_leader_view_id.insert(
 5699                id,
 5700                FollowerView {
 5701                    view: item,
 5702                    location: panel_id,
 5703                },
 5704            );
 5705
 5706            Some(())
 5707        })
 5708        .context("no follower state")?;
 5709
 5710        Ok(())
 5711    }
 5712
 5713    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5714        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5715            return;
 5716        };
 5717
 5718        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5719            let buffer_entity_id = agent_location.buffer.entity_id();
 5720            let view_id = ViewId {
 5721                creator: CollaboratorId::Agent,
 5722                id: buffer_entity_id.as_u64(),
 5723            };
 5724            follower_state.active_view_id = Some(view_id);
 5725
 5726            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5727                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5728                hash_map::Entry::Vacant(entry) => {
 5729                    let existing_view =
 5730                        follower_state
 5731                            .center_pane
 5732                            .read(cx)
 5733                            .items()
 5734                            .find_map(|item| {
 5735                                let item = item.to_followable_item_handle(cx)?;
 5736                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5737                                    && item.project_item_model_ids(cx).as_slice()
 5738                                        == [buffer_entity_id]
 5739                                {
 5740                                    Some(item)
 5741                                } else {
 5742                                    None
 5743                                }
 5744                            });
 5745                    let view = existing_view.or_else(|| {
 5746                        agent_location.buffer.upgrade().and_then(|buffer| {
 5747                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 5748                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 5749                            })?
 5750                            .to_followable_item_handle(cx)
 5751                        })
 5752                    });
 5753
 5754                    view.map(|view| {
 5755                        entry.insert(FollowerView {
 5756                            view,
 5757                            location: None,
 5758                        })
 5759                    })
 5760                }
 5761            };
 5762
 5763            if let Some(item) = item {
 5764                item.view
 5765                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 5766                item.view
 5767                    .update_agent_location(agent_location.position, window, cx);
 5768            }
 5769        } else {
 5770            follower_state.active_view_id = None;
 5771        }
 5772
 5773        self.leader_updated(CollaboratorId::Agent, window, cx);
 5774    }
 5775
 5776    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 5777        let mut is_project_item = true;
 5778        let mut update = proto::UpdateActiveView::default();
 5779        if window.is_window_active() {
 5780            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 5781
 5782            if let Some(item) = active_item
 5783                && item.item_focus_handle(cx).contains_focused(window, cx)
 5784            {
 5785                let leader_id = self
 5786                    .pane_for(&*item)
 5787                    .and_then(|pane| self.leader_for_pane(&pane));
 5788                let leader_peer_id = match leader_id {
 5789                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5790                    Some(CollaboratorId::Agent) | None => None,
 5791                };
 5792
 5793                if let Some(item) = item.to_followable_item_handle(cx) {
 5794                    let id = item
 5795                        .remote_id(&self.app_state.client, window, cx)
 5796                        .map(|id| id.to_proto());
 5797
 5798                    if let Some(id) = id
 5799                        && let Some(variant) = item.to_state_proto(window, cx)
 5800                    {
 5801                        let view = Some(proto::View {
 5802                            id,
 5803                            leader_id: leader_peer_id,
 5804                            variant: Some(variant),
 5805                            panel_id: panel_id.map(|id| id as i32),
 5806                        });
 5807
 5808                        is_project_item = item.is_project_item(window, cx);
 5809                        update = proto::UpdateActiveView { view };
 5810                    };
 5811                }
 5812            }
 5813        }
 5814
 5815        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 5816        if active_view_id != self.last_active_view_id.as_ref() {
 5817            self.last_active_view_id = active_view_id.cloned();
 5818            self.update_followers(
 5819                is_project_item,
 5820                proto::update_followers::Variant::UpdateActiveView(update),
 5821                window,
 5822                cx,
 5823            );
 5824        }
 5825    }
 5826
 5827    fn active_item_for_followers(
 5828        &self,
 5829        window: &mut Window,
 5830        cx: &mut App,
 5831    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 5832        let mut active_item = None;
 5833        let mut panel_id = None;
 5834        for dock in self.all_docks() {
 5835            if dock.focus_handle(cx).contains_focused(window, cx)
 5836                && let Some(panel) = dock.read(cx).active_panel()
 5837                && let Some(pane) = panel.pane(cx)
 5838                && let Some(item) = pane.read(cx).active_item()
 5839            {
 5840                active_item = Some(item);
 5841                panel_id = panel.remote_id();
 5842                break;
 5843            }
 5844        }
 5845
 5846        if active_item.is_none() {
 5847            active_item = self.active_pane().read(cx).active_item();
 5848        }
 5849        (active_item, panel_id)
 5850    }
 5851
 5852    fn update_followers(
 5853        &self,
 5854        project_only: bool,
 5855        update: proto::update_followers::Variant,
 5856        _: &mut Window,
 5857        cx: &mut App,
 5858    ) -> Option<()> {
 5859        // If this update only applies to for followers in the current project,
 5860        // then skip it unless this project is shared. If it applies to all
 5861        // followers, regardless of project, then set `project_id` to none,
 5862        // indicating that it goes to all followers.
 5863        let project_id = if project_only {
 5864            Some(self.project.read(cx).remote_id()?)
 5865        } else {
 5866            None
 5867        };
 5868        self.app_state().workspace_store.update(cx, |store, cx| {
 5869            store.update_followers(project_id, update, cx)
 5870        })
 5871    }
 5872
 5873    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 5874        self.follower_states.iter().find_map(|(leader_id, state)| {
 5875            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 5876                Some(*leader_id)
 5877            } else {
 5878                None
 5879            }
 5880        })
 5881    }
 5882
 5883    fn leader_updated(
 5884        &mut self,
 5885        leader_id: impl Into<CollaboratorId>,
 5886        window: &mut Window,
 5887        cx: &mut Context<Self>,
 5888    ) -> Option<Box<dyn ItemHandle>> {
 5889        cx.notify();
 5890
 5891        let leader_id = leader_id.into();
 5892        let (panel_id, item) = match leader_id {
 5893            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 5894            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 5895        };
 5896
 5897        let state = self.follower_states.get(&leader_id)?;
 5898        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 5899        let pane;
 5900        if let Some(panel_id) = panel_id {
 5901            pane = self
 5902                .activate_panel_for_proto_id(panel_id, window, cx)?
 5903                .pane(cx)?;
 5904            let state = self.follower_states.get_mut(&leader_id)?;
 5905            state.dock_pane = Some(pane.clone());
 5906        } else {
 5907            pane = state.center_pane.clone();
 5908            let state = self.follower_states.get_mut(&leader_id)?;
 5909            if let Some(dock_pane) = state.dock_pane.take() {
 5910                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 5911            }
 5912        }
 5913
 5914        pane.update(cx, |pane, cx| {
 5915            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 5916            if let Some(index) = pane.index_for_item(item.as_ref()) {
 5917                pane.activate_item(index, false, false, window, cx);
 5918            } else {
 5919                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 5920            }
 5921
 5922            if focus_active_item {
 5923                pane.focus_active_item(window, cx)
 5924            }
 5925        });
 5926
 5927        Some(item)
 5928    }
 5929
 5930    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 5931        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 5932        let active_view_id = state.active_view_id?;
 5933        Some(
 5934            state
 5935                .items_by_leader_view_id
 5936                .get(&active_view_id)?
 5937                .view
 5938                .boxed_clone(),
 5939        )
 5940    }
 5941
 5942    fn active_item_for_peer(
 5943        &self,
 5944        peer_id: PeerId,
 5945        window: &mut Window,
 5946        cx: &mut Context<Self>,
 5947    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 5948        let call = self.active_call()?;
 5949        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 5950        let leader_in_this_app;
 5951        let leader_in_this_project;
 5952        match participant.location {
 5953            ParticipantLocation::SharedProject { project_id } => {
 5954                leader_in_this_app = true;
 5955                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 5956            }
 5957            ParticipantLocation::UnsharedProject => {
 5958                leader_in_this_app = true;
 5959                leader_in_this_project = false;
 5960            }
 5961            ParticipantLocation::External => {
 5962                leader_in_this_app = false;
 5963                leader_in_this_project = false;
 5964            }
 5965        };
 5966        let state = self.follower_states.get(&peer_id.into())?;
 5967        let mut item_to_activate = None;
 5968        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 5969            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 5970                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 5971            {
 5972                item_to_activate = Some((item.location, item.view.boxed_clone()));
 5973            }
 5974        } else if let Some(shared_screen) =
 5975            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 5976        {
 5977            item_to_activate = Some((None, Box::new(shared_screen)));
 5978        }
 5979        item_to_activate
 5980    }
 5981
 5982    fn shared_screen_for_peer(
 5983        &self,
 5984        peer_id: PeerId,
 5985        pane: &Entity<Pane>,
 5986        window: &mut Window,
 5987        cx: &mut App,
 5988    ) -> Option<Entity<SharedScreen>> {
 5989        self.active_call()?
 5990            .create_shared_screen(peer_id, pane, window, cx)
 5991    }
 5992
 5993    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5994        if window.is_window_active() {
 5995            self.update_active_view_for_followers(window, cx);
 5996
 5997            if let Some(database_id) = self.database_id {
 5998                let db = WorkspaceDb::global(cx);
 5999                cx.background_spawn(async move { db.update_timestamp(database_id).await })
 6000                    .detach();
 6001            }
 6002        } else {
 6003            for pane in &self.panes {
 6004                pane.update(cx, |pane, cx| {
 6005                    if let Some(item) = pane.active_item() {
 6006                        item.workspace_deactivated(window, cx);
 6007                    }
 6008                    for item in pane.items() {
 6009                        if matches!(
 6010                            item.workspace_settings(cx).autosave,
 6011                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6012                        ) {
 6013                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6014                                .detach_and_log_err(cx);
 6015                        }
 6016                    }
 6017                });
 6018            }
 6019        }
 6020    }
 6021
 6022    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6023        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6024    }
 6025
 6026    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6027        self.active_call.as_ref().map(|(call, _)| call.clone())
 6028    }
 6029
 6030    fn on_active_call_event(
 6031        &mut self,
 6032        event: &ActiveCallEvent,
 6033        window: &mut Window,
 6034        cx: &mut Context<Self>,
 6035    ) {
 6036        match event {
 6037            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6038            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6039                self.leader_updated(participant_id, window, cx);
 6040            }
 6041        }
 6042    }
 6043
 6044    pub fn database_id(&self) -> Option<WorkspaceId> {
 6045        self.database_id
 6046    }
 6047
 6048    #[cfg(any(test, feature = "test-support"))]
 6049    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6050        self.database_id = Some(id);
 6051    }
 6052
 6053    pub fn session_id(&self) -> Option<String> {
 6054        self.session_id.clone()
 6055    }
 6056
 6057    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6058        let Some(display) = window.display(cx) else {
 6059            return Task::ready(());
 6060        };
 6061        let Ok(display_uuid) = display.uuid() else {
 6062            return Task::ready(());
 6063        };
 6064
 6065        let window_bounds = window.inner_window_bounds();
 6066        let database_id = self.database_id;
 6067        let has_paths = !self.root_paths(cx).is_empty();
 6068        let db = WorkspaceDb::global(cx);
 6069        let kvp = db::kvp::KeyValueStore::global(cx);
 6070
 6071        cx.background_executor().spawn(async move {
 6072            if !has_paths {
 6073                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6074                    .await
 6075                    .log_err();
 6076            }
 6077            if let Some(database_id) = database_id {
 6078                db.set_window_open_status(
 6079                    database_id,
 6080                    SerializedWindowBounds(window_bounds),
 6081                    display_uuid,
 6082                )
 6083                .await
 6084                .log_err();
 6085            } else {
 6086                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6087                    .await
 6088                    .log_err();
 6089            }
 6090        })
 6091    }
 6092
 6093    /// Bypass the 200ms serialization throttle and write workspace state to
 6094    /// the DB immediately. Returns a task the caller can await to ensure the
 6095    /// write completes. Used by the quit handler so the most recent state
 6096    /// isn't lost to a pending throttle timer when the process exits.
 6097    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6098        self._schedule_serialize_workspace.take();
 6099        self._serialize_workspace_task.take();
 6100        self.bounds_save_task_queued.take();
 6101
 6102        let bounds_task = self.save_window_bounds(window, cx);
 6103        let serialize_task = self.serialize_workspace_internal(window, cx);
 6104        cx.spawn(async move |_| {
 6105            bounds_task.await;
 6106            serialize_task.await;
 6107        })
 6108    }
 6109
 6110    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6111        let project = self.project().read(cx);
 6112        project
 6113            .visible_worktrees(cx)
 6114            .map(|worktree| worktree.read(cx).abs_path())
 6115            .collect::<Vec<_>>()
 6116    }
 6117
 6118    pub fn path_list(&self, cx: &App) -> PathList {
 6119        PathList::new(&self.root_paths(cx))
 6120    }
 6121
 6122    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6123        match member {
 6124            Member::Axis(PaneAxis { members, .. }) => {
 6125                for child in members.iter() {
 6126                    self.remove_panes(child.clone(), window, cx)
 6127                }
 6128            }
 6129            Member::Pane(pane) => {
 6130                self.force_remove_pane(&pane, &None, window, cx);
 6131            }
 6132        }
 6133    }
 6134
 6135    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6136        self.session_id.take();
 6137        self.serialize_workspace_internal(window, cx)
 6138    }
 6139
 6140    fn force_remove_pane(
 6141        &mut self,
 6142        pane: &Entity<Pane>,
 6143        focus_on: &Option<Entity<Pane>>,
 6144        window: &mut Window,
 6145        cx: &mut Context<Workspace>,
 6146    ) {
 6147        self.panes.retain(|p| p != pane);
 6148        if let Some(focus_on) = focus_on {
 6149            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6150        } else if self.active_pane() == pane {
 6151            self.panes
 6152                .last()
 6153                .unwrap()
 6154                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6155        }
 6156        if self.last_active_center_pane == Some(pane.downgrade()) {
 6157            self.last_active_center_pane = None;
 6158        }
 6159        cx.notify();
 6160    }
 6161
 6162    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6163        if self._schedule_serialize_workspace.is_none() {
 6164            self._schedule_serialize_workspace =
 6165                Some(cx.spawn_in(window, async move |this, cx| {
 6166                    cx.background_executor()
 6167                        .timer(SERIALIZATION_THROTTLE_TIME)
 6168                        .await;
 6169                    this.update_in(cx, |this, window, cx| {
 6170                        this._serialize_workspace_task =
 6171                            Some(this.serialize_workspace_internal(window, cx));
 6172                        this._schedule_serialize_workspace.take();
 6173                    })
 6174                    .log_err();
 6175                }));
 6176        }
 6177    }
 6178
 6179    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6180        let Some(database_id) = self.database_id() else {
 6181            return Task::ready(());
 6182        };
 6183
 6184        fn serialize_pane_handle(
 6185            pane_handle: &Entity<Pane>,
 6186            window: &mut Window,
 6187            cx: &mut App,
 6188        ) -> SerializedPane {
 6189            let (items, active, pinned_count) = {
 6190                let pane = pane_handle.read(cx);
 6191                let active_item_id = pane.active_item().map(|item| item.item_id());
 6192                (
 6193                    pane.items()
 6194                        .filter_map(|handle| {
 6195                            let handle = handle.to_serializable_item_handle(cx)?;
 6196
 6197                            Some(SerializedItem {
 6198                                kind: Arc::from(handle.serialized_item_kind()),
 6199                                item_id: handle.item_id().as_u64(),
 6200                                active: Some(handle.item_id()) == active_item_id,
 6201                                preview: pane.is_active_preview_item(handle.item_id()),
 6202                            })
 6203                        })
 6204                        .collect::<Vec<_>>(),
 6205                    pane.has_focus(window, cx),
 6206                    pane.pinned_count(),
 6207                )
 6208            };
 6209
 6210            SerializedPane::new(items, active, pinned_count)
 6211        }
 6212
 6213        fn build_serialized_pane_group(
 6214            pane_group: &Member,
 6215            window: &mut Window,
 6216            cx: &mut App,
 6217        ) -> SerializedPaneGroup {
 6218            match pane_group {
 6219                Member::Axis(PaneAxis {
 6220                    axis,
 6221                    members,
 6222                    flexes,
 6223                    bounding_boxes: _,
 6224                }) => SerializedPaneGroup::Group {
 6225                    axis: SerializedAxis(*axis),
 6226                    children: members
 6227                        .iter()
 6228                        .map(|member| build_serialized_pane_group(member, window, cx))
 6229                        .collect::<Vec<_>>(),
 6230                    flexes: Some(flexes.lock().clone()),
 6231                },
 6232                Member::Pane(pane_handle) => {
 6233                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6234                }
 6235            }
 6236        }
 6237
 6238        fn build_serialized_docks(
 6239            this: &Workspace,
 6240            window: &mut Window,
 6241            cx: &mut App,
 6242        ) -> DockStructure {
 6243            this.capture_dock_state(window, cx)
 6244        }
 6245
 6246        match self.workspace_location(cx) {
 6247            WorkspaceLocation::Location(location, paths) => {
 6248                let breakpoints = self.project.update(cx, |project, cx| {
 6249                    project
 6250                        .breakpoint_store()
 6251                        .read(cx)
 6252                        .all_source_breakpoints(cx)
 6253                });
 6254                let user_toolchains = self
 6255                    .project
 6256                    .read(cx)
 6257                    .user_toolchains(cx)
 6258                    .unwrap_or_default();
 6259
 6260                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6261                let docks = build_serialized_docks(self, window, cx);
 6262                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6263
 6264                let serialized_workspace = SerializedWorkspace {
 6265                    id: database_id,
 6266                    location,
 6267                    paths,
 6268                    center_group,
 6269                    window_bounds,
 6270                    display: Default::default(),
 6271                    docks,
 6272                    centered_layout: self.centered_layout,
 6273                    session_id: self.session_id.clone(),
 6274                    breakpoints,
 6275                    window_id: Some(window.window_handle().window_id().as_u64()),
 6276                    user_toolchains,
 6277                };
 6278
 6279                let db = WorkspaceDb::global(cx);
 6280                window.spawn(cx, async move |_| {
 6281                    db.save_workspace(serialized_workspace).await;
 6282                })
 6283            }
 6284            WorkspaceLocation::DetachFromSession => {
 6285                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6286                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6287                // Save dock state for empty local workspaces
 6288                let docks = build_serialized_docks(self, window, cx);
 6289                let db = WorkspaceDb::global(cx);
 6290                let kvp = db::kvp::KeyValueStore::global(cx);
 6291                window.spawn(cx, async move |_| {
 6292                    db.set_window_open_status(
 6293                        database_id,
 6294                        window_bounds,
 6295                        display.unwrap_or_default(),
 6296                    )
 6297                    .await
 6298                    .log_err();
 6299                    db.set_session_id(database_id, None).await.log_err();
 6300                    persistence::write_default_dock_state(&kvp, docks)
 6301                        .await
 6302                        .log_err();
 6303                })
 6304            }
 6305            WorkspaceLocation::None => {
 6306                // Save dock state for empty non-local workspaces
 6307                let docks = build_serialized_docks(self, window, cx);
 6308                let kvp = db::kvp::KeyValueStore::global(cx);
 6309                window.spawn(cx, async move |_| {
 6310                    persistence::write_default_dock_state(&kvp, docks)
 6311                        .await
 6312                        .log_err();
 6313                })
 6314            }
 6315        }
 6316    }
 6317
 6318    fn has_any_items_open(&self, cx: &App) -> bool {
 6319        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6320    }
 6321
 6322    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6323        let paths = PathList::new(&self.root_paths(cx));
 6324        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6325            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6326        } else if self.project.read(cx).is_local() {
 6327            if !paths.is_empty() || self.has_any_items_open(cx) {
 6328                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6329            } else {
 6330                WorkspaceLocation::DetachFromSession
 6331            }
 6332        } else {
 6333            WorkspaceLocation::None
 6334        }
 6335    }
 6336
 6337    fn update_history(&self, cx: &mut App) {
 6338        let Some(id) = self.database_id() else {
 6339            return;
 6340        };
 6341        if !self.project.read(cx).is_local() {
 6342            return;
 6343        }
 6344        if let Some(manager) = HistoryManager::global(cx) {
 6345            let paths = PathList::new(&self.root_paths(cx));
 6346            manager.update(cx, |this, cx| {
 6347                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6348            });
 6349        }
 6350    }
 6351
 6352    async fn serialize_items(
 6353        this: &WeakEntity<Self>,
 6354        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6355        cx: &mut AsyncWindowContext,
 6356    ) -> Result<()> {
 6357        const CHUNK_SIZE: usize = 200;
 6358
 6359        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6360
 6361        while let Some(items_received) = serializable_items.next().await {
 6362            let unique_items =
 6363                items_received
 6364                    .into_iter()
 6365                    .fold(HashMap::default(), |mut acc, item| {
 6366                        acc.entry(item.item_id()).or_insert(item);
 6367                        acc
 6368                    });
 6369
 6370            // We use into_iter() here so that the references to the items are moved into
 6371            // the tasks and not kept alive while we're sleeping.
 6372            for (_, item) in unique_items.into_iter() {
 6373                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6374                    item.serialize(workspace, false, window, cx)
 6375                }) {
 6376                    cx.background_spawn(async move { task.await.log_err() })
 6377                        .detach();
 6378                }
 6379            }
 6380
 6381            cx.background_executor()
 6382                .timer(SERIALIZATION_THROTTLE_TIME)
 6383                .await;
 6384        }
 6385
 6386        Ok(())
 6387    }
 6388
 6389    pub(crate) fn enqueue_item_serialization(
 6390        &mut self,
 6391        item: Box<dyn SerializableItemHandle>,
 6392    ) -> Result<()> {
 6393        self.serializable_items_tx
 6394            .unbounded_send(item)
 6395            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6396    }
 6397
 6398    pub(crate) fn load_workspace(
 6399        serialized_workspace: SerializedWorkspace,
 6400        paths_to_open: Vec<Option<ProjectPath>>,
 6401        window: &mut Window,
 6402        cx: &mut Context<Workspace>,
 6403    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6404        cx.spawn_in(window, async move |workspace, cx| {
 6405            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6406
 6407            let mut center_group = None;
 6408            let mut center_items = None;
 6409
 6410            // Traverse the splits tree and add to things
 6411            if let Some((group, active_pane, items)) = serialized_workspace
 6412                .center_group
 6413                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6414                .await
 6415            {
 6416                center_items = Some(items);
 6417                center_group = Some((group, active_pane))
 6418            }
 6419
 6420            let mut items_by_project_path = HashMap::default();
 6421            let mut item_ids_by_kind = HashMap::default();
 6422            let mut all_deserialized_items = Vec::default();
 6423            cx.update(|_, cx| {
 6424                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6425                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6426                        item_ids_by_kind
 6427                            .entry(serializable_item_handle.serialized_item_kind())
 6428                            .or_insert(Vec::new())
 6429                            .push(item.item_id().as_u64() as ItemId);
 6430                    }
 6431
 6432                    if let Some(project_path) = item.project_path(cx) {
 6433                        items_by_project_path.insert(project_path, item.clone());
 6434                    }
 6435                    all_deserialized_items.push(item);
 6436                }
 6437            })?;
 6438
 6439            let opened_items = paths_to_open
 6440                .into_iter()
 6441                .map(|path_to_open| {
 6442                    path_to_open
 6443                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6444                })
 6445                .collect::<Vec<_>>();
 6446
 6447            // Remove old panes from workspace panes list
 6448            workspace.update_in(cx, |workspace, window, cx| {
 6449                if let Some((center_group, active_pane)) = center_group {
 6450                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6451
 6452                    // Swap workspace center group
 6453                    workspace.center = PaneGroup::with_root(center_group);
 6454                    workspace.center.set_is_center(true);
 6455                    workspace.center.mark_positions(cx);
 6456
 6457                    if let Some(active_pane) = active_pane {
 6458                        workspace.set_active_pane(&active_pane, window, cx);
 6459                        cx.focus_self(window);
 6460                    } else {
 6461                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6462                    }
 6463                }
 6464
 6465                let docks = serialized_workspace.docks;
 6466
 6467                for (dock, serialized_dock) in [
 6468                    (&mut workspace.right_dock, docks.right),
 6469                    (&mut workspace.left_dock, docks.left),
 6470                    (&mut workspace.bottom_dock, docks.bottom),
 6471                ]
 6472                .iter_mut()
 6473                {
 6474                    dock.update(cx, |dock, cx| {
 6475                        dock.serialized_dock = Some(serialized_dock.clone());
 6476                        dock.restore_state(window, cx);
 6477                    });
 6478                }
 6479
 6480                cx.notify();
 6481            })?;
 6482
 6483            let _ = project
 6484                .update(cx, |project, cx| {
 6485                    project
 6486                        .breakpoint_store()
 6487                        .update(cx, |breakpoint_store, cx| {
 6488                            breakpoint_store
 6489                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6490                        })
 6491                })
 6492                .await;
 6493
 6494            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6495            // after loading the items, we might have different items and in order to avoid
 6496            // the database filling up, we delete items that haven't been loaded now.
 6497            //
 6498            // The items that have been loaded, have been saved after they've been added to the workspace.
 6499            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6500                item_ids_by_kind
 6501                    .into_iter()
 6502                    .map(|(item_kind, loaded_items)| {
 6503                        SerializableItemRegistry::cleanup(
 6504                            item_kind,
 6505                            serialized_workspace.id,
 6506                            loaded_items,
 6507                            window,
 6508                            cx,
 6509                        )
 6510                        .log_err()
 6511                    })
 6512                    .collect::<Vec<_>>()
 6513            })?;
 6514
 6515            futures::future::join_all(clean_up_tasks).await;
 6516
 6517            workspace
 6518                .update_in(cx, |workspace, window, cx| {
 6519                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6520                    workspace.serialize_workspace_internal(window, cx).detach();
 6521
 6522                    // Ensure that we mark the window as edited if we did load dirty items
 6523                    workspace.update_window_edited(window, cx);
 6524                })
 6525                .ok();
 6526
 6527            Ok(opened_items)
 6528        })
 6529    }
 6530
 6531    pub fn key_context(&self, cx: &App) -> KeyContext {
 6532        let mut context = KeyContext::new_with_defaults();
 6533        context.add("Workspace");
 6534        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6535        if let Some(status) = self
 6536            .debugger_provider
 6537            .as_ref()
 6538            .and_then(|provider| provider.active_thread_state(cx))
 6539        {
 6540            match status {
 6541                ThreadStatus::Running | ThreadStatus::Stepping => {
 6542                    context.add("debugger_running");
 6543                }
 6544                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6545                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6546            }
 6547        }
 6548
 6549        if self.left_dock.read(cx).is_open() {
 6550            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6551                context.set("left_dock", active_panel.panel_key());
 6552            }
 6553        }
 6554
 6555        if self.right_dock.read(cx).is_open() {
 6556            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6557                context.set("right_dock", active_panel.panel_key());
 6558            }
 6559        }
 6560
 6561        if self.bottom_dock.read(cx).is_open() {
 6562            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6563                context.set("bottom_dock", active_panel.panel_key());
 6564            }
 6565        }
 6566
 6567        context
 6568    }
 6569
 6570    /// Multiworkspace uses this to add workspace action handling to itself
 6571    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6572        self.add_workspace_actions_listeners(div, window, cx)
 6573            .on_action(cx.listener(
 6574                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6575                    for action in &action_sequence.0 {
 6576                        window.dispatch_action(action.boxed_clone(), cx);
 6577                    }
 6578                },
 6579            ))
 6580            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6581            .on_action(cx.listener(Self::close_all_items_and_panes))
 6582            .on_action(cx.listener(Self::close_item_in_all_panes))
 6583            .on_action(cx.listener(Self::save_all))
 6584            .on_action(cx.listener(Self::send_keystrokes))
 6585            .on_action(cx.listener(Self::add_folder_to_project))
 6586            .on_action(cx.listener(Self::follow_next_collaborator))
 6587            .on_action(cx.listener(Self::activate_pane_at_index))
 6588            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6589            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6590            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6591            .on_action(cx.listener(Self::toggle_theme_mode))
 6592            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6593                let pane = workspace.active_pane().clone();
 6594                workspace.unfollow_in_pane(&pane, window, cx);
 6595            }))
 6596            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6597                workspace
 6598                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6599                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6600            }))
 6601            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6602                workspace
 6603                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6604                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6605            }))
 6606            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6607                workspace
 6608                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6609                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6610            }))
 6611            .on_action(
 6612                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6613                    workspace.activate_previous_pane(window, cx)
 6614                }),
 6615            )
 6616            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6617                workspace.activate_next_pane(window, cx)
 6618            }))
 6619            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6620                workspace.activate_last_pane(window, cx)
 6621            }))
 6622            .on_action(
 6623                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6624                    workspace.activate_next_window(cx)
 6625                }),
 6626            )
 6627            .on_action(
 6628                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6629                    workspace.activate_previous_window(cx)
 6630                }),
 6631            )
 6632            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6633                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6634            }))
 6635            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6636                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6637            }))
 6638            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6639                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6640            }))
 6641            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6642                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6643            }))
 6644            .on_action(cx.listener(
 6645                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6646                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6647                },
 6648            ))
 6649            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6650                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6651            }))
 6652            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6653                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6654            }))
 6655            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6656                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6657            }))
 6658            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6659                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6660            }))
 6661            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6662                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6663                    SplitDirection::Down,
 6664                    SplitDirection::Up,
 6665                    SplitDirection::Right,
 6666                    SplitDirection::Left,
 6667                ];
 6668                for dir in DIRECTION_PRIORITY {
 6669                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6670                        workspace.swap_pane_in_direction(dir, cx);
 6671                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6672                        break;
 6673                    }
 6674                }
 6675            }))
 6676            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6677                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6678            }))
 6679            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6680                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6681            }))
 6682            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6683                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6684            }))
 6685            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6686                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6687            }))
 6688            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6689                this.toggle_dock(DockPosition::Left, window, cx);
 6690            }))
 6691            .on_action(cx.listener(
 6692                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6693                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6694                },
 6695            ))
 6696            .on_action(cx.listener(
 6697                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6698                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6699                },
 6700            ))
 6701            .on_action(cx.listener(
 6702                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6703                    if !workspace.close_active_dock(window, cx) {
 6704                        cx.propagate();
 6705                    }
 6706                },
 6707            ))
 6708            .on_action(
 6709                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6710                    workspace.close_all_docks(window, cx);
 6711                }),
 6712            )
 6713            .on_action(cx.listener(Self::toggle_all_docks))
 6714            .on_action(cx.listener(
 6715                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6716                    workspace.clear_all_notifications(cx);
 6717                },
 6718            ))
 6719            .on_action(cx.listener(
 6720                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6721                    workspace.clear_navigation_history(window, cx);
 6722                },
 6723            ))
 6724            .on_action(cx.listener(
 6725                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6726                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6727                        workspace.suppress_notification(&notification_id, cx);
 6728                    }
 6729                },
 6730            ))
 6731            .on_action(cx.listener(
 6732                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6733                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6734                },
 6735            ))
 6736            .on_action(
 6737                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6738                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6739                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6740                            trusted_worktrees.clear_trusted_paths()
 6741                        });
 6742                        let db = WorkspaceDb::global(cx);
 6743                        cx.spawn(async move |_, cx| {
 6744                            if db.clear_trusted_worktrees().await.log_err().is_some() {
 6745                                cx.update(|cx| reload(cx));
 6746                            }
 6747                        })
 6748                        .detach();
 6749                    }
 6750                }),
 6751            )
 6752            .on_action(cx.listener(
 6753                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 6754                    workspace.reopen_closed_item(window, cx).detach();
 6755                },
 6756            ))
 6757            .on_action(cx.listener(
 6758                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 6759                    for dock in workspace.all_docks() {
 6760                        if dock.focus_handle(cx).contains_focused(window, cx) {
 6761                            let Some(panel) = dock.read(cx).active_panel() else {
 6762                                return;
 6763                            };
 6764
 6765                            // Set to `None`, then the size will fall back to the default.
 6766                            panel.clone().set_size(None, window, cx);
 6767
 6768                            return;
 6769                        }
 6770                    }
 6771                },
 6772            ))
 6773            .on_action(cx.listener(
 6774                |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
 6775                    for dock in workspace.all_docks() {
 6776                        if let Some(panel) = dock.read(cx).visible_panel() {
 6777                            // Set to `None`, then the size will fall back to the default.
 6778                            panel.clone().set_size(None, window, cx);
 6779                        }
 6780                    }
 6781                },
 6782            ))
 6783            .on_action(cx.listener(
 6784                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 6785                    adjust_active_dock_size_by_px(
 6786                        px_with_ui_font_fallback(act.px, cx),
 6787                        workspace,
 6788                        window,
 6789                        cx,
 6790                    );
 6791                },
 6792            ))
 6793            .on_action(cx.listener(
 6794                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 6795                    adjust_active_dock_size_by_px(
 6796                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6797                        workspace,
 6798                        window,
 6799                        cx,
 6800                    );
 6801                },
 6802            ))
 6803            .on_action(cx.listener(
 6804                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 6805                    adjust_open_docks_size_by_px(
 6806                        px_with_ui_font_fallback(act.px, cx),
 6807                        workspace,
 6808                        window,
 6809                        cx,
 6810                    );
 6811                },
 6812            ))
 6813            .on_action(cx.listener(
 6814                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 6815                    adjust_open_docks_size_by_px(
 6816                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6817                        workspace,
 6818                        window,
 6819                        cx,
 6820                    );
 6821                },
 6822            ))
 6823            .on_action(cx.listener(Workspace::toggle_centered_layout))
 6824            .on_action(cx.listener(
 6825                |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
 6826                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6827                        let dock = active_dock.read(cx);
 6828                        if let Some(active_panel) = dock.active_panel() {
 6829                            if active_panel.pane(cx).is_none() {
 6830                                let mut recent_pane: Option<Entity<Pane>> = None;
 6831                                let mut recent_timestamp = 0;
 6832                                for pane_handle in workspace.panes() {
 6833                                    let pane = pane_handle.read(cx);
 6834                                    for entry in pane.activation_history() {
 6835                                        if entry.timestamp > recent_timestamp {
 6836                                            recent_timestamp = entry.timestamp;
 6837                                            recent_pane = Some(pane_handle.clone());
 6838                                        }
 6839                                    }
 6840                                }
 6841
 6842                                if let Some(pane) = recent_pane {
 6843                                    pane.update(cx, |pane, cx| {
 6844                                        let current_index = pane.active_item_index();
 6845                                        let items_len = pane.items_len();
 6846                                        if items_len > 0 {
 6847                                            let next_index = if current_index + 1 < items_len {
 6848                                                current_index + 1
 6849                                            } else {
 6850                                                0
 6851                                            };
 6852                                            pane.activate_item(
 6853                                                next_index, false, false, window, cx,
 6854                                            );
 6855                                        }
 6856                                    });
 6857                                    return;
 6858                                }
 6859                            }
 6860                        }
 6861                    }
 6862                    cx.propagate();
 6863                },
 6864            ))
 6865            .on_action(cx.listener(
 6866                |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
 6867                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6868                        let dock = active_dock.read(cx);
 6869                        if let Some(active_panel) = dock.active_panel() {
 6870                            if active_panel.pane(cx).is_none() {
 6871                                let mut recent_pane: Option<Entity<Pane>> = None;
 6872                                let mut recent_timestamp = 0;
 6873                                for pane_handle in workspace.panes() {
 6874                                    let pane = pane_handle.read(cx);
 6875                                    for entry in pane.activation_history() {
 6876                                        if entry.timestamp > recent_timestamp {
 6877                                            recent_timestamp = entry.timestamp;
 6878                                            recent_pane = Some(pane_handle.clone());
 6879                                        }
 6880                                    }
 6881                                }
 6882
 6883                                if let Some(pane) = recent_pane {
 6884                                    pane.update(cx, |pane, cx| {
 6885                                        let current_index = pane.active_item_index();
 6886                                        let items_len = pane.items_len();
 6887                                        if items_len > 0 {
 6888                                            let prev_index = if current_index > 0 {
 6889                                                current_index - 1
 6890                                            } else {
 6891                                                items_len.saturating_sub(1)
 6892                                            };
 6893                                            pane.activate_item(
 6894                                                prev_index, false, false, window, cx,
 6895                                            );
 6896                                        }
 6897                                    });
 6898                                    return;
 6899                                }
 6900                            }
 6901                        }
 6902                    }
 6903                    cx.propagate();
 6904                },
 6905            ))
 6906            .on_action(cx.listener(
 6907                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 6908                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6909                        let dock = active_dock.read(cx);
 6910                        if let Some(active_panel) = dock.active_panel() {
 6911                            if active_panel.pane(cx).is_none() {
 6912                                let active_pane = workspace.active_pane().clone();
 6913                                active_pane.update(cx, |pane, cx| {
 6914                                    pane.close_active_item(action, window, cx)
 6915                                        .detach_and_log_err(cx);
 6916                                });
 6917                                return;
 6918                            }
 6919                        }
 6920                    }
 6921                    cx.propagate();
 6922                },
 6923            ))
 6924            .on_action(
 6925                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 6926                    let pane = workspace.active_pane().clone();
 6927                    if let Some(item) = pane.read(cx).active_item() {
 6928                        item.toggle_read_only(window, cx);
 6929                    }
 6930                }),
 6931            )
 6932            .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
 6933                workspace.focus_center_pane(window, cx);
 6934            }))
 6935            .on_action(cx.listener(Workspace::cancel))
 6936    }
 6937
 6938    #[cfg(any(test, feature = "test-support"))]
 6939    pub fn set_random_database_id(&mut self) {
 6940        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 6941    }
 6942
 6943    #[cfg(any(test, feature = "test-support"))]
 6944    pub(crate) fn test_new(
 6945        project: Entity<Project>,
 6946        window: &mut Window,
 6947        cx: &mut Context<Self>,
 6948    ) -> Self {
 6949        use node_runtime::NodeRuntime;
 6950        use session::Session;
 6951
 6952        let client = project.read(cx).client();
 6953        let user_store = project.read(cx).user_store();
 6954        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 6955        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 6956        window.activate_window();
 6957        let app_state = Arc::new(AppState {
 6958            languages: project.read(cx).languages().clone(),
 6959            workspace_store,
 6960            client,
 6961            user_store,
 6962            fs: project.read(cx).fs().clone(),
 6963            build_window_options: |_, _| Default::default(),
 6964            node_runtime: NodeRuntime::unavailable(),
 6965            session,
 6966        });
 6967        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 6968        workspace
 6969            .active_pane
 6970            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6971        workspace
 6972    }
 6973
 6974    pub fn register_action<A: Action>(
 6975        &mut self,
 6976        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 6977    ) -> &mut Self {
 6978        let callback = Arc::new(callback);
 6979
 6980        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 6981            let callback = callback.clone();
 6982            div.on_action(cx.listener(move |workspace, event, window, cx| {
 6983                (callback)(workspace, event, window, cx)
 6984            }))
 6985        }));
 6986        self
 6987    }
 6988    pub fn register_action_renderer(
 6989        &mut self,
 6990        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 6991    ) -> &mut Self {
 6992        self.workspace_actions.push(Box::new(callback));
 6993        self
 6994    }
 6995
 6996    fn add_workspace_actions_listeners(
 6997        &self,
 6998        mut div: Div,
 6999        window: &mut Window,
 7000        cx: &mut Context<Self>,
 7001    ) -> Div {
 7002        for action in self.workspace_actions.iter() {
 7003            div = (action)(div, self, window, cx)
 7004        }
 7005        div
 7006    }
 7007
 7008    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 7009        self.modal_layer.read(cx).has_active_modal()
 7010    }
 7011
 7012    pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
 7013        self.modal_layer
 7014            .read(cx)
 7015            .is_active_modal_command_palette(cx)
 7016    }
 7017
 7018    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7019        self.modal_layer.read(cx).active_modal()
 7020    }
 7021
 7022    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7023    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7024    /// If no modal is active, the new modal will be shown.
 7025    ///
 7026    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7027    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7028    /// will not be shown.
 7029    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7030    where
 7031        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7032    {
 7033        self.modal_layer.update(cx, |modal_layer, cx| {
 7034            modal_layer.toggle_modal(window, cx, build)
 7035        })
 7036    }
 7037
 7038    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7039        self.modal_layer
 7040            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7041    }
 7042
 7043    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7044        self.toast_layer
 7045            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7046    }
 7047
 7048    pub fn toggle_centered_layout(
 7049        &mut self,
 7050        _: &ToggleCenteredLayout,
 7051        _: &mut Window,
 7052        cx: &mut Context<Self>,
 7053    ) {
 7054        self.centered_layout = !self.centered_layout;
 7055        if let Some(database_id) = self.database_id() {
 7056            let db = WorkspaceDb::global(cx);
 7057            let centered_layout = self.centered_layout;
 7058            cx.background_spawn(async move {
 7059                db.set_centered_layout(database_id, centered_layout).await
 7060            })
 7061            .detach_and_log_err(cx);
 7062        }
 7063        cx.notify();
 7064    }
 7065
 7066    fn adjust_padding(padding: Option<f32>) -> f32 {
 7067        padding
 7068            .unwrap_or(CenteredPaddingSettings::default().0)
 7069            .clamp(
 7070                CenteredPaddingSettings::MIN_PADDING,
 7071                CenteredPaddingSettings::MAX_PADDING,
 7072            )
 7073    }
 7074
 7075    fn render_dock(
 7076        &self,
 7077        position: DockPosition,
 7078        dock: &Entity<Dock>,
 7079        window: &mut Window,
 7080        cx: &mut App,
 7081    ) -> Option<Div> {
 7082        if self.zoomed_position == Some(position) {
 7083            return None;
 7084        }
 7085
 7086        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7087            let pane = panel.pane(cx)?;
 7088            let follower_states = &self.follower_states;
 7089            leader_border_for_pane(follower_states, &pane, window, cx)
 7090        });
 7091
 7092        Some(
 7093            div()
 7094                .flex()
 7095                .flex_none()
 7096                .overflow_hidden()
 7097                .child(dock.clone())
 7098                .children(leader_border),
 7099        )
 7100    }
 7101
 7102    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7103        window
 7104            .root::<MultiWorkspace>()
 7105            .flatten()
 7106            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7107    }
 7108
 7109    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7110        self.zoomed.as_ref()
 7111    }
 7112
 7113    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7114        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7115            return;
 7116        };
 7117        let windows = cx.windows();
 7118        let next_window =
 7119            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7120                || {
 7121                    windows
 7122                        .iter()
 7123                        .cycle()
 7124                        .skip_while(|window| window.window_id() != current_window_id)
 7125                        .nth(1)
 7126                },
 7127            );
 7128
 7129        if let Some(window) = next_window {
 7130            window
 7131                .update(cx, |_, window, _| window.activate_window())
 7132                .ok();
 7133        }
 7134    }
 7135
 7136    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7137        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7138            return;
 7139        };
 7140        let windows = cx.windows();
 7141        let prev_window =
 7142            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7143                || {
 7144                    windows
 7145                        .iter()
 7146                        .rev()
 7147                        .cycle()
 7148                        .skip_while(|window| window.window_id() != current_window_id)
 7149                        .nth(1)
 7150                },
 7151            );
 7152
 7153        if let Some(window) = prev_window {
 7154            window
 7155                .update(cx, |_, window, _| window.activate_window())
 7156                .ok();
 7157        }
 7158    }
 7159
 7160    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7161        if cx.stop_active_drag(window) {
 7162        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7163            dismiss_app_notification(&notification_id, cx);
 7164        } else {
 7165            cx.propagate();
 7166        }
 7167    }
 7168
 7169    fn adjust_dock_size_by_px(
 7170        &mut self,
 7171        panel_size: Pixels,
 7172        dock_pos: DockPosition,
 7173        px: Pixels,
 7174        window: &mut Window,
 7175        cx: &mut Context<Self>,
 7176    ) {
 7177        match dock_pos {
 7178            DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
 7179            DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
 7180            DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
 7181        }
 7182    }
 7183
 7184    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7185        let workspace_width = self.bounds.size.width;
 7186        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7187
 7188        self.right_dock.read_with(cx, |right_dock, cx| {
 7189            let right_dock_size = right_dock
 7190                .active_panel_size(window, cx)
 7191                .unwrap_or(Pixels::ZERO);
 7192            if right_dock_size + size > workspace_width {
 7193                size = workspace_width - right_dock_size
 7194            }
 7195        });
 7196
 7197        self.left_dock.update(cx, |left_dock, cx| {
 7198            if WorkspaceSettings::get_global(cx)
 7199                .resize_all_panels_in_dock
 7200                .contains(&DockPosition::Left)
 7201            {
 7202                left_dock.resize_all_panels(Some(size), window, cx);
 7203            } else {
 7204                left_dock.resize_active_panel(Some(size), window, cx);
 7205            }
 7206        });
 7207    }
 7208
 7209    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7210        let workspace_width = self.bounds.size.width;
 7211        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7212        self.left_dock.read_with(cx, |left_dock, cx| {
 7213            let left_dock_size = left_dock
 7214                .active_panel_size(window, cx)
 7215                .unwrap_or(Pixels::ZERO);
 7216            if left_dock_size + size > workspace_width {
 7217                size = workspace_width - left_dock_size
 7218            }
 7219        });
 7220        self.right_dock.update(cx, |right_dock, cx| {
 7221            if WorkspaceSettings::get_global(cx)
 7222                .resize_all_panels_in_dock
 7223                .contains(&DockPosition::Right)
 7224            {
 7225                right_dock.resize_all_panels(Some(size), window, cx);
 7226            } else {
 7227                right_dock.resize_active_panel(Some(size), window, cx);
 7228            }
 7229        });
 7230    }
 7231
 7232    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7233        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7234        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7235            if WorkspaceSettings::get_global(cx)
 7236                .resize_all_panels_in_dock
 7237                .contains(&DockPosition::Bottom)
 7238            {
 7239                bottom_dock.resize_all_panels(Some(size), window, cx);
 7240            } else {
 7241                bottom_dock.resize_active_panel(Some(size), window, cx);
 7242            }
 7243        });
 7244    }
 7245
 7246    fn toggle_edit_predictions_all_files(
 7247        &mut self,
 7248        _: &ToggleEditPrediction,
 7249        _window: &mut Window,
 7250        cx: &mut Context<Self>,
 7251    ) {
 7252        let fs = self.project().read(cx).fs().clone();
 7253        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7254        update_settings_file(fs, cx, move |file, _| {
 7255            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7256        });
 7257    }
 7258
 7259    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7260        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7261        let next_mode = match current_mode {
 7262            Some(theme::ThemeAppearanceMode::Light) => theme::ThemeAppearanceMode::Dark,
 7263            Some(theme::ThemeAppearanceMode::Dark) => theme::ThemeAppearanceMode::Light,
 7264            Some(theme::ThemeAppearanceMode::System) | None => match cx.theme().appearance() {
 7265                theme::Appearance::Light => theme::ThemeAppearanceMode::Dark,
 7266                theme::Appearance::Dark => theme::ThemeAppearanceMode::Light,
 7267            },
 7268        };
 7269
 7270        let fs = self.project().read(cx).fs().clone();
 7271        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7272            theme::set_mode(settings, next_mode);
 7273        });
 7274    }
 7275
 7276    pub fn show_worktree_trust_security_modal(
 7277        &mut self,
 7278        toggle: bool,
 7279        window: &mut Window,
 7280        cx: &mut Context<Self>,
 7281    ) {
 7282        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7283            if toggle {
 7284                security_modal.update(cx, |security_modal, cx| {
 7285                    security_modal.dismiss(cx);
 7286                })
 7287            } else {
 7288                security_modal.update(cx, |security_modal, cx| {
 7289                    security_modal.refresh_restricted_paths(cx);
 7290                });
 7291            }
 7292        } else {
 7293            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7294                .map(|trusted_worktrees| {
 7295                    trusted_worktrees
 7296                        .read(cx)
 7297                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7298                })
 7299                .unwrap_or(false);
 7300            if has_restricted_worktrees {
 7301                let project = self.project().read(cx);
 7302                let remote_host = project
 7303                    .remote_connection_options(cx)
 7304                    .map(RemoteHostLocation::from);
 7305                let worktree_store = project.worktree_store().downgrade();
 7306                self.toggle_modal(window, cx, |_, cx| {
 7307                    SecurityModal::new(worktree_store, remote_host, cx)
 7308                });
 7309            }
 7310        }
 7311    }
 7312}
 7313
 7314pub trait AnyActiveCall {
 7315    fn entity(&self) -> AnyEntity;
 7316    fn is_in_room(&self, _: &App) -> bool;
 7317    fn room_id(&self, _: &App) -> Option<u64>;
 7318    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7319    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7320    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7321    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7322    fn is_sharing_project(&self, _: &App) -> bool;
 7323    fn has_remote_participants(&self, _: &App) -> bool;
 7324    fn local_participant_is_guest(&self, _: &App) -> bool;
 7325    fn client(&self, _: &App) -> Arc<Client>;
 7326    fn share_on_join(&self, _: &App) -> bool;
 7327    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7328    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7329    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7330    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7331    fn join_project(
 7332        &self,
 7333        _: u64,
 7334        _: Arc<LanguageRegistry>,
 7335        _: Arc<dyn Fs>,
 7336        _: &mut App,
 7337    ) -> Task<Result<Entity<Project>>>;
 7338    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7339    fn subscribe(
 7340        &self,
 7341        _: &mut Window,
 7342        _: &mut Context<Workspace>,
 7343        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7344    ) -> Subscription;
 7345    fn create_shared_screen(
 7346        &self,
 7347        _: PeerId,
 7348        _: &Entity<Pane>,
 7349        _: &mut Window,
 7350        _: &mut App,
 7351    ) -> Option<Entity<SharedScreen>>;
 7352}
 7353
 7354#[derive(Clone)]
 7355pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7356impl Global for GlobalAnyActiveCall {}
 7357
 7358impl GlobalAnyActiveCall {
 7359    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7360        cx.try_global()
 7361    }
 7362
 7363    pub(crate) fn global(cx: &App) -> &Self {
 7364        cx.global()
 7365    }
 7366}
 7367
 7368pub fn merge_conflict_notification_id() -> NotificationId {
 7369    struct MergeConflictNotification;
 7370    NotificationId::unique::<MergeConflictNotification>()
 7371}
 7372
 7373/// Workspace-local view of a remote participant's location.
 7374#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7375pub enum ParticipantLocation {
 7376    SharedProject { project_id: u64 },
 7377    UnsharedProject,
 7378    External,
 7379}
 7380
 7381impl ParticipantLocation {
 7382    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7383        match location
 7384            .and_then(|l| l.variant)
 7385            .context("participant location was not provided")?
 7386        {
 7387            proto::participant_location::Variant::SharedProject(project) => {
 7388                Ok(Self::SharedProject {
 7389                    project_id: project.id,
 7390                })
 7391            }
 7392            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7393            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7394        }
 7395    }
 7396}
 7397/// Workspace-local view of a remote collaborator's state.
 7398/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7399#[derive(Clone)]
 7400pub struct RemoteCollaborator {
 7401    pub user: Arc<User>,
 7402    pub peer_id: PeerId,
 7403    pub location: ParticipantLocation,
 7404    pub participant_index: ParticipantIndex,
 7405}
 7406
 7407pub enum ActiveCallEvent {
 7408    ParticipantLocationChanged { participant_id: PeerId },
 7409    RemoteVideoTracksChanged { participant_id: PeerId },
 7410}
 7411
 7412fn leader_border_for_pane(
 7413    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7414    pane: &Entity<Pane>,
 7415    _: &Window,
 7416    cx: &App,
 7417) -> Option<Div> {
 7418    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7419        if state.pane() == pane {
 7420            Some((*leader_id, state))
 7421        } else {
 7422            None
 7423        }
 7424    })?;
 7425
 7426    let mut leader_color = match leader_id {
 7427        CollaboratorId::PeerId(leader_peer_id) => {
 7428            let leader = GlobalAnyActiveCall::try_global(cx)?
 7429                .0
 7430                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7431
 7432            cx.theme()
 7433                .players()
 7434                .color_for_participant(leader.participant_index.0)
 7435                .cursor
 7436        }
 7437        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7438    };
 7439    leader_color.fade_out(0.3);
 7440    Some(
 7441        div()
 7442            .absolute()
 7443            .size_full()
 7444            .left_0()
 7445            .top_0()
 7446            .border_2()
 7447            .border_color(leader_color),
 7448    )
 7449}
 7450
 7451fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7452    ZED_WINDOW_POSITION
 7453        .zip(*ZED_WINDOW_SIZE)
 7454        .map(|(position, size)| Bounds {
 7455            origin: position,
 7456            size,
 7457        })
 7458}
 7459
 7460fn open_items(
 7461    serialized_workspace: Option<SerializedWorkspace>,
 7462    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7463    window: &mut Window,
 7464    cx: &mut Context<Workspace>,
 7465) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7466    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7467        Workspace::load_workspace(
 7468            serialized_workspace,
 7469            project_paths_to_open
 7470                .iter()
 7471                .map(|(_, project_path)| project_path)
 7472                .cloned()
 7473                .collect(),
 7474            window,
 7475            cx,
 7476        )
 7477    });
 7478
 7479    cx.spawn_in(window, async move |workspace, cx| {
 7480        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7481
 7482        if let Some(restored_items) = restored_items {
 7483            let restored_items = restored_items.await?;
 7484
 7485            let restored_project_paths = restored_items
 7486                .iter()
 7487                .filter_map(|item| {
 7488                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7489                        .ok()
 7490                        .flatten()
 7491                })
 7492                .collect::<HashSet<_>>();
 7493
 7494            for restored_item in restored_items {
 7495                opened_items.push(restored_item.map(Ok));
 7496            }
 7497
 7498            project_paths_to_open
 7499                .iter_mut()
 7500                .for_each(|(_, project_path)| {
 7501                    if let Some(project_path_to_open) = project_path
 7502                        && restored_project_paths.contains(project_path_to_open)
 7503                    {
 7504                        *project_path = None;
 7505                    }
 7506                });
 7507        } else {
 7508            for _ in 0..project_paths_to_open.len() {
 7509                opened_items.push(None);
 7510            }
 7511        }
 7512        assert!(opened_items.len() == project_paths_to_open.len());
 7513
 7514        let tasks =
 7515            project_paths_to_open
 7516                .into_iter()
 7517                .enumerate()
 7518                .map(|(ix, (abs_path, project_path))| {
 7519                    let workspace = workspace.clone();
 7520                    cx.spawn(async move |cx| {
 7521                        let file_project_path = project_path?;
 7522                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7523                            workspace.project().update(cx, |project, cx| {
 7524                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7525                            })
 7526                        });
 7527
 7528                        // We only want to open file paths here. If one of the items
 7529                        // here is a directory, it was already opened further above
 7530                        // with a `find_or_create_worktree`.
 7531                        if let Ok(task) = abs_path_task
 7532                            && task.await.is_none_or(|p| p.is_file())
 7533                        {
 7534                            return Some((
 7535                                ix,
 7536                                workspace
 7537                                    .update_in(cx, |workspace, window, cx| {
 7538                                        workspace.open_path(
 7539                                            file_project_path,
 7540                                            None,
 7541                                            true,
 7542                                            window,
 7543                                            cx,
 7544                                        )
 7545                                    })
 7546                                    .log_err()?
 7547                                    .await,
 7548                            ));
 7549                        }
 7550                        None
 7551                    })
 7552                });
 7553
 7554        let tasks = tasks.collect::<Vec<_>>();
 7555
 7556        let tasks = futures::future::join_all(tasks);
 7557        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7558            opened_items[ix] = Some(path_open_result);
 7559        }
 7560
 7561        Ok(opened_items)
 7562    })
 7563}
 7564
 7565#[derive(Clone)]
 7566enum ActivateInDirectionTarget {
 7567    Pane(Entity<Pane>),
 7568    Dock(Entity<Dock>),
 7569    Sidebar(FocusHandle),
 7570}
 7571
 7572fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7573    window
 7574        .update(cx, |multi_workspace, _, cx| {
 7575            let workspace = multi_workspace.workspace().clone();
 7576            workspace.update(cx, |workspace, cx| {
 7577                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7578                    struct DatabaseFailedNotification;
 7579
 7580                    workspace.show_notification(
 7581                        NotificationId::unique::<DatabaseFailedNotification>(),
 7582                        cx,
 7583                        |cx| {
 7584                            cx.new(|cx| {
 7585                                MessageNotification::new("Failed to load the database file.", cx)
 7586                                    .primary_message("File an Issue")
 7587                                    .primary_icon(IconName::Plus)
 7588                                    .primary_on_click(|window, cx| {
 7589                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7590                                    })
 7591                            })
 7592                        },
 7593                    );
 7594                }
 7595            });
 7596        })
 7597        .log_err();
 7598}
 7599
 7600fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7601    if val == 0 {
 7602        ThemeSettings::get_global(cx).ui_font_size(cx)
 7603    } else {
 7604        px(val as f32)
 7605    }
 7606}
 7607
 7608fn adjust_active_dock_size_by_px(
 7609    px: Pixels,
 7610    workspace: &mut Workspace,
 7611    window: &mut Window,
 7612    cx: &mut Context<Workspace>,
 7613) {
 7614    let Some(active_dock) = workspace
 7615        .all_docks()
 7616        .into_iter()
 7617        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7618    else {
 7619        return;
 7620    };
 7621    let dock = active_dock.read(cx);
 7622    let Some(panel_size) = dock.active_panel_size(window, cx) else {
 7623        return;
 7624    };
 7625    let dock_pos = dock.position();
 7626    workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
 7627}
 7628
 7629fn adjust_open_docks_size_by_px(
 7630    px: Pixels,
 7631    workspace: &mut Workspace,
 7632    window: &mut Window,
 7633    cx: &mut Context<Workspace>,
 7634) {
 7635    let docks = workspace
 7636        .all_docks()
 7637        .into_iter()
 7638        .filter_map(|dock| {
 7639            if dock.read(cx).is_open() {
 7640                let dock = dock.read(cx);
 7641                let panel_size = dock.active_panel_size(window, cx)?;
 7642                let dock_pos = dock.position();
 7643                Some((panel_size, dock_pos, px))
 7644            } else {
 7645                None
 7646            }
 7647        })
 7648        .collect::<Vec<_>>();
 7649
 7650    docks
 7651        .into_iter()
 7652        .for_each(|(panel_size, dock_pos, offset)| {
 7653            workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
 7654        });
 7655}
 7656
 7657impl Focusable for Workspace {
 7658    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7659        self.active_pane.focus_handle(cx)
 7660    }
 7661}
 7662
 7663#[derive(Clone)]
 7664struct DraggedDock(DockPosition);
 7665
 7666impl Render for DraggedDock {
 7667    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7668        gpui::Empty
 7669    }
 7670}
 7671
 7672impl Render for Workspace {
 7673    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 7674        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 7675        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 7676            log::info!("Rendered first frame");
 7677        }
 7678
 7679        let centered_layout = self.centered_layout
 7680            && self.center.panes().len() == 1
 7681            && self.active_item(cx).is_some();
 7682        let render_padding = |size| {
 7683            (size > 0.0).then(|| {
 7684                div()
 7685                    .h_full()
 7686                    .w(relative(size))
 7687                    .bg(cx.theme().colors().editor_background)
 7688                    .border_color(cx.theme().colors().pane_group_border)
 7689            })
 7690        };
 7691        let paddings = if centered_layout {
 7692            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 7693            (
 7694                render_padding(Self::adjust_padding(
 7695                    settings.left_padding.map(|padding| padding.0),
 7696                )),
 7697                render_padding(Self::adjust_padding(
 7698                    settings.right_padding.map(|padding| padding.0),
 7699                )),
 7700            )
 7701        } else {
 7702            (None, None)
 7703        };
 7704        let ui_font = theme::setup_ui_font(window, cx);
 7705
 7706        let theme = cx.theme().clone();
 7707        let colors = theme.colors();
 7708        let notification_entities = self
 7709            .notifications
 7710            .iter()
 7711            .map(|(_, notification)| notification.entity_id())
 7712            .collect::<Vec<_>>();
 7713        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 7714
 7715        div()
 7716            .relative()
 7717            .size_full()
 7718            .flex()
 7719            .flex_col()
 7720            .font(ui_font)
 7721            .gap_0()
 7722                .justify_start()
 7723                .items_start()
 7724                .text_color(colors.text)
 7725                .overflow_hidden()
 7726                .children(self.titlebar_item.clone())
 7727                .on_modifiers_changed(move |_, _, cx| {
 7728                    for &id in &notification_entities {
 7729                        cx.notify(id);
 7730                    }
 7731                })
 7732                .child(
 7733                    div()
 7734                        .size_full()
 7735                        .relative()
 7736                        .flex_1()
 7737                        .flex()
 7738                        .flex_col()
 7739                        .child(
 7740                            div()
 7741                                .id("workspace")
 7742                                .bg(colors.background)
 7743                                .relative()
 7744                                .flex_1()
 7745                                .w_full()
 7746                                .flex()
 7747                                .flex_col()
 7748                                .overflow_hidden()
 7749                                .border_t_1()
 7750                                .border_b_1()
 7751                                .border_color(colors.border)
 7752                                .child({
 7753                                    let this = cx.entity();
 7754                                    canvas(
 7755                                        move |bounds, window, cx| {
 7756                                            this.update(cx, |this, cx| {
 7757                                                let bounds_changed = this.bounds != bounds;
 7758                                                this.bounds = bounds;
 7759
 7760                                                if bounds_changed {
 7761                                                    this.left_dock.update(cx, |dock, cx| {
 7762                                                        dock.clamp_panel_size(
 7763                                                            bounds.size.width,
 7764                                                            window,
 7765                                                            cx,
 7766                                                        )
 7767                                                    });
 7768
 7769                                                    this.right_dock.update(cx, |dock, cx| {
 7770                                                        dock.clamp_panel_size(
 7771                                                            bounds.size.width,
 7772                                                            window,
 7773                                                            cx,
 7774                                                        )
 7775                                                    });
 7776
 7777                                                    this.bottom_dock.update(cx, |dock, cx| {
 7778                                                        dock.clamp_panel_size(
 7779                                                            bounds.size.height,
 7780                                                            window,
 7781                                                            cx,
 7782                                                        )
 7783                                                    });
 7784                                                }
 7785                                            })
 7786                                        },
 7787                                        |_, _, _, _| {},
 7788                                    )
 7789                                    .absolute()
 7790                                    .size_full()
 7791                                })
 7792                                .when(self.zoomed.is_none(), |this| {
 7793                                    this.on_drag_move(cx.listener(
 7794                                        move |workspace,
 7795                                              e: &DragMoveEvent<DraggedDock>,
 7796                                              window,
 7797                                              cx| {
 7798                                            if workspace.previous_dock_drag_coordinates
 7799                                                != Some(e.event.position)
 7800                                            {
 7801                                                workspace.previous_dock_drag_coordinates =
 7802                                                    Some(e.event.position);
 7803
 7804                                                match e.drag(cx).0 {
 7805                                                    DockPosition::Left => {
 7806                                                        workspace.resize_left_dock(
 7807                                                            e.event.position.x
 7808                                                                - workspace.bounds.left(),
 7809                                                            window,
 7810                                                            cx,
 7811                                                        );
 7812                                                    }
 7813                                                    DockPosition::Right => {
 7814                                                        workspace.resize_right_dock(
 7815                                                            workspace.bounds.right()
 7816                                                                - e.event.position.x,
 7817                                                            window,
 7818                                                            cx,
 7819                                                        );
 7820                                                    }
 7821                                                    DockPosition::Bottom => {
 7822                                                        workspace.resize_bottom_dock(
 7823                                                            workspace.bounds.bottom()
 7824                                                                - e.event.position.y,
 7825                                                            window,
 7826                                                            cx,
 7827                                                        );
 7828                                                    }
 7829                                                };
 7830                                                workspace.serialize_workspace(window, cx);
 7831                                            }
 7832                                        },
 7833                                    ))
 7834
 7835                                })
 7836                                .child({
 7837                                    match bottom_dock_layout {
 7838                                        BottomDockLayout::Full => div()
 7839                                            .flex()
 7840                                            .flex_col()
 7841                                            .h_full()
 7842                                            .child(
 7843                                                div()
 7844                                                    .flex()
 7845                                                    .flex_row()
 7846                                                    .flex_1()
 7847                                                    .overflow_hidden()
 7848                                                    .children(self.render_dock(
 7849                                                        DockPosition::Left,
 7850                                                        &self.left_dock,
 7851                                                        window,
 7852                                                        cx,
 7853                                                    ))
 7854
 7855                                                    .child(
 7856                                                        div()
 7857                                                            .flex()
 7858                                                            .flex_col()
 7859                                                            .flex_1()
 7860                                                            .overflow_hidden()
 7861                                                            .child(
 7862                                                                h_flex()
 7863                                                                    .flex_1()
 7864                                                                    .when_some(
 7865                                                                        paddings.0,
 7866                                                                        |this, p| {
 7867                                                                            this.child(
 7868                                                                                p.border_r_1(),
 7869                                                                            )
 7870                                                                        },
 7871                                                                    )
 7872                                                                    .child(self.center.render(
 7873                                                                        self.zoomed.as_ref(),
 7874                                                                        &PaneRenderContext {
 7875                                                                            follower_states:
 7876                                                                                &self.follower_states,
 7877                                                                            active_call: self.active_call(),
 7878                                                                            active_pane: &self.active_pane,
 7879                                                                            app_state: &self.app_state,
 7880                                                                            project: &self.project,
 7881                                                                            workspace: &self.weak_self,
 7882                                                                        },
 7883                                                                        window,
 7884                                                                        cx,
 7885                                                                    ))
 7886                                                                    .when_some(
 7887                                                                        paddings.1,
 7888                                                                        |this, p| {
 7889                                                                            this.child(
 7890                                                                                p.border_l_1(),
 7891                                                                            )
 7892                                                                        },
 7893                                                                    ),
 7894                                                            ),
 7895                                                    )
 7896
 7897                                                    .children(self.render_dock(
 7898                                                        DockPosition::Right,
 7899                                                        &self.right_dock,
 7900                                                        window,
 7901                                                        cx,
 7902                                                    )),
 7903                                            )
 7904                                            .child(div().w_full().children(self.render_dock(
 7905                                                DockPosition::Bottom,
 7906                                                &self.bottom_dock,
 7907                                                window,
 7908                                                cx
 7909                                            ))),
 7910
 7911                                        BottomDockLayout::LeftAligned => div()
 7912                                            .flex()
 7913                                            .flex_row()
 7914                                            .h_full()
 7915                                            .child(
 7916                                                div()
 7917                                                    .flex()
 7918                                                    .flex_col()
 7919                                                    .flex_1()
 7920                                                    .h_full()
 7921                                                    .child(
 7922                                                        div()
 7923                                                            .flex()
 7924                                                            .flex_row()
 7925                                                            .flex_1()
 7926                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 7927
 7928                                                            .child(
 7929                                                                div()
 7930                                                                    .flex()
 7931                                                                    .flex_col()
 7932                                                                    .flex_1()
 7933                                                                    .overflow_hidden()
 7934                                                                    .child(
 7935                                                                        h_flex()
 7936                                                                            .flex_1()
 7937                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7938                                                                            .child(self.center.render(
 7939                                                                                self.zoomed.as_ref(),
 7940                                                                                &PaneRenderContext {
 7941                                                                                    follower_states:
 7942                                                                                        &self.follower_states,
 7943                                                                                    active_call: self.active_call(),
 7944                                                                                    active_pane: &self.active_pane,
 7945                                                                                    app_state: &self.app_state,
 7946                                                                                    project: &self.project,
 7947                                                                                    workspace: &self.weak_self,
 7948                                                                                },
 7949                                                                                window,
 7950                                                                                cx,
 7951                                                                            ))
 7952                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7953                                                                    )
 7954                                                            )
 7955
 7956                                                    )
 7957                                                    .child(
 7958                                                        div()
 7959                                                            .w_full()
 7960                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7961                                                    ),
 7962                                            )
 7963                                            .children(self.render_dock(
 7964                                                DockPosition::Right,
 7965                                                &self.right_dock,
 7966                                                window,
 7967                                                cx,
 7968                                            )),
 7969                                        BottomDockLayout::RightAligned => div()
 7970                                            .flex()
 7971                                            .flex_row()
 7972                                            .h_full()
 7973                                            .children(self.render_dock(
 7974                                                DockPosition::Left,
 7975                                                &self.left_dock,
 7976                                                window,
 7977                                                cx,
 7978                                            ))
 7979
 7980                                            .child(
 7981                                                div()
 7982                                                    .flex()
 7983                                                    .flex_col()
 7984                                                    .flex_1()
 7985                                                    .h_full()
 7986                                                    .child(
 7987                                                        div()
 7988                                                            .flex()
 7989                                                            .flex_row()
 7990                                                            .flex_1()
 7991                                                            .child(
 7992                                                                div()
 7993                                                                    .flex()
 7994                                                                    .flex_col()
 7995                                                                    .flex_1()
 7996                                                                    .overflow_hidden()
 7997                                                                    .child(
 7998                                                                        h_flex()
 7999                                                                            .flex_1()
 8000                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8001                                                                            .child(self.center.render(
 8002                                                                                self.zoomed.as_ref(),
 8003                                                                                &PaneRenderContext {
 8004                                                                                    follower_states:
 8005                                                                                        &self.follower_states,
 8006                                                                                    active_call: self.active_call(),
 8007                                                                                    active_pane: &self.active_pane,
 8008                                                                                    app_state: &self.app_state,
 8009                                                                                    project: &self.project,
 8010                                                                                    workspace: &self.weak_self,
 8011                                                                                },
 8012                                                                                window,
 8013                                                                                cx,
 8014                                                                            ))
 8015                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8016                                                                    )
 8017                                                            )
 8018
 8019                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 8020                                                    )
 8021                                                    .child(
 8022                                                        div()
 8023                                                            .w_full()
 8024                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8025                                                    ),
 8026                                            ),
 8027                                        BottomDockLayout::Contained => div()
 8028                                            .flex()
 8029                                            .flex_row()
 8030                                            .h_full()
 8031                                            .children(self.render_dock(
 8032                                                DockPosition::Left,
 8033                                                &self.left_dock,
 8034                                                window,
 8035                                                cx,
 8036                                            ))
 8037
 8038                                            .child(
 8039                                                div()
 8040                                                    .flex()
 8041                                                    .flex_col()
 8042                                                    .flex_1()
 8043                                                    .overflow_hidden()
 8044                                                    .child(
 8045                                                        h_flex()
 8046                                                            .flex_1()
 8047                                                            .when_some(paddings.0, |this, p| {
 8048                                                                this.child(p.border_r_1())
 8049                                                            })
 8050                                                            .child(self.center.render(
 8051                                                                self.zoomed.as_ref(),
 8052                                                                &PaneRenderContext {
 8053                                                                    follower_states:
 8054                                                                        &self.follower_states,
 8055                                                                    active_call: self.active_call(),
 8056                                                                    active_pane: &self.active_pane,
 8057                                                                    app_state: &self.app_state,
 8058                                                                    project: &self.project,
 8059                                                                    workspace: &self.weak_self,
 8060                                                                },
 8061                                                                window,
 8062                                                                cx,
 8063                                                            ))
 8064                                                            .when_some(paddings.1, |this, p| {
 8065                                                                this.child(p.border_l_1())
 8066                                                            }),
 8067                                                    )
 8068                                                    .children(self.render_dock(
 8069                                                        DockPosition::Bottom,
 8070                                                        &self.bottom_dock,
 8071                                                        window,
 8072                                                        cx,
 8073                                                    )),
 8074                                            )
 8075
 8076                                            .children(self.render_dock(
 8077                                                DockPosition::Right,
 8078                                                &self.right_dock,
 8079                                                window,
 8080                                                cx,
 8081                                            )),
 8082                                    }
 8083                                })
 8084                                .children(self.zoomed.as_ref().and_then(|view| {
 8085                                    let zoomed_view = view.upgrade()?;
 8086                                    let div = div()
 8087                                        .occlude()
 8088                                        .absolute()
 8089                                        .overflow_hidden()
 8090                                        .border_color(colors.border)
 8091                                        .bg(colors.background)
 8092                                        .child(zoomed_view)
 8093                                        .inset_0()
 8094                                        .shadow_lg();
 8095
 8096                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8097                                       return Some(div);
 8098                                    }
 8099
 8100                                    Some(match self.zoomed_position {
 8101                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8102                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8103                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8104                                        None => {
 8105                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8106                                        }
 8107                                    })
 8108                                }))
 8109                                .children(self.render_notifications(window, cx)),
 8110                        )
 8111                        .when(self.status_bar_visible(cx), |parent| {
 8112                            parent.child(self.status_bar.clone())
 8113                        })
 8114                        .child(self.toast_layer.clone()),
 8115                )
 8116    }
 8117}
 8118
 8119impl WorkspaceStore {
 8120    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8121        Self {
 8122            workspaces: Default::default(),
 8123            _subscriptions: vec![
 8124                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8125                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8126            ],
 8127            client,
 8128        }
 8129    }
 8130
 8131    pub fn update_followers(
 8132        &self,
 8133        project_id: Option<u64>,
 8134        update: proto::update_followers::Variant,
 8135        cx: &App,
 8136    ) -> Option<()> {
 8137        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8138        let room_id = active_call.0.room_id(cx)?;
 8139        self.client
 8140            .send(proto::UpdateFollowers {
 8141                room_id,
 8142                project_id,
 8143                variant: Some(update),
 8144            })
 8145            .log_err()
 8146    }
 8147
 8148    pub async fn handle_follow(
 8149        this: Entity<Self>,
 8150        envelope: TypedEnvelope<proto::Follow>,
 8151        mut cx: AsyncApp,
 8152    ) -> Result<proto::FollowResponse> {
 8153        this.update(&mut cx, |this, cx| {
 8154            let follower = Follower {
 8155                project_id: envelope.payload.project_id,
 8156                peer_id: envelope.original_sender_id()?,
 8157            };
 8158
 8159            let mut response = proto::FollowResponse::default();
 8160
 8161            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8162                let Some(workspace) = weak_workspace.upgrade() else {
 8163                    return false;
 8164                };
 8165                window_handle
 8166                    .update(cx, |_, window, cx| {
 8167                        workspace.update(cx, |workspace, cx| {
 8168                            let handler_response =
 8169                                workspace.handle_follow(follower.project_id, window, cx);
 8170                            if let Some(active_view) = handler_response.active_view
 8171                                && workspace.project.read(cx).remote_id() == follower.project_id
 8172                            {
 8173                                response.active_view = Some(active_view)
 8174                            }
 8175                        });
 8176                    })
 8177                    .is_ok()
 8178            });
 8179
 8180            Ok(response)
 8181        })
 8182    }
 8183
 8184    async fn handle_update_followers(
 8185        this: Entity<Self>,
 8186        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8187        mut cx: AsyncApp,
 8188    ) -> Result<()> {
 8189        let leader_id = envelope.original_sender_id()?;
 8190        let update = envelope.payload;
 8191
 8192        this.update(&mut cx, |this, cx| {
 8193            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8194                let Some(workspace) = weak_workspace.upgrade() else {
 8195                    return false;
 8196                };
 8197                window_handle
 8198                    .update(cx, |_, window, cx| {
 8199                        workspace.update(cx, |workspace, cx| {
 8200                            let project_id = workspace.project.read(cx).remote_id();
 8201                            if update.project_id != project_id && update.project_id.is_some() {
 8202                                return;
 8203                            }
 8204                            workspace.handle_update_followers(
 8205                                leader_id,
 8206                                update.clone(),
 8207                                window,
 8208                                cx,
 8209                            );
 8210                        });
 8211                    })
 8212                    .is_ok()
 8213            });
 8214            Ok(())
 8215        })
 8216    }
 8217
 8218    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8219        self.workspaces.iter().map(|(_, weak)| weak)
 8220    }
 8221
 8222    pub fn workspaces_with_windows(
 8223        &self,
 8224    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8225        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8226    }
 8227}
 8228
 8229impl ViewId {
 8230    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8231        Ok(Self {
 8232            creator: message
 8233                .creator
 8234                .map(CollaboratorId::PeerId)
 8235                .context("creator is missing")?,
 8236            id: message.id,
 8237        })
 8238    }
 8239
 8240    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8241        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8242            Some(proto::ViewId {
 8243                creator: Some(peer_id),
 8244                id: self.id,
 8245            })
 8246        } else {
 8247            None
 8248        }
 8249    }
 8250}
 8251
 8252impl FollowerState {
 8253    fn pane(&self) -> &Entity<Pane> {
 8254        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8255    }
 8256}
 8257
 8258pub trait WorkspaceHandle {
 8259    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8260}
 8261
 8262impl WorkspaceHandle for Entity<Workspace> {
 8263    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8264        self.read(cx)
 8265            .worktrees(cx)
 8266            .flat_map(|worktree| {
 8267                let worktree_id = worktree.read(cx).id();
 8268                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8269                    worktree_id,
 8270                    path: f.path.clone(),
 8271                })
 8272            })
 8273            .collect::<Vec<_>>()
 8274    }
 8275}
 8276
 8277pub async fn last_opened_workspace_location(
 8278    db: &WorkspaceDb,
 8279    fs: &dyn fs::Fs,
 8280) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8281    db.last_workspace(fs)
 8282        .await
 8283        .log_err()
 8284        .flatten()
 8285        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8286}
 8287
 8288pub async fn last_session_workspace_locations(
 8289    db: &WorkspaceDb,
 8290    last_session_id: &str,
 8291    last_session_window_stack: Option<Vec<WindowId>>,
 8292    fs: &dyn fs::Fs,
 8293) -> Option<Vec<SessionWorkspace>> {
 8294    db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8295        .await
 8296        .log_err()
 8297}
 8298
 8299pub struct MultiWorkspaceRestoreResult {
 8300    pub window_handle: WindowHandle<MultiWorkspace>,
 8301    pub errors: Vec<anyhow::Error>,
 8302}
 8303
 8304pub async fn restore_multiworkspace(
 8305    multi_workspace: SerializedMultiWorkspace,
 8306    app_state: Arc<AppState>,
 8307    cx: &mut AsyncApp,
 8308) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8309    let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
 8310    let mut group_iter = workspaces.into_iter();
 8311    let first = group_iter
 8312        .next()
 8313        .context("window group must not be empty")?;
 8314
 8315    let window_handle = if first.paths.is_empty() {
 8316        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8317            .await?
 8318    } else {
 8319        let OpenResult { window, .. } = cx
 8320            .update(|cx| {
 8321                Workspace::new_local(
 8322                    first.paths.paths().to_vec(),
 8323                    app_state.clone(),
 8324                    None,
 8325                    None,
 8326                    None,
 8327                    true,
 8328                    cx,
 8329                )
 8330            })
 8331            .await?;
 8332        window
 8333    };
 8334
 8335    let mut errors = Vec::new();
 8336
 8337    for session_workspace in group_iter {
 8338        let error = if session_workspace.paths.is_empty() {
 8339            cx.update(|cx| {
 8340                open_workspace_by_id(
 8341                    session_workspace.workspace_id,
 8342                    app_state.clone(),
 8343                    Some(window_handle),
 8344                    cx,
 8345                )
 8346            })
 8347            .await
 8348            .err()
 8349        } else {
 8350            cx.update(|cx| {
 8351                Workspace::new_local(
 8352                    session_workspace.paths.paths().to_vec(),
 8353                    app_state.clone(),
 8354                    Some(window_handle),
 8355                    None,
 8356                    None,
 8357                    false,
 8358                    cx,
 8359                )
 8360            })
 8361            .await
 8362            .err()
 8363        };
 8364
 8365        if let Some(error) = error {
 8366            errors.push(error);
 8367        }
 8368    }
 8369
 8370    if let Some(target_id) = state.active_workspace_id {
 8371        window_handle
 8372            .update(cx, |multi_workspace, window, cx| {
 8373                let target_index = multi_workspace
 8374                    .workspaces()
 8375                    .iter()
 8376                    .position(|ws| ws.read(cx).database_id() == Some(target_id));
 8377                if let Some(index) = target_index {
 8378                    multi_workspace.activate_index(index, window, cx);
 8379                } else if !multi_workspace.workspaces().is_empty() {
 8380                    multi_workspace.activate_index(0, window, cx);
 8381                }
 8382            })
 8383            .ok();
 8384    } else {
 8385        window_handle
 8386            .update(cx, |multi_workspace, window, cx| {
 8387                if !multi_workspace.workspaces().is_empty() {
 8388                    multi_workspace.activate_index(0, window, cx);
 8389                }
 8390            })
 8391            .ok();
 8392    }
 8393
 8394    if state.sidebar_open {
 8395        window_handle
 8396            .update(cx, |multi_workspace, _, cx| {
 8397                multi_workspace.open_sidebar(cx);
 8398            })
 8399            .ok();
 8400    }
 8401
 8402    window_handle
 8403        .update(cx, |_, window, _cx| {
 8404            window.activate_window();
 8405        })
 8406        .ok();
 8407
 8408    Ok(MultiWorkspaceRestoreResult {
 8409        window_handle,
 8410        errors,
 8411    })
 8412}
 8413
 8414actions!(
 8415    collab,
 8416    [
 8417        /// Opens the channel notes for the current call.
 8418        ///
 8419        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8420        /// channel in the collab panel.
 8421        ///
 8422        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8423        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8424        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8425        OpenChannelNotes,
 8426        /// Mutes your microphone.
 8427        Mute,
 8428        /// Deafens yourself (mute both microphone and speakers).
 8429        Deafen,
 8430        /// Leaves the current call.
 8431        LeaveCall,
 8432        /// Shares the current project with collaborators.
 8433        ShareProject,
 8434        /// Shares your screen with collaborators.
 8435        ScreenShare,
 8436        /// Copies the current room name and session id for debugging purposes.
 8437        CopyRoomId,
 8438    ]
 8439);
 8440
 8441/// Opens the channel notes for a specific channel by its ID.
 8442#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8443#[action(namespace = collab)]
 8444#[serde(deny_unknown_fields)]
 8445pub struct OpenChannelNotesById {
 8446    pub channel_id: u64,
 8447}
 8448
 8449actions!(
 8450    zed,
 8451    [
 8452        /// Opens the Zed log file.
 8453        OpenLog,
 8454        /// Reveals the Zed log file in the system file manager.
 8455        RevealLogInFileManager
 8456    ]
 8457);
 8458
 8459async fn join_channel_internal(
 8460    channel_id: ChannelId,
 8461    app_state: &Arc<AppState>,
 8462    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8463    requesting_workspace: Option<WeakEntity<Workspace>>,
 8464    active_call: &dyn AnyActiveCall,
 8465    cx: &mut AsyncApp,
 8466) -> Result<bool> {
 8467    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8468        if !active_call.is_in_room(cx) {
 8469            return (false, false);
 8470        }
 8471
 8472        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8473        let should_prompt = active_call.is_sharing_project(cx)
 8474            && active_call.has_remote_participants(cx)
 8475            && !already_in_channel;
 8476        (should_prompt, already_in_channel)
 8477    });
 8478
 8479    if already_in_channel {
 8480        let task = cx.update(|cx| {
 8481            if let Some((project, host)) = active_call.most_active_project(cx) {
 8482                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8483            } else {
 8484                None
 8485            }
 8486        });
 8487        if let Some(task) = task {
 8488            task.await?;
 8489        }
 8490        return anyhow::Ok(true);
 8491    }
 8492
 8493    if should_prompt {
 8494        if let Some(multi_workspace) = requesting_window {
 8495            let answer = multi_workspace
 8496                .update(cx, |_, window, cx| {
 8497                    window.prompt(
 8498                        PromptLevel::Warning,
 8499                        "Do you want to switch channels?",
 8500                        Some("Leaving this call will unshare your current project."),
 8501                        &["Yes, Join Channel", "Cancel"],
 8502                        cx,
 8503                    )
 8504                })?
 8505                .await;
 8506
 8507            if answer == Ok(1) {
 8508                return Ok(false);
 8509            }
 8510        } else {
 8511            return Ok(false);
 8512        }
 8513    }
 8514
 8515    let client = cx.update(|cx| active_call.client(cx));
 8516
 8517    let mut client_status = client.status();
 8518
 8519    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8520    'outer: loop {
 8521        let Some(status) = client_status.recv().await else {
 8522            anyhow::bail!("error connecting");
 8523        };
 8524
 8525        match status {
 8526            Status::Connecting
 8527            | Status::Authenticating
 8528            | Status::Authenticated
 8529            | Status::Reconnecting
 8530            | Status::Reauthenticating
 8531            | Status::Reauthenticated => continue,
 8532            Status::Connected { .. } => break 'outer,
 8533            Status::SignedOut | Status::AuthenticationError => {
 8534                return Err(ErrorCode::SignedOut.into());
 8535            }
 8536            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8537            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8538                return Err(ErrorCode::Disconnected.into());
 8539            }
 8540        }
 8541    }
 8542
 8543    let joined = cx
 8544        .update(|cx| active_call.join_channel(channel_id, cx))
 8545        .await?;
 8546
 8547    if !joined {
 8548        return anyhow::Ok(true);
 8549    }
 8550
 8551    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8552
 8553    let task = cx.update(|cx| {
 8554        if let Some((project, host)) = active_call.most_active_project(cx) {
 8555            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8556        }
 8557
 8558        // If you are the first to join a channel, see if you should share your project.
 8559        if !active_call.has_remote_participants(cx)
 8560            && !active_call.local_participant_is_guest(cx)
 8561            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8562        {
 8563            let project = workspace.update(cx, |workspace, cx| {
 8564                let project = workspace.project.read(cx);
 8565
 8566                if !active_call.share_on_join(cx) {
 8567                    return None;
 8568                }
 8569
 8570                if (project.is_local() || project.is_via_remote_server())
 8571                    && project.visible_worktrees(cx).any(|tree| {
 8572                        tree.read(cx)
 8573                            .root_entry()
 8574                            .is_some_and(|entry| entry.is_dir())
 8575                    })
 8576                {
 8577                    Some(workspace.project.clone())
 8578                } else {
 8579                    None
 8580                }
 8581            });
 8582            if let Some(project) = project {
 8583                let share_task = active_call.share_project(project, cx);
 8584                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8585                    share_task.await?;
 8586                    Ok(())
 8587                }));
 8588            }
 8589        }
 8590
 8591        None
 8592    });
 8593    if let Some(task) = task {
 8594        task.await?;
 8595        return anyhow::Ok(true);
 8596    }
 8597    anyhow::Ok(false)
 8598}
 8599
 8600pub fn join_channel(
 8601    channel_id: ChannelId,
 8602    app_state: Arc<AppState>,
 8603    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8604    requesting_workspace: Option<WeakEntity<Workspace>>,
 8605    cx: &mut App,
 8606) -> Task<Result<()>> {
 8607    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8608    cx.spawn(async move |cx| {
 8609        let result = join_channel_internal(
 8610            channel_id,
 8611            &app_state,
 8612            requesting_window,
 8613            requesting_workspace,
 8614            &*active_call.0,
 8615            cx,
 8616        )
 8617        .await;
 8618
 8619        // join channel succeeded, and opened a window
 8620        if matches!(result, Ok(true)) {
 8621            return anyhow::Ok(());
 8622        }
 8623
 8624        // find an existing workspace to focus and show call controls
 8625        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8626        if active_window.is_none() {
 8627            // no open workspaces, make one to show the error in (blergh)
 8628            let OpenResult {
 8629                window: window_handle,
 8630                ..
 8631            } = cx
 8632                .update(|cx| {
 8633                    Workspace::new_local(
 8634                        vec![],
 8635                        app_state.clone(),
 8636                        requesting_window,
 8637                        None,
 8638                        None,
 8639                        true,
 8640                        cx,
 8641                    )
 8642                })
 8643                .await?;
 8644
 8645            window_handle
 8646                .update(cx, |_, window, _cx| {
 8647                    window.activate_window();
 8648                })
 8649                .ok();
 8650
 8651            if result.is_ok() {
 8652                cx.update(|cx| {
 8653                    cx.dispatch_action(&OpenChannelNotes);
 8654                });
 8655            }
 8656
 8657            active_window = Some(window_handle);
 8658        }
 8659
 8660        if let Err(err) = result {
 8661            log::error!("failed to join channel: {}", err);
 8662            if let Some(active_window) = active_window {
 8663                active_window
 8664                    .update(cx, |_, window, cx| {
 8665                        let detail: SharedString = match err.error_code() {
 8666                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 8667                            ErrorCode::UpgradeRequired => concat!(
 8668                                "Your are running an unsupported version of Zed. ",
 8669                                "Please update to continue."
 8670                            )
 8671                            .into(),
 8672                            ErrorCode::NoSuchChannel => concat!(
 8673                                "No matching channel was found. ",
 8674                                "Please check the link and try again."
 8675                            )
 8676                            .into(),
 8677                            ErrorCode::Forbidden => concat!(
 8678                                "This channel is private, and you do not have access. ",
 8679                                "Please ask someone to add you and try again."
 8680                            )
 8681                            .into(),
 8682                            ErrorCode::Disconnected => {
 8683                                "Please check your internet connection and try again.".into()
 8684                            }
 8685                            _ => format!("{}\n\nPlease try again.", err).into(),
 8686                        };
 8687                        window.prompt(
 8688                            PromptLevel::Critical,
 8689                            "Failed to join channel",
 8690                            Some(&detail),
 8691                            &["Ok"],
 8692                            cx,
 8693                        )
 8694                    })?
 8695                    .await
 8696                    .ok();
 8697            }
 8698        }
 8699
 8700        // return ok, we showed the error to the user.
 8701        anyhow::Ok(())
 8702    })
 8703}
 8704
 8705pub async fn get_any_active_multi_workspace(
 8706    app_state: Arc<AppState>,
 8707    mut cx: AsyncApp,
 8708) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8709    // find an existing workspace to focus and show call controls
 8710    let active_window = activate_any_workspace_window(&mut cx);
 8711    if active_window.is_none() {
 8712        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
 8713            .await?;
 8714    }
 8715    activate_any_workspace_window(&mut cx).context("could not open zed")
 8716}
 8717
 8718fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 8719    cx.update(|cx| {
 8720        if let Some(workspace_window) = cx
 8721            .active_window()
 8722            .and_then(|window| window.downcast::<MultiWorkspace>())
 8723        {
 8724            return Some(workspace_window);
 8725        }
 8726
 8727        for window in cx.windows() {
 8728            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 8729                workspace_window
 8730                    .update(cx, |_, window, _| window.activate_window())
 8731                    .ok();
 8732                return Some(workspace_window);
 8733            }
 8734        }
 8735        None
 8736    })
 8737}
 8738
 8739pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 8740    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 8741}
 8742
 8743pub fn workspace_windows_for_location(
 8744    serialized_location: &SerializedWorkspaceLocation,
 8745    cx: &App,
 8746) -> Vec<WindowHandle<MultiWorkspace>> {
 8747    cx.windows()
 8748        .into_iter()
 8749        .filter_map(|window| window.downcast::<MultiWorkspace>())
 8750        .filter(|multi_workspace| {
 8751            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 8752                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 8753                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 8754                }
 8755                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 8756                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 8757                    a.distro_name == b.distro_name
 8758                }
 8759                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 8760                    a.container_id == b.container_id
 8761                }
 8762                #[cfg(any(test, feature = "test-support"))]
 8763                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 8764                    a.id == b.id
 8765                }
 8766                _ => false,
 8767            };
 8768
 8769            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 8770                multi_workspace.workspaces().iter().any(|workspace| {
 8771                    match workspace.read(cx).workspace_location(cx) {
 8772                        WorkspaceLocation::Location(location, _) => {
 8773                            match (&location, serialized_location) {
 8774                                (
 8775                                    SerializedWorkspaceLocation::Local,
 8776                                    SerializedWorkspaceLocation::Local,
 8777                                ) => true,
 8778                                (
 8779                                    SerializedWorkspaceLocation::Remote(a),
 8780                                    SerializedWorkspaceLocation::Remote(b),
 8781                                ) => same_host(a, b),
 8782                                _ => false,
 8783                            }
 8784                        }
 8785                        _ => false,
 8786                    }
 8787                })
 8788            })
 8789        })
 8790        .collect()
 8791}
 8792
 8793pub async fn find_existing_workspace(
 8794    abs_paths: &[PathBuf],
 8795    open_options: &OpenOptions,
 8796    location: &SerializedWorkspaceLocation,
 8797    cx: &mut AsyncApp,
 8798) -> (
 8799    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 8800    OpenVisible,
 8801) {
 8802    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 8803    let mut open_visible = OpenVisible::All;
 8804    let mut best_match = None;
 8805
 8806    if open_options.open_new_workspace != Some(true) {
 8807        cx.update(|cx| {
 8808            for window in workspace_windows_for_location(location, cx) {
 8809                if let Ok(multi_workspace) = window.read(cx) {
 8810                    for workspace in multi_workspace.workspaces() {
 8811                        let project = workspace.read(cx).project.read(cx);
 8812                        let m = project.visibility_for_paths(
 8813                            abs_paths,
 8814                            open_options.open_new_workspace == None,
 8815                            cx,
 8816                        );
 8817                        if m > best_match {
 8818                            existing = Some((window, workspace.clone()));
 8819                            best_match = m;
 8820                        } else if best_match.is_none()
 8821                            && open_options.open_new_workspace == Some(false)
 8822                        {
 8823                            existing = Some((window, workspace.clone()))
 8824                        }
 8825                    }
 8826                }
 8827            }
 8828        });
 8829
 8830        let all_paths_are_files = existing
 8831            .as_ref()
 8832            .and_then(|(_, target_workspace)| {
 8833                cx.update(|cx| {
 8834                    let workspace = target_workspace.read(cx);
 8835                    let project = workspace.project.read(cx);
 8836                    let path_style = workspace.path_style(cx);
 8837                    Some(!abs_paths.iter().any(|path| {
 8838                        let path = util::paths::SanitizedPath::new(path);
 8839                        project.worktrees(cx).any(|worktree| {
 8840                            let worktree = worktree.read(cx);
 8841                            let abs_path = worktree.abs_path();
 8842                            path_style
 8843                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 8844                                .and_then(|rel| worktree.entry_for_path(&rel))
 8845                                .is_some_and(|e| e.is_dir())
 8846                        })
 8847                    }))
 8848                })
 8849            })
 8850            .unwrap_or(false);
 8851
 8852        if open_options.open_new_workspace.is_none()
 8853            && existing.is_some()
 8854            && open_options.wait
 8855            && all_paths_are_files
 8856        {
 8857            cx.update(|cx| {
 8858                let windows = workspace_windows_for_location(location, cx);
 8859                let window = cx
 8860                    .active_window()
 8861                    .and_then(|window| window.downcast::<MultiWorkspace>())
 8862                    .filter(|window| windows.contains(window))
 8863                    .or_else(|| windows.into_iter().next());
 8864                if let Some(window) = window {
 8865                    if let Ok(multi_workspace) = window.read(cx) {
 8866                        let active_workspace = multi_workspace.workspace().clone();
 8867                        existing = Some((window, active_workspace));
 8868                        open_visible = OpenVisible::None;
 8869                    }
 8870                }
 8871            });
 8872        }
 8873    }
 8874    (existing, open_visible)
 8875}
 8876
 8877#[derive(Default, Clone)]
 8878pub struct OpenOptions {
 8879    pub visible: Option<OpenVisible>,
 8880    pub focus: Option<bool>,
 8881    pub open_new_workspace: Option<bool>,
 8882    pub wait: bool,
 8883    pub replace_window: Option<WindowHandle<MultiWorkspace>>,
 8884    pub env: Option<HashMap<String, String>>,
 8885}
 8886
 8887/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 8888/// or [`Workspace::open_workspace_for_paths`].
 8889pub struct OpenResult {
 8890    pub window: WindowHandle<MultiWorkspace>,
 8891    pub workspace: Entity<Workspace>,
 8892    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 8893}
 8894
 8895/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 8896pub fn open_workspace_by_id(
 8897    workspace_id: WorkspaceId,
 8898    app_state: Arc<AppState>,
 8899    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8900    cx: &mut App,
 8901) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 8902    let project_handle = Project::local(
 8903        app_state.client.clone(),
 8904        app_state.node_runtime.clone(),
 8905        app_state.user_store.clone(),
 8906        app_state.languages.clone(),
 8907        app_state.fs.clone(),
 8908        None,
 8909        project::LocalProjectFlags {
 8910            init_worktree_trust: true,
 8911            ..project::LocalProjectFlags::default()
 8912        },
 8913        cx,
 8914    );
 8915
 8916    let db = WorkspaceDb::global(cx);
 8917    let kvp = db::kvp::KeyValueStore::global(cx);
 8918    cx.spawn(async move |cx| {
 8919        let serialized_workspace = db
 8920            .workspace_for_id(workspace_id)
 8921            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 8922
 8923        let centered_layout = serialized_workspace.centered_layout;
 8924
 8925        let (window, workspace) = if let Some(window) = requesting_window {
 8926            let workspace = window.update(cx, |multi_workspace, window, cx| {
 8927                let workspace = cx.new(|cx| {
 8928                    let mut workspace = Workspace::new(
 8929                        Some(workspace_id),
 8930                        project_handle.clone(),
 8931                        app_state.clone(),
 8932                        window,
 8933                        cx,
 8934                    );
 8935                    workspace.centered_layout = centered_layout;
 8936                    workspace
 8937                });
 8938                multi_workspace.add_workspace(workspace.clone(), cx);
 8939                workspace
 8940            })?;
 8941            (window, workspace)
 8942        } else {
 8943            let window_bounds_override = window_bounds_env_override();
 8944
 8945            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 8946                (Some(WindowBounds::Windowed(bounds)), None)
 8947            } else if let Some(display) = serialized_workspace.display
 8948                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 8949            {
 8950                (Some(bounds.0), Some(display))
 8951            } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
 8952                (Some(bounds), Some(display))
 8953            } else {
 8954                (None, None)
 8955            };
 8956
 8957            let options = cx.update(|cx| {
 8958                let mut options = (app_state.build_window_options)(display, cx);
 8959                options.window_bounds = window_bounds;
 8960                options
 8961            });
 8962
 8963            let window = cx.open_window(options, {
 8964                let app_state = app_state.clone();
 8965                let project_handle = project_handle.clone();
 8966                move |window, cx| {
 8967                    let workspace = cx.new(|cx| {
 8968                        let mut workspace = Workspace::new(
 8969                            Some(workspace_id),
 8970                            project_handle,
 8971                            app_state,
 8972                            window,
 8973                            cx,
 8974                        );
 8975                        workspace.centered_layout = centered_layout;
 8976                        workspace
 8977                    });
 8978                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 8979                }
 8980            })?;
 8981
 8982            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 8983                multi_workspace.workspace().clone()
 8984            })?;
 8985
 8986            (window, workspace)
 8987        };
 8988
 8989        notify_if_database_failed(window, cx);
 8990
 8991        // Restore items from the serialized workspace
 8992        window
 8993            .update(cx, |_, window, cx| {
 8994                workspace.update(cx, |_workspace, cx| {
 8995                    open_items(Some(serialized_workspace), vec![], window, cx)
 8996                })
 8997            })?
 8998            .await?;
 8999
 9000        window.update(cx, |_, window, cx| {
 9001            workspace.update(cx, |workspace, cx| {
 9002                workspace.serialize_workspace(window, cx);
 9003            });
 9004        })?;
 9005
 9006        Ok(window)
 9007    })
 9008}
 9009
 9010#[allow(clippy::type_complexity)]
 9011pub fn open_paths(
 9012    abs_paths: &[PathBuf],
 9013    app_state: Arc<AppState>,
 9014    open_options: OpenOptions,
 9015    cx: &mut App,
 9016) -> Task<anyhow::Result<OpenResult>> {
 9017    let abs_paths = abs_paths.to_vec();
 9018    #[cfg(target_os = "windows")]
 9019    let wsl_path = abs_paths
 9020        .iter()
 9021        .find_map(|p| util::paths::WslPath::from_path(p));
 9022
 9023    cx.spawn(async move |cx| {
 9024        let (mut existing, mut open_visible) = find_existing_workspace(
 9025            &abs_paths,
 9026            &open_options,
 9027            &SerializedWorkspaceLocation::Local,
 9028            cx,
 9029        )
 9030        .await;
 9031
 9032        // Fallback: if no workspace contains the paths and all paths are files,
 9033        // prefer an existing local workspace window (active window first).
 9034        if open_options.open_new_workspace.is_none() && existing.is_none() {
 9035            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 9036            let all_metadatas = futures::future::join_all(all_paths)
 9037                .await
 9038                .into_iter()
 9039                .filter_map(|result| result.ok().flatten())
 9040                .collect::<Vec<_>>();
 9041
 9042            if all_metadatas.iter().all(|file| !file.is_dir) {
 9043                cx.update(|cx| {
 9044                    let windows = workspace_windows_for_location(
 9045                        &SerializedWorkspaceLocation::Local,
 9046                        cx,
 9047                    );
 9048                    let window = cx
 9049                        .active_window()
 9050                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9051                        .filter(|window| windows.contains(window))
 9052                        .or_else(|| windows.into_iter().next());
 9053                    if let Some(window) = window {
 9054                        if let Ok(multi_workspace) = window.read(cx) {
 9055                            let active_workspace = multi_workspace.workspace().clone();
 9056                            existing = Some((window, active_workspace));
 9057                            open_visible = OpenVisible::None;
 9058                        }
 9059                    }
 9060                });
 9061            }
 9062        }
 9063
 9064        let result = if let Some((existing, target_workspace)) = existing {
 9065            let open_task = existing
 9066                .update(cx, |multi_workspace, window, cx| {
 9067                    window.activate_window();
 9068                    multi_workspace.activate(target_workspace.clone(), cx);
 9069                    target_workspace.update(cx, |workspace, cx| {
 9070                        workspace.open_paths(
 9071                            abs_paths,
 9072                            OpenOptions {
 9073                                visible: Some(open_visible),
 9074                                ..Default::default()
 9075                            },
 9076                            None,
 9077                            window,
 9078                            cx,
 9079                        )
 9080                    })
 9081                })?
 9082                .await;
 9083
 9084            _ = existing.update(cx, |multi_workspace, _, cx| {
 9085                let workspace = multi_workspace.workspace().clone();
 9086                workspace.update(cx, |workspace, cx| {
 9087                    for item in open_task.iter().flatten() {
 9088                        if let Err(e) = item {
 9089                            workspace.show_error(&e, cx);
 9090                        }
 9091                    }
 9092                });
 9093            });
 9094
 9095            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9096        } else {
 9097            let result = cx
 9098                .update(move |cx| {
 9099                    Workspace::new_local(
 9100                        abs_paths,
 9101                        app_state.clone(),
 9102                        open_options.replace_window,
 9103                        open_options.env,
 9104                        None,
 9105                        true,
 9106                        cx,
 9107                    )
 9108                })
 9109                .await;
 9110
 9111            if let Ok(ref result) = result {
 9112                result.window
 9113                    .update(cx, |_, window, _cx| {
 9114                        window.activate_window();
 9115                    })
 9116                    .log_err();
 9117            }
 9118
 9119            result
 9120        };
 9121
 9122        #[cfg(target_os = "windows")]
 9123        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9124            && let Ok(ref result) = result
 9125        {
 9126            result.window
 9127                .update(cx, move |multi_workspace, _window, cx| {
 9128                    struct OpenInWsl;
 9129                    let workspace = multi_workspace.workspace().clone();
 9130                    workspace.update(cx, |workspace, cx| {
 9131                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9132                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9133                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9134                            cx.new(move |cx| {
 9135                                MessageNotification::new(msg, cx)
 9136                                    .primary_message("Open in WSL")
 9137                                    .primary_icon(IconName::FolderOpen)
 9138                                    .primary_on_click(move |window, cx| {
 9139                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9140                                                distro: remote::WslConnectionOptions {
 9141                                                        distro_name: distro.clone(),
 9142                                                    user: None,
 9143                                                },
 9144                                                paths: vec![path.clone().into()],
 9145                                            }), cx)
 9146                                    })
 9147                            })
 9148                        });
 9149                    });
 9150                })
 9151                .unwrap();
 9152        };
 9153        result
 9154    })
 9155}
 9156
 9157pub fn open_new(
 9158    open_options: OpenOptions,
 9159    app_state: Arc<AppState>,
 9160    cx: &mut App,
 9161    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9162) -> Task<anyhow::Result<()>> {
 9163    let task = Workspace::new_local(
 9164        Vec::new(),
 9165        app_state,
 9166        open_options.replace_window,
 9167        open_options.env,
 9168        Some(Box::new(init)),
 9169        true,
 9170        cx,
 9171    );
 9172    cx.spawn(async move |cx| {
 9173        let OpenResult { window, .. } = task.await?;
 9174        window
 9175            .update(cx, |_, window, _cx| {
 9176                window.activate_window();
 9177            })
 9178            .ok();
 9179        Ok(())
 9180    })
 9181}
 9182
 9183pub fn create_and_open_local_file(
 9184    path: &'static Path,
 9185    window: &mut Window,
 9186    cx: &mut Context<Workspace>,
 9187    default_content: impl 'static + Send + FnOnce() -> Rope,
 9188) -> Task<Result<Box<dyn ItemHandle>>> {
 9189    cx.spawn_in(window, async move |workspace, cx| {
 9190        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9191        if !fs.is_file(path).await {
 9192            fs.create_file(path, Default::default()).await?;
 9193            fs.save(path, &default_content(), Default::default())
 9194                .await?;
 9195        }
 9196
 9197        workspace
 9198            .update_in(cx, |workspace, window, cx| {
 9199                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9200                    let path = workspace
 9201                        .project
 9202                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9203                    cx.spawn_in(window, async move |workspace, cx| {
 9204                        let path = path.await?;
 9205                        let mut items = workspace
 9206                            .update_in(cx, |workspace, window, cx| {
 9207                                workspace.open_paths(
 9208                                    vec![path.to_path_buf()],
 9209                                    OpenOptions {
 9210                                        visible: Some(OpenVisible::None),
 9211                                        ..Default::default()
 9212                                    },
 9213                                    None,
 9214                                    window,
 9215                                    cx,
 9216                                )
 9217                            })?
 9218                            .await;
 9219                        let item = items.pop().flatten();
 9220                        item.with_context(|| format!("path {path:?} is not a file"))?
 9221                    })
 9222                })
 9223            })?
 9224            .await?
 9225            .await
 9226    })
 9227}
 9228
 9229pub fn open_remote_project_with_new_connection(
 9230    window: WindowHandle<MultiWorkspace>,
 9231    remote_connection: Arc<dyn RemoteConnection>,
 9232    cancel_rx: oneshot::Receiver<()>,
 9233    delegate: Arc<dyn RemoteClientDelegate>,
 9234    app_state: Arc<AppState>,
 9235    paths: Vec<PathBuf>,
 9236    cx: &mut App,
 9237) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9238    cx.spawn(async move |cx| {
 9239        let (workspace_id, serialized_workspace) =
 9240            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9241                .await?;
 9242
 9243        let session = match cx
 9244            .update(|cx| {
 9245                remote::RemoteClient::new(
 9246                    ConnectionIdentifier::Workspace(workspace_id.0),
 9247                    remote_connection,
 9248                    cancel_rx,
 9249                    delegate,
 9250                    cx,
 9251                )
 9252            })
 9253            .await?
 9254        {
 9255            Some(result) => result,
 9256            None => return Ok(Vec::new()),
 9257        };
 9258
 9259        let project = cx.update(|cx| {
 9260            project::Project::remote(
 9261                session,
 9262                app_state.client.clone(),
 9263                app_state.node_runtime.clone(),
 9264                app_state.user_store.clone(),
 9265                app_state.languages.clone(),
 9266                app_state.fs.clone(),
 9267                true,
 9268                cx,
 9269            )
 9270        });
 9271
 9272        open_remote_project_inner(
 9273            project,
 9274            paths,
 9275            workspace_id,
 9276            serialized_workspace,
 9277            app_state,
 9278            window,
 9279            cx,
 9280        )
 9281        .await
 9282    })
 9283}
 9284
 9285pub fn open_remote_project_with_existing_connection(
 9286    connection_options: RemoteConnectionOptions,
 9287    project: Entity<Project>,
 9288    paths: Vec<PathBuf>,
 9289    app_state: Arc<AppState>,
 9290    window: WindowHandle<MultiWorkspace>,
 9291    cx: &mut AsyncApp,
 9292) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9293    cx.spawn(async move |cx| {
 9294        let (workspace_id, serialized_workspace) =
 9295            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9296
 9297        open_remote_project_inner(
 9298            project,
 9299            paths,
 9300            workspace_id,
 9301            serialized_workspace,
 9302            app_state,
 9303            window,
 9304            cx,
 9305        )
 9306        .await
 9307    })
 9308}
 9309
 9310async fn open_remote_project_inner(
 9311    project: Entity<Project>,
 9312    paths: Vec<PathBuf>,
 9313    workspace_id: WorkspaceId,
 9314    serialized_workspace: Option<SerializedWorkspace>,
 9315    app_state: Arc<AppState>,
 9316    window: WindowHandle<MultiWorkspace>,
 9317    cx: &mut AsyncApp,
 9318) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9319    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9320    let toolchains = db.toolchains(workspace_id).await?;
 9321    for (toolchain, worktree_path, path) in toolchains {
 9322        project
 9323            .update(cx, |this, cx| {
 9324                let Some(worktree_id) =
 9325                    this.find_worktree(&worktree_path, cx)
 9326                        .and_then(|(worktree, rel_path)| {
 9327                            if rel_path.is_empty() {
 9328                                Some(worktree.read(cx).id())
 9329                            } else {
 9330                                None
 9331                            }
 9332                        })
 9333                else {
 9334                    return Task::ready(None);
 9335                };
 9336
 9337                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9338            })
 9339            .await;
 9340    }
 9341    let mut project_paths_to_open = vec![];
 9342    let mut project_path_errors = vec![];
 9343
 9344    for path in paths {
 9345        let result = cx
 9346            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9347            .await;
 9348        match result {
 9349            Ok((_, project_path)) => {
 9350                project_paths_to_open.push((path.clone(), Some(project_path)));
 9351            }
 9352            Err(error) => {
 9353                project_path_errors.push(error);
 9354            }
 9355        };
 9356    }
 9357
 9358    if project_paths_to_open.is_empty() {
 9359        return Err(project_path_errors.pop().context("no paths given")?);
 9360    }
 9361
 9362    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9363        telemetry::event!("SSH Project Opened");
 9364
 9365        let new_workspace = cx.new(|cx| {
 9366            let mut workspace =
 9367                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9368            workspace.update_history(cx);
 9369
 9370            if let Some(ref serialized) = serialized_workspace {
 9371                workspace.centered_layout = serialized.centered_layout;
 9372            }
 9373
 9374            workspace
 9375        });
 9376
 9377        multi_workspace.activate(new_workspace.clone(), cx);
 9378        new_workspace
 9379    })?;
 9380
 9381    let items = window
 9382        .update(cx, |_, window, cx| {
 9383            window.activate_window();
 9384            workspace.update(cx, |_workspace, cx| {
 9385                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9386            })
 9387        })?
 9388        .await?;
 9389
 9390    workspace.update(cx, |workspace, cx| {
 9391        for error in project_path_errors {
 9392            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9393                if let Some(path) = error.error_tag("path") {
 9394                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9395                }
 9396            } else {
 9397                workspace.show_error(&error, cx)
 9398            }
 9399        }
 9400    });
 9401
 9402    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9403}
 9404
 9405fn deserialize_remote_project(
 9406    connection_options: RemoteConnectionOptions,
 9407    paths: Vec<PathBuf>,
 9408    cx: &AsyncApp,
 9409) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9410    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9411    cx.background_spawn(async move {
 9412        let remote_connection_id = db
 9413            .get_or_create_remote_connection(connection_options)
 9414            .await?;
 9415
 9416        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
 9417
 9418        let workspace_id = if let Some(workspace_id) =
 9419            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9420        {
 9421            workspace_id
 9422        } else {
 9423            db.next_id().await?
 9424        };
 9425
 9426        Ok((workspace_id, serialized_workspace))
 9427    })
 9428}
 9429
 9430pub fn join_in_room_project(
 9431    project_id: u64,
 9432    follow_user_id: u64,
 9433    app_state: Arc<AppState>,
 9434    cx: &mut App,
 9435) -> Task<Result<()>> {
 9436    let windows = cx.windows();
 9437    cx.spawn(async move |cx| {
 9438        let existing_window_and_workspace: Option<(
 9439            WindowHandle<MultiWorkspace>,
 9440            Entity<Workspace>,
 9441        )> = windows.into_iter().find_map(|window_handle| {
 9442            window_handle
 9443                .downcast::<MultiWorkspace>()
 9444                .and_then(|window_handle| {
 9445                    window_handle
 9446                        .update(cx, |multi_workspace, _window, cx| {
 9447                            for workspace in multi_workspace.workspaces() {
 9448                                if workspace.read(cx).project().read(cx).remote_id()
 9449                                    == Some(project_id)
 9450                                {
 9451                                    return Some((window_handle, workspace.clone()));
 9452                                }
 9453                            }
 9454                            None
 9455                        })
 9456                        .unwrap_or(None)
 9457                })
 9458        });
 9459
 9460        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9461            existing_window_and_workspace
 9462        {
 9463            existing_window
 9464                .update(cx, |multi_workspace, _, cx| {
 9465                    multi_workspace.activate(target_workspace, cx);
 9466                })
 9467                .ok();
 9468            existing_window
 9469        } else {
 9470            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9471            let project = cx
 9472                .update(|cx| {
 9473                    active_call.0.join_project(
 9474                        project_id,
 9475                        app_state.languages.clone(),
 9476                        app_state.fs.clone(),
 9477                        cx,
 9478                    )
 9479                })
 9480                .await?;
 9481
 9482            let window_bounds_override = window_bounds_env_override();
 9483            cx.update(|cx| {
 9484                let mut options = (app_state.build_window_options)(None, cx);
 9485                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9486                cx.open_window(options, |window, cx| {
 9487                    let workspace = cx.new(|cx| {
 9488                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9489                    });
 9490                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9491                })
 9492            })?
 9493        };
 9494
 9495        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9496            cx.activate(true);
 9497            window.activate_window();
 9498
 9499            // We set the active workspace above, so this is the correct workspace.
 9500            let workspace = multi_workspace.workspace().clone();
 9501            workspace.update(cx, |workspace, cx| {
 9502                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9503                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9504                    .or_else(|| {
 9505                        // If we couldn't follow the given user, follow the host instead.
 9506                        let collaborator = workspace
 9507                            .project()
 9508                            .read(cx)
 9509                            .collaborators()
 9510                            .values()
 9511                            .find(|collaborator| collaborator.is_host)?;
 9512                        Some(collaborator.peer_id)
 9513                    });
 9514
 9515                if let Some(follow_peer_id) = follow_peer_id {
 9516                    workspace.follow(follow_peer_id, window, cx);
 9517                }
 9518            });
 9519        })?;
 9520
 9521        anyhow::Ok(())
 9522    })
 9523}
 9524
 9525pub fn reload(cx: &mut App) {
 9526    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9527    let mut workspace_windows = cx
 9528        .windows()
 9529        .into_iter()
 9530        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9531        .collect::<Vec<_>>();
 9532
 9533    // If multiple windows have unsaved changes, and need a save prompt,
 9534    // prompt in the active window before switching to a different window.
 9535    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9536
 9537    let mut prompt = None;
 9538    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9539        prompt = window
 9540            .update(cx, |_, window, cx| {
 9541                window.prompt(
 9542                    PromptLevel::Info,
 9543                    "Are you sure you want to restart?",
 9544                    None,
 9545                    &["Restart", "Cancel"],
 9546                    cx,
 9547                )
 9548            })
 9549            .ok();
 9550    }
 9551
 9552    cx.spawn(async move |cx| {
 9553        if let Some(prompt) = prompt {
 9554            let answer = prompt.await?;
 9555            if answer != 0 {
 9556                return anyhow::Ok(());
 9557            }
 9558        }
 9559
 9560        // If the user cancels any save prompt, then keep the app open.
 9561        for window in workspace_windows {
 9562            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9563                let workspace = multi_workspace.workspace().clone();
 9564                workspace.update(cx, |workspace, cx| {
 9565                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9566                })
 9567            }) && !should_close.await?
 9568            {
 9569                return anyhow::Ok(());
 9570            }
 9571        }
 9572        cx.update(|cx| cx.restart());
 9573        anyhow::Ok(())
 9574    })
 9575    .detach_and_log_err(cx);
 9576}
 9577
 9578fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9579    let mut parts = value.split(',');
 9580    let x: usize = parts.next()?.parse().ok()?;
 9581    let y: usize = parts.next()?.parse().ok()?;
 9582    Some(point(px(x as f32), px(y as f32)))
 9583}
 9584
 9585fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9586    let mut parts = value.split(',');
 9587    let width: usize = parts.next()?.parse().ok()?;
 9588    let height: usize = parts.next()?.parse().ok()?;
 9589    Some(size(px(width as f32), px(height as f32)))
 9590}
 9591
 9592/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9593/// appropriate.
 9594///
 9595/// The `border_radius_tiling` parameter allows overriding which corners get
 9596/// rounded, independently of the actual window tiling state. This is used
 9597/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9598/// we want square corners on the left (so the sidebar appears flush with the
 9599/// window edge) but we still need the shadow padding for proper visual
 9600/// appearance. Unlike actual window tiling, this only affects border radius -
 9601/// not padding or shadows.
 9602pub fn client_side_decorations(
 9603    element: impl IntoElement,
 9604    window: &mut Window,
 9605    cx: &mut App,
 9606    border_radius_tiling: Tiling,
 9607) -> Stateful<Div> {
 9608    const BORDER_SIZE: Pixels = px(1.0);
 9609    let decorations = window.window_decorations();
 9610    let tiling = match decorations {
 9611        Decorations::Server => Tiling::default(),
 9612        Decorations::Client { tiling } => tiling,
 9613    };
 9614
 9615    match decorations {
 9616        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9617        Decorations::Server => window.set_client_inset(px(0.0)),
 9618    }
 9619
 9620    struct GlobalResizeEdge(ResizeEdge);
 9621    impl Global for GlobalResizeEdge {}
 9622
 9623    div()
 9624        .id("window-backdrop")
 9625        .bg(transparent_black())
 9626        .map(|div| match decorations {
 9627            Decorations::Server => div,
 9628            Decorations::Client { .. } => div
 9629                .when(
 9630                    !(tiling.top
 9631                        || tiling.right
 9632                        || border_radius_tiling.top
 9633                        || border_radius_tiling.right),
 9634                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9635                )
 9636                .when(
 9637                    !(tiling.top
 9638                        || tiling.left
 9639                        || border_radius_tiling.top
 9640                        || border_radius_tiling.left),
 9641                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9642                )
 9643                .when(
 9644                    !(tiling.bottom
 9645                        || tiling.right
 9646                        || border_radius_tiling.bottom
 9647                        || border_radius_tiling.right),
 9648                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9649                )
 9650                .when(
 9651                    !(tiling.bottom
 9652                        || tiling.left
 9653                        || border_radius_tiling.bottom
 9654                        || border_radius_tiling.left),
 9655                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9656                )
 9657                .when(!tiling.top, |div| {
 9658                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9659                })
 9660                .when(!tiling.bottom, |div| {
 9661                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9662                })
 9663                .when(!tiling.left, |div| {
 9664                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9665                })
 9666                .when(!tiling.right, |div| {
 9667                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9668                })
 9669                .on_mouse_move(move |e, window, cx| {
 9670                    let size = window.window_bounds().get_bounds().size;
 9671                    let pos = e.position;
 9672
 9673                    let new_edge =
 9674                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 9675
 9676                    let edge = cx.try_global::<GlobalResizeEdge>();
 9677                    if new_edge != edge.map(|edge| edge.0) {
 9678                        window
 9679                            .window_handle()
 9680                            .update(cx, |workspace, _, cx| {
 9681                                cx.notify(workspace.entity_id());
 9682                            })
 9683                            .ok();
 9684                    }
 9685                })
 9686                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 9687                    let size = window.window_bounds().get_bounds().size;
 9688                    let pos = e.position;
 9689
 9690                    let edge = match resize_edge(
 9691                        pos,
 9692                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 9693                        size,
 9694                        tiling,
 9695                    ) {
 9696                        Some(value) => value,
 9697                        None => return,
 9698                    };
 9699
 9700                    window.start_window_resize(edge);
 9701                }),
 9702        })
 9703        .size_full()
 9704        .child(
 9705            div()
 9706                .cursor(CursorStyle::Arrow)
 9707                .map(|div| match decorations {
 9708                    Decorations::Server => div,
 9709                    Decorations::Client { .. } => div
 9710                        .border_color(cx.theme().colors().border)
 9711                        .when(
 9712                            !(tiling.top
 9713                                || tiling.right
 9714                                || border_radius_tiling.top
 9715                                || border_radius_tiling.right),
 9716                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9717                        )
 9718                        .when(
 9719                            !(tiling.top
 9720                                || tiling.left
 9721                                || border_radius_tiling.top
 9722                                || border_radius_tiling.left),
 9723                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9724                        )
 9725                        .when(
 9726                            !(tiling.bottom
 9727                                || tiling.right
 9728                                || border_radius_tiling.bottom
 9729                                || border_radius_tiling.right),
 9730                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9731                        )
 9732                        .when(
 9733                            !(tiling.bottom
 9734                                || tiling.left
 9735                                || border_radius_tiling.bottom
 9736                                || border_radius_tiling.left),
 9737                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9738                        )
 9739                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 9740                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 9741                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 9742                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 9743                        .when(!tiling.is_tiled(), |div| {
 9744                            div.shadow(vec![gpui::BoxShadow {
 9745                                color: Hsla {
 9746                                    h: 0.,
 9747                                    s: 0.,
 9748                                    l: 0.,
 9749                                    a: 0.4,
 9750                                },
 9751                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 9752                                spread_radius: px(0.),
 9753                                offset: point(px(0.0), px(0.0)),
 9754                            }])
 9755                        }),
 9756                })
 9757                .on_mouse_move(|_e, _, cx| {
 9758                    cx.stop_propagation();
 9759                })
 9760                .size_full()
 9761                .child(element),
 9762        )
 9763        .map(|div| match decorations {
 9764            Decorations::Server => div,
 9765            Decorations::Client { tiling, .. } => div.child(
 9766                canvas(
 9767                    |_bounds, window, _| {
 9768                        window.insert_hitbox(
 9769                            Bounds::new(
 9770                                point(px(0.0), px(0.0)),
 9771                                window.window_bounds().get_bounds().size,
 9772                            ),
 9773                            HitboxBehavior::Normal,
 9774                        )
 9775                    },
 9776                    move |_bounds, hitbox, window, cx| {
 9777                        let mouse = window.mouse_position();
 9778                        let size = window.window_bounds().get_bounds().size;
 9779                        let Some(edge) =
 9780                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 9781                        else {
 9782                            return;
 9783                        };
 9784                        cx.set_global(GlobalResizeEdge(edge));
 9785                        window.set_cursor_style(
 9786                            match edge {
 9787                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 9788                                ResizeEdge::Left | ResizeEdge::Right => {
 9789                                    CursorStyle::ResizeLeftRight
 9790                                }
 9791                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 9792                                    CursorStyle::ResizeUpLeftDownRight
 9793                                }
 9794                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 9795                                    CursorStyle::ResizeUpRightDownLeft
 9796                                }
 9797                            },
 9798                            &hitbox,
 9799                        );
 9800                    },
 9801                )
 9802                .size_full()
 9803                .absolute(),
 9804            ),
 9805        })
 9806}
 9807
 9808fn resize_edge(
 9809    pos: Point<Pixels>,
 9810    shadow_size: Pixels,
 9811    window_size: Size<Pixels>,
 9812    tiling: Tiling,
 9813) -> Option<ResizeEdge> {
 9814    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 9815    if bounds.contains(&pos) {
 9816        return None;
 9817    }
 9818
 9819    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 9820    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 9821    if !tiling.top && top_left_bounds.contains(&pos) {
 9822        return Some(ResizeEdge::TopLeft);
 9823    }
 9824
 9825    let top_right_bounds = Bounds::new(
 9826        Point::new(window_size.width - corner_size.width, px(0.)),
 9827        corner_size,
 9828    );
 9829    if !tiling.top && top_right_bounds.contains(&pos) {
 9830        return Some(ResizeEdge::TopRight);
 9831    }
 9832
 9833    let bottom_left_bounds = Bounds::new(
 9834        Point::new(px(0.), window_size.height - corner_size.height),
 9835        corner_size,
 9836    );
 9837    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 9838        return Some(ResizeEdge::BottomLeft);
 9839    }
 9840
 9841    let bottom_right_bounds = Bounds::new(
 9842        Point::new(
 9843            window_size.width - corner_size.width,
 9844            window_size.height - corner_size.height,
 9845        ),
 9846        corner_size,
 9847    );
 9848    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 9849        return Some(ResizeEdge::BottomRight);
 9850    }
 9851
 9852    if !tiling.top && pos.y < shadow_size {
 9853        Some(ResizeEdge::Top)
 9854    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 9855        Some(ResizeEdge::Bottom)
 9856    } else if !tiling.left && pos.x < shadow_size {
 9857        Some(ResizeEdge::Left)
 9858    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 9859        Some(ResizeEdge::Right)
 9860    } else {
 9861        None
 9862    }
 9863}
 9864
 9865fn join_pane_into_active(
 9866    active_pane: &Entity<Pane>,
 9867    pane: &Entity<Pane>,
 9868    window: &mut Window,
 9869    cx: &mut App,
 9870) {
 9871    if pane == active_pane {
 9872    } else if pane.read(cx).items_len() == 0 {
 9873        pane.update(cx, |_, cx| {
 9874            cx.emit(pane::Event::Remove {
 9875                focus_on_pane: None,
 9876            });
 9877        })
 9878    } else {
 9879        move_all_items(pane, active_pane, window, cx);
 9880    }
 9881}
 9882
 9883fn move_all_items(
 9884    from_pane: &Entity<Pane>,
 9885    to_pane: &Entity<Pane>,
 9886    window: &mut Window,
 9887    cx: &mut App,
 9888) {
 9889    let destination_is_different = from_pane != to_pane;
 9890    let mut moved_items = 0;
 9891    for (item_ix, item_handle) in from_pane
 9892        .read(cx)
 9893        .items()
 9894        .enumerate()
 9895        .map(|(ix, item)| (ix, item.clone()))
 9896        .collect::<Vec<_>>()
 9897    {
 9898        let ix = item_ix - moved_items;
 9899        if destination_is_different {
 9900            // Close item from previous pane
 9901            from_pane.update(cx, |source, cx| {
 9902                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 9903            });
 9904            moved_items += 1;
 9905        }
 9906
 9907        // This automatically removes duplicate items in the pane
 9908        to_pane.update(cx, |destination, cx| {
 9909            destination.add_item(item_handle, true, true, None, window, cx);
 9910            window.focus(&destination.focus_handle(cx), cx)
 9911        });
 9912    }
 9913}
 9914
 9915pub fn move_item(
 9916    source: &Entity<Pane>,
 9917    destination: &Entity<Pane>,
 9918    item_id_to_move: EntityId,
 9919    destination_index: usize,
 9920    activate: bool,
 9921    window: &mut Window,
 9922    cx: &mut App,
 9923) {
 9924    let Some((item_ix, item_handle)) = source
 9925        .read(cx)
 9926        .items()
 9927        .enumerate()
 9928        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 9929        .map(|(ix, item)| (ix, item.clone()))
 9930    else {
 9931        // Tab was closed during drag
 9932        return;
 9933    };
 9934
 9935    if source != destination {
 9936        // Close item from previous pane
 9937        source.update(cx, |source, cx| {
 9938            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 9939        });
 9940    }
 9941
 9942    // This automatically removes duplicate items in the pane
 9943    destination.update(cx, |destination, cx| {
 9944        destination.add_item_inner(
 9945            item_handle,
 9946            activate,
 9947            activate,
 9948            activate,
 9949            Some(destination_index),
 9950            window,
 9951            cx,
 9952        );
 9953        if activate {
 9954            window.focus(&destination.focus_handle(cx), cx)
 9955        }
 9956    });
 9957}
 9958
 9959pub fn move_active_item(
 9960    source: &Entity<Pane>,
 9961    destination: &Entity<Pane>,
 9962    focus_destination: bool,
 9963    close_if_empty: bool,
 9964    window: &mut Window,
 9965    cx: &mut App,
 9966) {
 9967    if source == destination {
 9968        return;
 9969    }
 9970    let Some(active_item) = source.read(cx).active_item() else {
 9971        return;
 9972    };
 9973    source.update(cx, |source_pane, cx| {
 9974        let item_id = active_item.item_id();
 9975        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 9976        destination.update(cx, |target_pane, cx| {
 9977            target_pane.add_item(
 9978                active_item,
 9979                focus_destination,
 9980                focus_destination,
 9981                Some(target_pane.items_len()),
 9982                window,
 9983                cx,
 9984            );
 9985        });
 9986    });
 9987}
 9988
 9989pub fn clone_active_item(
 9990    workspace_id: Option<WorkspaceId>,
 9991    source: &Entity<Pane>,
 9992    destination: &Entity<Pane>,
 9993    focus_destination: bool,
 9994    window: &mut Window,
 9995    cx: &mut App,
 9996) {
 9997    if source == destination {
 9998        return;
 9999    }
10000    let Some(active_item) = source.read(cx).active_item() else {
10001        return;
10002    };
10003    if !active_item.can_split(cx) {
10004        return;
10005    }
10006    let destination = destination.downgrade();
10007    let task = active_item.clone_on_split(workspace_id, window, cx);
10008    window
10009        .spawn(cx, async move |cx| {
10010            let Some(clone) = task.await else {
10011                return;
10012            };
10013            destination
10014                .update_in(cx, |target_pane, window, cx| {
10015                    target_pane.add_item(
10016                        clone,
10017                        focus_destination,
10018                        focus_destination,
10019                        Some(target_pane.items_len()),
10020                        window,
10021                        cx,
10022                    );
10023                })
10024                .log_err();
10025        })
10026        .detach();
10027}
10028
10029#[derive(Debug)]
10030pub struct WorkspacePosition {
10031    pub window_bounds: Option<WindowBounds>,
10032    pub display: Option<Uuid>,
10033    pub centered_layout: bool,
10034}
10035
10036pub fn remote_workspace_position_from_db(
10037    connection_options: RemoteConnectionOptions,
10038    paths_to_open: &[PathBuf],
10039    cx: &App,
10040) -> Task<Result<WorkspacePosition>> {
10041    let paths = paths_to_open.to_vec();
10042    let db = WorkspaceDb::global(cx);
10043    let kvp = db::kvp::KeyValueStore::global(cx);
10044
10045    cx.background_spawn(async move {
10046        let remote_connection_id = db
10047            .get_or_create_remote_connection(connection_options)
10048            .await
10049            .context("fetching serialized ssh project")?;
10050        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10051
10052        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10053            (Some(WindowBounds::Windowed(bounds)), None)
10054        } else {
10055            let restorable_bounds = serialized_workspace
10056                .as_ref()
10057                .and_then(|workspace| {
10058                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10059                })
10060                .or_else(|| persistence::read_default_window_bounds(&kvp));
10061
10062            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10063                (Some(serialized_bounds), Some(serialized_display))
10064            } else {
10065                (None, None)
10066            }
10067        };
10068
10069        let centered_layout = serialized_workspace
10070            .as_ref()
10071            .map(|w| w.centered_layout)
10072            .unwrap_or(false);
10073
10074        Ok(WorkspacePosition {
10075            window_bounds,
10076            display,
10077            centered_layout,
10078        })
10079    })
10080}
10081
10082pub fn with_active_or_new_workspace(
10083    cx: &mut App,
10084    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10085) {
10086    match cx
10087        .active_window()
10088        .and_then(|w| w.downcast::<MultiWorkspace>())
10089    {
10090        Some(multi_workspace) => {
10091            cx.defer(move |cx| {
10092                multi_workspace
10093                    .update(cx, |multi_workspace, window, cx| {
10094                        let workspace = multi_workspace.workspace().clone();
10095                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10096                    })
10097                    .log_err();
10098            });
10099        }
10100        None => {
10101            let app_state = AppState::global(cx);
10102            if let Some(app_state) = app_state.upgrade() {
10103                open_new(
10104                    OpenOptions::default(),
10105                    app_state,
10106                    cx,
10107                    move |workspace, window, cx| f(workspace, window, cx),
10108                )
10109                .detach_and_log_err(cx);
10110            }
10111        }
10112    }
10113}
10114
10115#[cfg(test)]
10116mod tests {
10117    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10118
10119    use super::*;
10120    use crate::{
10121        dock::{PanelEvent, test::TestPanel},
10122        item::{
10123            ItemBufferKind, ItemEvent,
10124            test::{TestItem, TestProjectItem},
10125        },
10126    };
10127    use fs::FakeFs;
10128    use gpui::{
10129        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10130        UpdateGlobal, VisualTestContext, px,
10131    };
10132    use project::{Project, ProjectEntryId};
10133    use serde_json::json;
10134    use settings::SettingsStore;
10135    use util::path;
10136    use util::rel_path::rel_path;
10137
10138    #[gpui::test]
10139    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10140        init_test(cx);
10141
10142        let fs = FakeFs::new(cx.executor());
10143        let project = Project::test(fs, [], cx).await;
10144        let (workspace, cx) =
10145            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10146
10147        // Adding an item with no ambiguity renders the tab without detail.
10148        let item1 = cx.new(|cx| {
10149            let mut item = TestItem::new(cx);
10150            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10151            item
10152        });
10153        workspace.update_in(cx, |workspace, window, cx| {
10154            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10155        });
10156        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10157
10158        // Adding an item that creates ambiguity increases the level of detail on
10159        // both tabs.
10160        let item2 = cx.new_window_entity(|_window, cx| {
10161            let mut item = TestItem::new(cx);
10162            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10163            item
10164        });
10165        workspace.update_in(cx, |workspace, window, cx| {
10166            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10167        });
10168        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10169        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10170
10171        // Adding an item that creates ambiguity increases the level of detail only
10172        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10173        // we stop at the highest detail available.
10174        let item3 = cx.new(|cx| {
10175            let mut item = TestItem::new(cx);
10176            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10177            item
10178        });
10179        workspace.update_in(cx, |workspace, window, cx| {
10180            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10181        });
10182        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10183        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10184        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10185    }
10186
10187    #[gpui::test]
10188    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10189        init_test(cx);
10190
10191        let fs = FakeFs::new(cx.executor());
10192        fs.insert_tree(
10193            "/root1",
10194            json!({
10195                "one.txt": "",
10196                "two.txt": "",
10197            }),
10198        )
10199        .await;
10200        fs.insert_tree(
10201            "/root2",
10202            json!({
10203                "three.txt": "",
10204            }),
10205        )
10206        .await;
10207
10208        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10209        let (workspace, cx) =
10210            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10211        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10212        let worktree_id = project.update(cx, |project, cx| {
10213            project.worktrees(cx).next().unwrap().read(cx).id()
10214        });
10215
10216        let item1 = cx.new(|cx| {
10217            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10218        });
10219        let item2 = cx.new(|cx| {
10220            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10221        });
10222
10223        // Add an item to an empty pane
10224        workspace.update_in(cx, |workspace, window, cx| {
10225            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10226        });
10227        project.update(cx, |project, cx| {
10228            assert_eq!(
10229                project.active_entry(),
10230                project
10231                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10232                    .map(|e| e.id)
10233            );
10234        });
10235        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10236
10237        // Add a second item to a non-empty pane
10238        workspace.update_in(cx, |workspace, window, cx| {
10239            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10240        });
10241        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10242        project.update(cx, |project, cx| {
10243            assert_eq!(
10244                project.active_entry(),
10245                project
10246                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10247                    .map(|e| e.id)
10248            );
10249        });
10250
10251        // Close the active item
10252        pane.update_in(cx, |pane, window, cx| {
10253            pane.close_active_item(&Default::default(), window, cx)
10254        })
10255        .await
10256        .unwrap();
10257        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10258        project.update(cx, |project, cx| {
10259            assert_eq!(
10260                project.active_entry(),
10261                project
10262                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10263                    .map(|e| e.id)
10264            );
10265        });
10266
10267        // Add a project folder
10268        project
10269            .update(cx, |project, cx| {
10270                project.find_or_create_worktree("root2", true, cx)
10271            })
10272            .await
10273            .unwrap();
10274        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10275
10276        // Remove a project folder
10277        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10278        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10279    }
10280
10281    #[gpui::test]
10282    async fn test_close_window(cx: &mut TestAppContext) {
10283        init_test(cx);
10284
10285        let fs = FakeFs::new(cx.executor());
10286        fs.insert_tree("/root", json!({ "one": "" })).await;
10287
10288        let project = Project::test(fs, ["root".as_ref()], cx).await;
10289        let (workspace, cx) =
10290            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10291
10292        // When there are no dirty items, there's nothing to do.
10293        let item1 = cx.new(TestItem::new);
10294        workspace.update_in(cx, |w, window, cx| {
10295            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10296        });
10297        let task = workspace.update_in(cx, |w, window, cx| {
10298            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10299        });
10300        assert!(task.await.unwrap());
10301
10302        // When there are dirty untitled items, prompt to save each one. If the user
10303        // cancels any prompt, then abort.
10304        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10305        let item3 = cx.new(|cx| {
10306            TestItem::new(cx)
10307                .with_dirty(true)
10308                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10309        });
10310        workspace.update_in(cx, |w, window, cx| {
10311            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10312            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10313        });
10314        let task = workspace.update_in(cx, |w, window, cx| {
10315            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10316        });
10317        cx.executor().run_until_parked();
10318        cx.simulate_prompt_answer("Cancel"); // cancel save all
10319        cx.executor().run_until_parked();
10320        assert!(!cx.has_pending_prompt());
10321        assert!(!task.await.unwrap());
10322    }
10323
10324    #[gpui::test]
10325    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10326        init_test(cx);
10327
10328        let fs = FakeFs::new(cx.executor());
10329        fs.insert_tree("/root", json!({ "one": "" })).await;
10330
10331        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10332        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10333        let multi_workspace_handle =
10334            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10335        cx.run_until_parked();
10336
10337        let workspace_a = multi_workspace_handle
10338            .read_with(cx, |mw, _| mw.workspace().clone())
10339            .unwrap();
10340
10341        let workspace_b = multi_workspace_handle
10342            .update(cx, |mw, window, cx| {
10343                mw.test_add_workspace(project_b, window, cx)
10344            })
10345            .unwrap();
10346
10347        // Activate workspace A
10348        multi_workspace_handle
10349            .update(cx, |mw, window, cx| {
10350                mw.activate_index(0, window, cx);
10351            })
10352            .unwrap();
10353
10354        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10355
10356        // Workspace A has a clean item
10357        let item_a = cx.new(TestItem::new);
10358        workspace_a.update_in(cx, |w, window, cx| {
10359            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10360        });
10361
10362        // Workspace B has a dirty item
10363        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10364        workspace_b.update_in(cx, |w, window, cx| {
10365            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10366        });
10367
10368        // Verify workspace A is active
10369        multi_workspace_handle
10370            .read_with(cx, |mw, _| {
10371                assert_eq!(mw.active_workspace_index(), 0);
10372            })
10373            .unwrap();
10374
10375        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10376        multi_workspace_handle
10377            .update(cx, |mw, window, cx| {
10378                mw.close_window(&CloseWindow, window, cx);
10379            })
10380            .unwrap();
10381        cx.run_until_parked();
10382
10383        // Workspace B should now be active since it has dirty items that need attention
10384        multi_workspace_handle
10385            .read_with(cx, |mw, _| {
10386                assert_eq!(
10387                    mw.active_workspace_index(),
10388                    1,
10389                    "workspace B should be activated when it prompts"
10390                );
10391            })
10392            .unwrap();
10393
10394        // User cancels the save prompt from workspace B
10395        cx.simulate_prompt_answer("Cancel");
10396        cx.run_until_parked();
10397
10398        // Window should still exist because workspace B's close was cancelled
10399        assert!(
10400            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10401            "window should still exist after cancelling one workspace's close"
10402        );
10403    }
10404
10405    #[gpui::test]
10406    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10407        init_test(cx);
10408
10409        // Register TestItem as a serializable item
10410        cx.update(|cx| {
10411            register_serializable_item::<TestItem>(cx);
10412        });
10413
10414        let fs = FakeFs::new(cx.executor());
10415        fs.insert_tree("/root", json!({ "one": "" })).await;
10416
10417        let project = Project::test(fs, ["root".as_ref()], cx).await;
10418        let (workspace, cx) =
10419            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10420
10421        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10422        let item1 = cx.new(|cx| {
10423            TestItem::new(cx)
10424                .with_dirty(true)
10425                .with_serialize(|| Some(Task::ready(Ok(()))))
10426        });
10427        let item2 = cx.new(|cx| {
10428            TestItem::new(cx)
10429                .with_dirty(true)
10430                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10431                .with_serialize(|| Some(Task::ready(Ok(()))))
10432        });
10433        workspace.update_in(cx, |w, window, cx| {
10434            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10435            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10436        });
10437        let task = workspace.update_in(cx, |w, window, cx| {
10438            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10439        });
10440        assert!(task.await.unwrap());
10441    }
10442
10443    #[gpui::test]
10444    async fn test_close_pane_items(cx: &mut TestAppContext) {
10445        init_test(cx);
10446
10447        let fs = FakeFs::new(cx.executor());
10448
10449        let project = Project::test(fs, None, cx).await;
10450        let (workspace, cx) =
10451            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10452
10453        let item1 = cx.new(|cx| {
10454            TestItem::new(cx)
10455                .with_dirty(true)
10456                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10457        });
10458        let item2 = cx.new(|cx| {
10459            TestItem::new(cx)
10460                .with_dirty(true)
10461                .with_conflict(true)
10462                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10463        });
10464        let item3 = cx.new(|cx| {
10465            TestItem::new(cx)
10466                .with_dirty(true)
10467                .with_conflict(true)
10468                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10469        });
10470        let item4 = cx.new(|cx| {
10471            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10472                let project_item = TestProjectItem::new_untitled(cx);
10473                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10474                project_item
10475            }])
10476        });
10477        let pane = workspace.update_in(cx, |workspace, window, cx| {
10478            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10479            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10480            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10481            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10482            workspace.active_pane().clone()
10483        });
10484
10485        let close_items = pane.update_in(cx, |pane, window, cx| {
10486            pane.activate_item(1, true, true, window, cx);
10487            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10488            let item1_id = item1.item_id();
10489            let item3_id = item3.item_id();
10490            let item4_id = item4.item_id();
10491            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10492                [item1_id, item3_id, item4_id].contains(&id)
10493            })
10494        });
10495        cx.executor().run_until_parked();
10496
10497        assert!(cx.has_pending_prompt());
10498        cx.simulate_prompt_answer("Save all");
10499
10500        cx.executor().run_until_parked();
10501
10502        // Item 1 is saved. There's a prompt to save item 3.
10503        pane.update(cx, |pane, cx| {
10504            assert_eq!(item1.read(cx).save_count, 1);
10505            assert_eq!(item1.read(cx).save_as_count, 0);
10506            assert_eq!(item1.read(cx).reload_count, 0);
10507            assert_eq!(pane.items_len(), 3);
10508            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10509        });
10510        assert!(cx.has_pending_prompt());
10511
10512        // Cancel saving item 3.
10513        cx.simulate_prompt_answer("Discard");
10514        cx.executor().run_until_parked();
10515
10516        // Item 3 is reloaded. There's a prompt to save item 4.
10517        pane.update(cx, |pane, cx| {
10518            assert_eq!(item3.read(cx).save_count, 0);
10519            assert_eq!(item3.read(cx).save_as_count, 0);
10520            assert_eq!(item3.read(cx).reload_count, 1);
10521            assert_eq!(pane.items_len(), 2);
10522            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10523        });
10524
10525        // There's a prompt for a path for item 4.
10526        cx.simulate_new_path_selection(|_| Some(Default::default()));
10527        close_items.await.unwrap();
10528
10529        // The requested items are closed.
10530        pane.update(cx, |pane, cx| {
10531            assert_eq!(item4.read(cx).save_count, 0);
10532            assert_eq!(item4.read(cx).save_as_count, 1);
10533            assert_eq!(item4.read(cx).reload_count, 0);
10534            assert_eq!(pane.items_len(), 1);
10535            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10536        });
10537    }
10538
10539    #[gpui::test]
10540    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10541        init_test(cx);
10542
10543        let fs = FakeFs::new(cx.executor());
10544        let project = Project::test(fs, [], cx).await;
10545        let (workspace, cx) =
10546            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10547
10548        // Create several workspace items with single project entries, and two
10549        // workspace items with multiple project entries.
10550        let single_entry_items = (0..=4)
10551            .map(|project_entry_id| {
10552                cx.new(|cx| {
10553                    TestItem::new(cx)
10554                        .with_dirty(true)
10555                        .with_project_items(&[dirty_project_item(
10556                            project_entry_id,
10557                            &format!("{project_entry_id}.txt"),
10558                            cx,
10559                        )])
10560                })
10561            })
10562            .collect::<Vec<_>>();
10563        let item_2_3 = cx.new(|cx| {
10564            TestItem::new(cx)
10565                .with_dirty(true)
10566                .with_buffer_kind(ItemBufferKind::Multibuffer)
10567                .with_project_items(&[
10568                    single_entry_items[2].read(cx).project_items[0].clone(),
10569                    single_entry_items[3].read(cx).project_items[0].clone(),
10570                ])
10571        });
10572        let item_3_4 = cx.new(|cx| {
10573            TestItem::new(cx)
10574                .with_dirty(true)
10575                .with_buffer_kind(ItemBufferKind::Multibuffer)
10576                .with_project_items(&[
10577                    single_entry_items[3].read(cx).project_items[0].clone(),
10578                    single_entry_items[4].read(cx).project_items[0].clone(),
10579                ])
10580        });
10581
10582        // Create two panes that contain the following project entries:
10583        //   left pane:
10584        //     multi-entry items:   (2, 3)
10585        //     single-entry items:  0, 2, 3, 4
10586        //   right pane:
10587        //     single-entry items:  4, 1
10588        //     multi-entry items:   (3, 4)
10589        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10590            let left_pane = workspace.active_pane().clone();
10591            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10592            workspace.add_item_to_active_pane(
10593                single_entry_items[0].boxed_clone(),
10594                None,
10595                true,
10596                window,
10597                cx,
10598            );
10599            workspace.add_item_to_active_pane(
10600                single_entry_items[2].boxed_clone(),
10601                None,
10602                true,
10603                window,
10604                cx,
10605            );
10606            workspace.add_item_to_active_pane(
10607                single_entry_items[3].boxed_clone(),
10608                None,
10609                true,
10610                window,
10611                cx,
10612            );
10613            workspace.add_item_to_active_pane(
10614                single_entry_items[4].boxed_clone(),
10615                None,
10616                true,
10617                window,
10618                cx,
10619            );
10620
10621            let right_pane =
10622                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10623
10624            let boxed_clone = single_entry_items[1].boxed_clone();
10625            let right_pane = window.spawn(cx, async move |cx| {
10626                right_pane.await.inspect(|right_pane| {
10627                    right_pane
10628                        .update_in(cx, |pane, window, cx| {
10629                            pane.add_item(boxed_clone, true, true, None, window, cx);
10630                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10631                        })
10632                        .unwrap();
10633                })
10634            });
10635
10636            (left_pane, right_pane)
10637        });
10638        let right_pane = right_pane.await.unwrap();
10639        cx.focus(&right_pane);
10640
10641        let close = right_pane.update_in(cx, |pane, window, cx| {
10642            pane.close_all_items(&CloseAllItems::default(), window, cx)
10643                .unwrap()
10644        });
10645        cx.executor().run_until_parked();
10646
10647        let msg = cx.pending_prompt().unwrap().0;
10648        assert!(msg.contains("1.txt"));
10649        assert!(!msg.contains("2.txt"));
10650        assert!(!msg.contains("3.txt"));
10651        assert!(!msg.contains("4.txt"));
10652
10653        // With best-effort close, cancelling item 1 keeps it open but items 4
10654        // and (3,4) still close since their entries exist in left pane.
10655        cx.simulate_prompt_answer("Cancel");
10656        close.await;
10657
10658        right_pane.read_with(cx, |pane, _| {
10659            assert_eq!(pane.items_len(), 1);
10660        });
10661
10662        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10663        left_pane
10664            .update_in(cx, |left_pane, window, cx| {
10665                left_pane.close_item_by_id(
10666                    single_entry_items[3].entity_id(),
10667                    SaveIntent::Skip,
10668                    window,
10669                    cx,
10670                )
10671            })
10672            .await
10673            .unwrap();
10674
10675        let close = left_pane.update_in(cx, |pane, window, cx| {
10676            pane.close_all_items(&CloseAllItems::default(), window, cx)
10677                .unwrap()
10678        });
10679        cx.executor().run_until_parked();
10680
10681        let details = cx.pending_prompt().unwrap().1;
10682        assert!(details.contains("0.txt"));
10683        assert!(details.contains("3.txt"));
10684        assert!(details.contains("4.txt"));
10685        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10686        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10687        // assert!(!details.contains("2.txt"));
10688
10689        cx.simulate_prompt_answer("Save all");
10690        cx.executor().run_until_parked();
10691        close.await;
10692
10693        left_pane.read_with(cx, |pane, _| {
10694            assert_eq!(pane.items_len(), 0);
10695        });
10696    }
10697
10698    #[gpui::test]
10699    async fn test_autosave(cx: &mut gpui::TestAppContext) {
10700        init_test(cx);
10701
10702        let fs = FakeFs::new(cx.executor());
10703        let project = Project::test(fs, [], cx).await;
10704        let (workspace, cx) =
10705            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10706        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10707
10708        let item = cx.new(|cx| {
10709            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10710        });
10711        let item_id = item.entity_id();
10712        workspace.update_in(cx, |workspace, window, cx| {
10713            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10714        });
10715
10716        // Autosave on window change.
10717        item.update(cx, |item, cx| {
10718            SettingsStore::update_global(cx, |settings, cx| {
10719                settings.update_user_settings(cx, |settings| {
10720                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10721                })
10722            });
10723            item.is_dirty = true;
10724        });
10725
10726        // Deactivating the window saves the file.
10727        cx.deactivate_window();
10728        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10729
10730        // Re-activating the window doesn't save the file.
10731        cx.update(|window, _| window.activate_window());
10732        cx.executor().run_until_parked();
10733        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10734
10735        // Autosave on focus change.
10736        item.update_in(cx, |item, window, cx| {
10737            cx.focus_self(window);
10738            SettingsStore::update_global(cx, |settings, cx| {
10739                settings.update_user_settings(cx, |settings| {
10740                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10741                })
10742            });
10743            item.is_dirty = true;
10744        });
10745        // Blurring the item saves the file.
10746        item.update_in(cx, |_, window, _| window.blur());
10747        cx.executor().run_until_parked();
10748        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10749
10750        // Deactivating the window still saves the file.
10751        item.update_in(cx, |item, window, cx| {
10752            cx.focus_self(window);
10753            item.is_dirty = true;
10754        });
10755        cx.deactivate_window();
10756        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10757
10758        // Autosave after delay.
10759        item.update(cx, |item, cx| {
10760            SettingsStore::update_global(cx, |settings, cx| {
10761                settings.update_user_settings(cx, |settings| {
10762                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10763                        milliseconds: 500.into(),
10764                    });
10765                })
10766            });
10767            item.is_dirty = true;
10768            cx.emit(ItemEvent::Edit);
10769        });
10770
10771        // Delay hasn't fully expired, so the file is still dirty and unsaved.
10772        cx.executor().advance_clock(Duration::from_millis(250));
10773        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10774
10775        // After delay expires, the file is saved.
10776        cx.executor().advance_clock(Duration::from_millis(250));
10777        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10778
10779        // Autosave after delay, should save earlier than delay if tab is closed
10780        item.update(cx, |item, cx| {
10781            item.is_dirty = true;
10782            cx.emit(ItemEvent::Edit);
10783        });
10784        cx.executor().advance_clock(Duration::from_millis(250));
10785        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10786
10787        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10788        pane.update_in(cx, |pane, window, cx| {
10789            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10790        })
10791        .await
10792        .unwrap();
10793        assert!(!cx.has_pending_prompt());
10794        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10795
10796        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10797        workspace.update_in(cx, |workspace, window, cx| {
10798            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10799        });
10800        item.update_in(cx, |item, _window, cx| {
10801            item.is_dirty = true;
10802            for project_item in &mut item.project_items {
10803                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10804            }
10805        });
10806        cx.run_until_parked();
10807        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10808
10809        // Autosave on focus change, ensuring closing the tab counts as such.
10810        item.update(cx, |item, cx| {
10811            SettingsStore::update_global(cx, |settings, cx| {
10812                settings.update_user_settings(cx, |settings| {
10813                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10814                })
10815            });
10816            item.is_dirty = true;
10817            for project_item in &mut item.project_items {
10818                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10819            }
10820        });
10821
10822        pane.update_in(cx, |pane, window, cx| {
10823            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10824        })
10825        .await
10826        .unwrap();
10827        assert!(!cx.has_pending_prompt());
10828        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10829
10830        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10831        workspace.update_in(cx, |workspace, window, cx| {
10832            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10833        });
10834        item.update_in(cx, |item, window, cx| {
10835            item.project_items[0].update(cx, |item, _| {
10836                item.entry_id = None;
10837            });
10838            item.is_dirty = true;
10839            window.blur();
10840        });
10841        cx.run_until_parked();
10842        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10843
10844        // Ensure autosave is prevented for deleted files also when closing the buffer.
10845        let _close_items = pane.update_in(cx, |pane, window, cx| {
10846            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10847        });
10848        cx.run_until_parked();
10849        assert!(cx.has_pending_prompt());
10850        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10851    }
10852
10853    #[gpui::test]
10854    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
10855        init_test(cx);
10856
10857        let fs = FakeFs::new(cx.executor());
10858        let project = Project::test(fs, [], cx).await;
10859        let (workspace, cx) =
10860            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10861
10862        // Create a multibuffer-like item with two child focus handles,
10863        // simulating individual buffer editors within a multibuffer.
10864        let item = cx.new(|cx| {
10865            TestItem::new(cx)
10866                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10867                .with_child_focus_handles(2, cx)
10868        });
10869        workspace.update_in(cx, |workspace, window, cx| {
10870            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10871        });
10872
10873        // Set autosave to OnFocusChange and focus the first child handle,
10874        // simulating the user's cursor being inside one of the multibuffer's excerpts.
10875        item.update_in(cx, |item, window, cx| {
10876            SettingsStore::update_global(cx, |settings, cx| {
10877                settings.update_user_settings(cx, |settings| {
10878                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10879                })
10880            });
10881            item.is_dirty = true;
10882            window.focus(&item.child_focus_handles[0], cx);
10883        });
10884        cx.executor().run_until_parked();
10885        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
10886
10887        // Moving focus from one child to another within the same item should
10888        // NOT trigger autosave — focus is still within the item's focus hierarchy.
10889        item.update_in(cx, |item, window, cx| {
10890            window.focus(&item.child_focus_handles[1], cx);
10891        });
10892        cx.executor().run_until_parked();
10893        item.read_with(cx, |item, _| {
10894            assert_eq!(
10895                item.save_count, 0,
10896                "Switching focus between children within the same item should not autosave"
10897            );
10898        });
10899
10900        // Blurring the item saves the file. This is the core regression scenario:
10901        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
10902        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
10903        // the leaf is always a child focus handle, so `on_blur` never detected
10904        // focus leaving the item.
10905        item.update_in(cx, |_, window, _| window.blur());
10906        cx.executor().run_until_parked();
10907        item.read_with(cx, |item, _| {
10908            assert_eq!(
10909                item.save_count, 1,
10910                "Blurring should trigger autosave when focus was on a child of the item"
10911            );
10912        });
10913
10914        // Deactivating the window should also trigger autosave when a child of
10915        // the multibuffer item currently owns focus.
10916        item.update_in(cx, |item, window, cx| {
10917            item.is_dirty = true;
10918            window.focus(&item.child_focus_handles[0], cx);
10919        });
10920        cx.executor().run_until_parked();
10921        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10922
10923        cx.deactivate_window();
10924        item.read_with(cx, |item, _| {
10925            assert_eq!(
10926                item.save_count, 2,
10927                "Deactivating window should trigger autosave when focus was on a child"
10928            );
10929        });
10930    }
10931
10932    #[gpui::test]
10933    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10934        init_test(cx);
10935
10936        let fs = FakeFs::new(cx.executor());
10937
10938        let project = Project::test(fs, [], cx).await;
10939        let (workspace, cx) =
10940            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10941
10942        let item = cx.new(|cx| {
10943            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10944        });
10945        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10946        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10947        let toolbar_notify_count = Rc::new(RefCell::new(0));
10948
10949        workspace.update_in(cx, |workspace, window, cx| {
10950            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10951            let toolbar_notification_count = toolbar_notify_count.clone();
10952            cx.observe_in(&toolbar, window, move |_, _, _, _| {
10953                *toolbar_notification_count.borrow_mut() += 1
10954            })
10955            .detach();
10956        });
10957
10958        pane.read_with(cx, |pane, _| {
10959            assert!(!pane.can_navigate_backward());
10960            assert!(!pane.can_navigate_forward());
10961        });
10962
10963        item.update_in(cx, |item, _, cx| {
10964            item.set_state("one".to_string(), cx);
10965        });
10966
10967        // Toolbar must be notified to re-render the navigation buttons
10968        assert_eq!(*toolbar_notify_count.borrow(), 1);
10969
10970        pane.read_with(cx, |pane, _| {
10971            assert!(pane.can_navigate_backward());
10972            assert!(!pane.can_navigate_forward());
10973        });
10974
10975        workspace
10976            .update_in(cx, |workspace, window, cx| {
10977                workspace.go_back(pane.downgrade(), window, cx)
10978            })
10979            .await
10980            .unwrap();
10981
10982        assert_eq!(*toolbar_notify_count.borrow(), 2);
10983        pane.read_with(cx, |pane, _| {
10984            assert!(!pane.can_navigate_backward());
10985            assert!(pane.can_navigate_forward());
10986        });
10987    }
10988
10989    #[gpui::test]
10990    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
10991        init_test(cx);
10992        let fs = FakeFs::new(cx.executor());
10993        let project = Project::test(fs, [], cx).await;
10994        let (multi_workspace, cx) =
10995            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
10996        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
10997
10998        workspace.update_in(cx, |workspace, window, cx| {
10999            let first_item = cx.new(|cx| {
11000                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11001            });
11002            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11003            workspace.split_pane(
11004                workspace.active_pane().clone(),
11005                SplitDirection::Right,
11006                window,
11007                cx,
11008            );
11009            workspace.split_pane(
11010                workspace.active_pane().clone(),
11011                SplitDirection::Right,
11012                window,
11013                cx,
11014            );
11015        });
11016
11017        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11018            let panes = workspace.center.panes();
11019            assert!(panes.len() >= 2);
11020            (
11021                panes.first().expect("at least one pane").entity_id(),
11022                panes.last().expect("at least one pane").entity_id(),
11023            )
11024        });
11025
11026        workspace.update_in(cx, |workspace, window, cx| {
11027            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11028        });
11029        workspace.update(cx, |workspace, _| {
11030            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11031            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11032        });
11033
11034        cx.dispatch_action(ActivateLastPane);
11035
11036        workspace.update(cx, |workspace, _| {
11037            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11038        });
11039    }
11040
11041    #[gpui::test]
11042    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11043        init_test(cx);
11044        let fs = FakeFs::new(cx.executor());
11045
11046        let project = Project::test(fs, [], cx).await;
11047        let (workspace, cx) =
11048            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11049
11050        let panel = workspace.update_in(cx, |workspace, window, cx| {
11051            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11052            workspace.add_panel(panel.clone(), window, cx);
11053
11054            workspace
11055                .right_dock()
11056                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11057
11058            panel
11059        });
11060
11061        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11062        pane.update_in(cx, |pane, window, cx| {
11063            let item = cx.new(TestItem::new);
11064            pane.add_item(Box::new(item), true, true, None, window, cx);
11065        });
11066
11067        // Transfer focus from center to panel
11068        workspace.update_in(cx, |workspace, window, cx| {
11069            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11070        });
11071
11072        workspace.update_in(cx, |workspace, window, cx| {
11073            assert!(workspace.right_dock().read(cx).is_open());
11074            assert!(!panel.is_zoomed(window, cx));
11075            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11076        });
11077
11078        // Transfer focus from panel to center
11079        workspace.update_in(cx, |workspace, window, cx| {
11080            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11081        });
11082
11083        workspace.update_in(cx, |workspace, window, cx| {
11084            assert!(workspace.right_dock().read(cx).is_open());
11085            assert!(!panel.is_zoomed(window, cx));
11086            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11087            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11088        });
11089
11090        // Close the dock
11091        workspace.update_in(cx, |workspace, window, cx| {
11092            workspace.toggle_dock(DockPosition::Right, window, cx);
11093        });
11094
11095        workspace.update_in(cx, |workspace, window, cx| {
11096            assert!(!workspace.right_dock().read(cx).is_open());
11097            assert!(!panel.is_zoomed(window, cx));
11098            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11099            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11100        });
11101
11102        // Open the dock
11103        workspace.update_in(cx, |workspace, window, cx| {
11104            workspace.toggle_dock(DockPosition::Right, window, cx);
11105        });
11106
11107        workspace.update_in(cx, |workspace, window, cx| {
11108            assert!(workspace.right_dock().read(cx).is_open());
11109            assert!(!panel.is_zoomed(window, cx));
11110            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11111        });
11112
11113        // Focus and zoom panel
11114        panel.update_in(cx, |panel, window, cx| {
11115            cx.focus_self(window);
11116            panel.set_zoomed(true, window, cx)
11117        });
11118
11119        workspace.update_in(cx, |workspace, window, cx| {
11120            assert!(workspace.right_dock().read(cx).is_open());
11121            assert!(panel.is_zoomed(window, cx));
11122            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11123        });
11124
11125        // Transfer focus to the center closes the dock
11126        workspace.update_in(cx, |workspace, window, cx| {
11127            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11128        });
11129
11130        workspace.update_in(cx, |workspace, window, cx| {
11131            assert!(!workspace.right_dock().read(cx).is_open());
11132            assert!(panel.is_zoomed(window, cx));
11133            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11134        });
11135
11136        // Transferring focus back to the panel keeps it zoomed
11137        workspace.update_in(cx, |workspace, window, cx| {
11138            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11139        });
11140
11141        workspace.update_in(cx, |workspace, window, cx| {
11142            assert!(workspace.right_dock().read(cx).is_open());
11143            assert!(panel.is_zoomed(window, cx));
11144            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11145        });
11146
11147        // Close the dock while it is zoomed
11148        workspace.update_in(cx, |workspace, window, cx| {
11149            workspace.toggle_dock(DockPosition::Right, window, cx)
11150        });
11151
11152        workspace.update_in(cx, |workspace, window, cx| {
11153            assert!(!workspace.right_dock().read(cx).is_open());
11154            assert!(panel.is_zoomed(window, cx));
11155            assert!(workspace.zoomed.is_none());
11156            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11157        });
11158
11159        // Opening the dock, when it's zoomed, retains focus
11160        workspace.update_in(cx, |workspace, window, cx| {
11161            workspace.toggle_dock(DockPosition::Right, window, cx)
11162        });
11163
11164        workspace.update_in(cx, |workspace, window, cx| {
11165            assert!(workspace.right_dock().read(cx).is_open());
11166            assert!(panel.is_zoomed(window, cx));
11167            assert!(workspace.zoomed.is_some());
11168            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11169        });
11170
11171        // Unzoom and close the panel, zoom the active pane.
11172        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11173        workspace.update_in(cx, |workspace, window, cx| {
11174            workspace.toggle_dock(DockPosition::Right, window, cx)
11175        });
11176        pane.update_in(cx, |pane, window, cx| {
11177            pane.toggle_zoom(&Default::default(), window, cx)
11178        });
11179
11180        // Opening a dock unzooms the pane.
11181        workspace.update_in(cx, |workspace, window, cx| {
11182            workspace.toggle_dock(DockPosition::Right, window, cx)
11183        });
11184        workspace.update_in(cx, |workspace, window, cx| {
11185            let pane = pane.read(cx);
11186            assert!(!pane.is_zoomed());
11187            assert!(!pane.focus_handle(cx).is_focused(window));
11188            assert!(workspace.right_dock().read(cx).is_open());
11189            assert!(workspace.zoomed.is_none());
11190        });
11191    }
11192
11193    #[gpui::test]
11194    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11195        init_test(cx);
11196        let fs = FakeFs::new(cx.executor());
11197
11198        let project = Project::test(fs, [], cx).await;
11199        let (workspace, cx) =
11200            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11201
11202        let panel = workspace.update_in(cx, |workspace, window, cx| {
11203            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11204            workspace.add_panel(panel.clone(), window, cx);
11205            panel
11206        });
11207
11208        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11209        pane.update_in(cx, |pane, window, cx| {
11210            let item = cx.new(TestItem::new);
11211            pane.add_item(Box::new(item), true, true, None, window, cx);
11212        });
11213
11214        // Enable close_panel_on_toggle
11215        cx.update_global(|store: &mut SettingsStore, cx| {
11216            store.update_user_settings(cx, |settings| {
11217                settings.workspace.close_panel_on_toggle = Some(true);
11218            });
11219        });
11220
11221        // Panel starts closed. Toggling should open and focus it.
11222        workspace.update_in(cx, |workspace, window, cx| {
11223            assert!(!workspace.right_dock().read(cx).is_open());
11224            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11225        });
11226
11227        workspace.update_in(cx, |workspace, window, cx| {
11228            assert!(
11229                workspace.right_dock().read(cx).is_open(),
11230                "Dock should be open after toggling from center"
11231            );
11232            assert!(
11233                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11234                "Panel should be focused after toggling from center"
11235            );
11236        });
11237
11238        // Panel is open and focused. Toggling should close the panel and
11239        // return focus to the center.
11240        workspace.update_in(cx, |workspace, window, cx| {
11241            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11242        });
11243
11244        workspace.update_in(cx, |workspace, window, cx| {
11245            assert!(
11246                !workspace.right_dock().read(cx).is_open(),
11247                "Dock should be closed after toggling from focused panel"
11248            );
11249            assert!(
11250                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11251                "Panel should not be focused after toggling from focused panel"
11252            );
11253        });
11254
11255        // Open the dock and focus something else so the panel is open but not
11256        // focused. Toggling should focus the panel (not close it).
11257        workspace.update_in(cx, |workspace, window, cx| {
11258            workspace
11259                .right_dock()
11260                .update(cx, |dock, cx| dock.set_open(true, window, cx));
11261            window.focus(&pane.read(cx).focus_handle(cx), cx);
11262        });
11263
11264        workspace.update_in(cx, |workspace, window, cx| {
11265            assert!(workspace.right_dock().read(cx).is_open());
11266            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11267            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11268        });
11269
11270        workspace.update_in(cx, |workspace, window, cx| {
11271            assert!(
11272                workspace.right_dock().read(cx).is_open(),
11273                "Dock should remain open when toggling focuses an open-but-unfocused panel"
11274            );
11275            assert!(
11276                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11277                "Panel should be focused after toggling an open-but-unfocused panel"
11278            );
11279        });
11280
11281        // Now disable the setting and verify the original behavior: toggling
11282        // from a focused panel moves focus to center but leaves the dock open.
11283        cx.update_global(|store: &mut SettingsStore, cx| {
11284            store.update_user_settings(cx, |settings| {
11285                settings.workspace.close_panel_on_toggle = Some(false);
11286            });
11287        });
11288
11289        workspace.update_in(cx, |workspace, window, cx| {
11290            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11291        });
11292
11293        workspace.update_in(cx, |workspace, window, cx| {
11294            assert!(
11295                workspace.right_dock().read(cx).is_open(),
11296                "Dock should remain open when setting is disabled"
11297            );
11298            assert!(
11299                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11300                "Panel should not be focused after toggling with setting disabled"
11301            );
11302        });
11303    }
11304
11305    #[gpui::test]
11306    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11307        init_test(cx);
11308        let fs = FakeFs::new(cx.executor());
11309
11310        let project = Project::test(fs, [], cx).await;
11311        let (workspace, cx) =
11312            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11313
11314        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11315            workspace.active_pane().clone()
11316        });
11317
11318        // Add an item to the pane so it can be zoomed
11319        workspace.update_in(cx, |workspace, window, cx| {
11320            let item = cx.new(TestItem::new);
11321            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11322        });
11323
11324        // Initially not zoomed
11325        workspace.update_in(cx, |workspace, _window, cx| {
11326            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11327            assert!(
11328                workspace.zoomed.is_none(),
11329                "Workspace should track no zoomed pane"
11330            );
11331            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11332        });
11333
11334        // Zoom In
11335        pane.update_in(cx, |pane, window, cx| {
11336            pane.zoom_in(&crate::ZoomIn, window, cx);
11337        });
11338
11339        workspace.update_in(cx, |workspace, window, cx| {
11340            assert!(
11341                pane.read(cx).is_zoomed(),
11342                "Pane should be zoomed after ZoomIn"
11343            );
11344            assert!(
11345                workspace.zoomed.is_some(),
11346                "Workspace should track the zoomed pane"
11347            );
11348            assert!(
11349                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11350                "ZoomIn should focus the pane"
11351            );
11352        });
11353
11354        // Zoom In again is a no-op
11355        pane.update_in(cx, |pane, window, cx| {
11356            pane.zoom_in(&crate::ZoomIn, window, cx);
11357        });
11358
11359        workspace.update_in(cx, |workspace, window, cx| {
11360            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11361            assert!(
11362                workspace.zoomed.is_some(),
11363                "Workspace still tracks zoomed pane"
11364            );
11365            assert!(
11366                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11367                "Pane remains focused after repeated ZoomIn"
11368            );
11369        });
11370
11371        // Zoom Out
11372        pane.update_in(cx, |pane, window, cx| {
11373            pane.zoom_out(&crate::ZoomOut, window, cx);
11374        });
11375
11376        workspace.update_in(cx, |workspace, _window, cx| {
11377            assert!(
11378                !pane.read(cx).is_zoomed(),
11379                "Pane should unzoom after ZoomOut"
11380            );
11381            assert!(
11382                workspace.zoomed.is_none(),
11383                "Workspace clears zoom tracking after ZoomOut"
11384            );
11385        });
11386
11387        // Zoom Out again is a no-op
11388        pane.update_in(cx, |pane, window, cx| {
11389            pane.zoom_out(&crate::ZoomOut, window, cx);
11390        });
11391
11392        workspace.update_in(cx, |workspace, _window, cx| {
11393            assert!(
11394                !pane.read(cx).is_zoomed(),
11395                "Second ZoomOut keeps pane unzoomed"
11396            );
11397            assert!(
11398                workspace.zoomed.is_none(),
11399                "Workspace remains without zoomed pane"
11400            );
11401        });
11402    }
11403
11404    #[gpui::test]
11405    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11406        init_test(cx);
11407        let fs = FakeFs::new(cx.executor());
11408
11409        let project = Project::test(fs, [], cx).await;
11410        let (workspace, cx) =
11411            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11412        workspace.update_in(cx, |workspace, window, cx| {
11413            // Open two docks
11414            let left_dock = workspace.dock_at_position(DockPosition::Left);
11415            let right_dock = workspace.dock_at_position(DockPosition::Right);
11416
11417            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11418            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11419
11420            assert!(left_dock.read(cx).is_open());
11421            assert!(right_dock.read(cx).is_open());
11422        });
11423
11424        workspace.update_in(cx, |workspace, window, cx| {
11425            // Toggle all docks - should close both
11426            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11427
11428            let left_dock = workspace.dock_at_position(DockPosition::Left);
11429            let right_dock = workspace.dock_at_position(DockPosition::Right);
11430            assert!(!left_dock.read(cx).is_open());
11431            assert!(!right_dock.read(cx).is_open());
11432        });
11433
11434        workspace.update_in(cx, |workspace, window, cx| {
11435            // Toggle again - should reopen both
11436            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11437
11438            let left_dock = workspace.dock_at_position(DockPosition::Left);
11439            let right_dock = workspace.dock_at_position(DockPosition::Right);
11440            assert!(left_dock.read(cx).is_open());
11441            assert!(right_dock.read(cx).is_open());
11442        });
11443    }
11444
11445    #[gpui::test]
11446    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11447        init_test(cx);
11448        let fs = FakeFs::new(cx.executor());
11449
11450        let project = Project::test(fs, [], cx).await;
11451        let (workspace, cx) =
11452            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11453        workspace.update_in(cx, |workspace, window, cx| {
11454            // Open two docks
11455            let left_dock = workspace.dock_at_position(DockPosition::Left);
11456            let right_dock = workspace.dock_at_position(DockPosition::Right);
11457
11458            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11459            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11460
11461            assert!(left_dock.read(cx).is_open());
11462            assert!(right_dock.read(cx).is_open());
11463        });
11464
11465        workspace.update_in(cx, |workspace, window, cx| {
11466            // Close them manually
11467            workspace.toggle_dock(DockPosition::Left, window, cx);
11468            workspace.toggle_dock(DockPosition::Right, window, cx);
11469
11470            let left_dock = workspace.dock_at_position(DockPosition::Left);
11471            let right_dock = workspace.dock_at_position(DockPosition::Right);
11472            assert!(!left_dock.read(cx).is_open());
11473            assert!(!right_dock.read(cx).is_open());
11474        });
11475
11476        workspace.update_in(cx, |workspace, window, cx| {
11477            // Toggle all docks - only last closed (right dock) should reopen
11478            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11479
11480            let left_dock = workspace.dock_at_position(DockPosition::Left);
11481            let right_dock = workspace.dock_at_position(DockPosition::Right);
11482            assert!(!left_dock.read(cx).is_open());
11483            assert!(right_dock.read(cx).is_open());
11484        });
11485    }
11486
11487    #[gpui::test]
11488    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11489        init_test(cx);
11490        let fs = FakeFs::new(cx.executor());
11491        let project = Project::test(fs, [], cx).await;
11492        let (multi_workspace, cx) =
11493            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11494        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11495
11496        // Open two docks (left and right) with one panel each
11497        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11498            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11499            workspace.add_panel(left_panel.clone(), window, cx);
11500
11501            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11502            workspace.add_panel(right_panel.clone(), window, cx);
11503
11504            workspace.toggle_dock(DockPosition::Left, window, cx);
11505            workspace.toggle_dock(DockPosition::Right, window, cx);
11506
11507            // Verify initial state
11508            assert!(
11509                workspace.left_dock().read(cx).is_open(),
11510                "Left dock should be open"
11511            );
11512            assert_eq!(
11513                workspace
11514                    .left_dock()
11515                    .read(cx)
11516                    .visible_panel()
11517                    .unwrap()
11518                    .panel_id(),
11519                left_panel.panel_id(),
11520                "Left panel should be visible in left dock"
11521            );
11522            assert!(
11523                workspace.right_dock().read(cx).is_open(),
11524                "Right dock should be open"
11525            );
11526            assert_eq!(
11527                workspace
11528                    .right_dock()
11529                    .read(cx)
11530                    .visible_panel()
11531                    .unwrap()
11532                    .panel_id(),
11533                right_panel.panel_id(),
11534                "Right panel should be visible in right dock"
11535            );
11536            assert!(
11537                !workspace.bottom_dock().read(cx).is_open(),
11538                "Bottom dock should be closed"
11539            );
11540
11541            (left_panel, right_panel)
11542        });
11543
11544        // Focus the left panel and move it to the next position (bottom dock)
11545        workspace.update_in(cx, |workspace, window, cx| {
11546            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11547            assert!(
11548                left_panel.read(cx).focus_handle(cx).is_focused(window),
11549                "Left panel should be focused"
11550            );
11551        });
11552
11553        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11554
11555        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11556        workspace.update(cx, |workspace, cx| {
11557            assert!(
11558                !workspace.left_dock().read(cx).is_open(),
11559                "Left dock should be closed"
11560            );
11561            assert!(
11562                workspace.bottom_dock().read(cx).is_open(),
11563                "Bottom dock should now be open"
11564            );
11565            assert_eq!(
11566                left_panel.read(cx).position,
11567                DockPosition::Bottom,
11568                "Left panel should now be in the bottom dock"
11569            );
11570            assert_eq!(
11571                workspace
11572                    .bottom_dock()
11573                    .read(cx)
11574                    .visible_panel()
11575                    .unwrap()
11576                    .panel_id(),
11577                left_panel.panel_id(),
11578                "Left panel should be the visible panel in the bottom dock"
11579            );
11580        });
11581
11582        // Toggle all docks off
11583        workspace.update_in(cx, |workspace, window, cx| {
11584            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11585            assert!(
11586                !workspace.left_dock().read(cx).is_open(),
11587                "Left dock should be closed"
11588            );
11589            assert!(
11590                !workspace.right_dock().read(cx).is_open(),
11591                "Right dock should be closed"
11592            );
11593            assert!(
11594                !workspace.bottom_dock().read(cx).is_open(),
11595                "Bottom dock should be closed"
11596            );
11597        });
11598
11599        // Toggle all docks back on and verify positions are restored
11600        workspace.update_in(cx, |workspace, window, cx| {
11601            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11602            assert!(
11603                !workspace.left_dock().read(cx).is_open(),
11604                "Left dock should remain closed"
11605            );
11606            assert!(
11607                workspace.right_dock().read(cx).is_open(),
11608                "Right dock should remain open"
11609            );
11610            assert!(
11611                workspace.bottom_dock().read(cx).is_open(),
11612                "Bottom dock should remain open"
11613            );
11614            assert_eq!(
11615                left_panel.read(cx).position,
11616                DockPosition::Bottom,
11617                "Left panel should remain in the bottom dock"
11618            );
11619            assert_eq!(
11620                right_panel.read(cx).position,
11621                DockPosition::Right,
11622                "Right panel should remain in the right dock"
11623            );
11624            assert_eq!(
11625                workspace
11626                    .bottom_dock()
11627                    .read(cx)
11628                    .visible_panel()
11629                    .unwrap()
11630                    .panel_id(),
11631                left_panel.panel_id(),
11632                "Left panel should be the visible panel in the right dock"
11633            );
11634        });
11635    }
11636
11637    #[gpui::test]
11638    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11639        init_test(cx);
11640
11641        let fs = FakeFs::new(cx.executor());
11642
11643        let project = Project::test(fs, None, cx).await;
11644        let (workspace, cx) =
11645            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11646
11647        // Let's arrange the panes like this:
11648        //
11649        // +-----------------------+
11650        // |         top           |
11651        // +------+--------+-------+
11652        // | left | center | right |
11653        // +------+--------+-------+
11654        // |        bottom         |
11655        // +-----------------------+
11656
11657        let top_item = cx.new(|cx| {
11658            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11659        });
11660        let bottom_item = cx.new(|cx| {
11661            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11662        });
11663        let left_item = cx.new(|cx| {
11664            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11665        });
11666        let right_item = cx.new(|cx| {
11667            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11668        });
11669        let center_item = cx.new(|cx| {
11670            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11671        });
11672
11673        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11674            let top_pane_id = workspace.active_pane().entity_id();
11675            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11676            workspace.split_pane(
11677                workspace.active_pane().clone(),
11678                SplitDirection::Down,
11679                window,
11680                cx,
11681            );
11682            top_pane_id
11683        });
11684        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11685            let bottom_pane_id = workspace.active_pane().entity_id();
11686            workspace.add_item_to_active_pane(
11687                Box::new(bottom_item.clone()),
11688                None,
11689                false,
11690                window,
11691                cx,
11692            );
11693            workspace.split_pane(
11694                workspace.active_pane().clone(),
11695                SplitDirection::Up,
11696                window,
11697                cx,
11698            );
11699            bottom_pane_id
11700        });
11701        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11702            let left_pane_id = workspace.active_pane().entity_id();
11703            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11704            workspace.split_pane(
11705                workspace.active_pane().clone(),
11706                SplitDirection::Right,
11707                window,
11708                cx,
11709            );
11710            left_pane_id
11711        });
11712        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11713            let right_pane_id = workspace.active_pane().entity_id();
11714            workspace.add_item_to_active_pane(
11715                Box::new(right_item.clone()),
11716                None,
11717                false,
11718                window,
11719                cx,
11720            );
11721            workspace.split_pane(
11722                workspace.active_pane().clone(),
11723                SplitDirection::Left,
11724                window,
11725                cx,
11726            );
11727            right_pane_id
11728        });
11729        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11730            let center_pane_id = workspace.active_pane().entity_id();
11731            workspace.add_item_to_active_pane(
11732                Box::new(center_item.clone()),
11733                None,
11734                false,
11735                window,
11736                cx,
11737            );
11738            center_pane_id
11739        });
11740        cx.executor().run_until_parked();
11741
11742        workspace.update_in(cx, |workspace, window, cx| {
11743            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11744
11745            // Join into next from center pane into right
11746            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11747        });
11748
11749        workspace.update_in(cx, |workspace, window, cx| {
11750            let active_pane = workspace.active_pane();
11751            assert_eq!(right_pane_id, active_pane.entity_id());
11752            assert_eq!(2, active_pane.read(cx).items_len());
11753            let item_ids_in_pane =
11754                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11755            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11756            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11757
11758            // Join into next from right pane into bottom
11759            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11760        });
11761
11762        workspace.update_in(cx, |workspace, window, cx| {
11763            let active_pane = workspace.active_pane();
11764            assert_eq!(bottom_pane_id, active_pane.entity_id());
11765            assert_eq!(3, active_pane.read(cx).items_len());
11766            let item_ids_in_pane =
11767                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11768            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11769            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11770            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11771
11772            // Join into next from bottom pane into left
11773            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11774        });
11775
11776        workspace.update_in(cx, |workspace, window, cx| {
11777            let active_pane = workspace.active_pane();
11778            assert_eq!(left_pane_id, active_pane.entity_id());
11779            assert_eq!(4, active_pane.read(cx).items_len());
11780            let item_ids_in_pane =
11781                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11782            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11783            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11784            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11785            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11786
11787            // Join into next from left pane into top
11788            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11789        });
11790
11791        workspace.update_in(cx, |workspace, window, cx| {
11792            let active_pane = workspace.active_pane();
11793            assert_eq!(top_pane_id, active_pane.entity_id());
11794            assert_eq!(5, active_pane.read(cx).items_len());
11795            let item_ids_in_pane =
11796                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11797            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11798            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11799            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11800            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11801            assert!(item_ids_in_pane.contains(&top_item.item_id()));
11802
11803            // Single pane left: no-op
11804            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11805        });
11806
11807        workspace.update(cx, |workspace, _cx| {
11808            let active_pane = workspace.active_pane();
11809            assert_eq!(top_pane_id, active_pane.entity_id());
11810        });
11811    }
11812
11813    fn add_an_item_to_active_pane(
11814        cx: &mut VisualTestContext,
11815        workspace: &Entity<Workspace>,
11816        item_id: u64,
11817    ) -> Entity<TestItem> {
11818        let item = cx.new(|cx| {
11819            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11820                item_id,
11821                "item{item_id}.txt",
11822                cx,
11823            )])
11824        });
11825        workspace.update_in(cx, |workspace, window, cx| {
11826            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11827        });
11828        item
11829    }
11830
11831    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11832        workspace.update_in(cx, |workspace, window, cx| {
11833            workspace.split_pane(
11834                workspace.active_pane().clone(),
11835                SplitDirection::Right,
11836                window,
11837                cx,
11838            )
11839        })
11840    }
11841
11842    #[gpui::test]
11843    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11844        init_test(cx);
11845        let fs = FakeFs::new(cx.executor());
11846        let project = Project::test(fs, None, cx).await;
11847        let (workspace, cx) =
11848            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11849
11850        add_an_item_to_active_pane(cx, &workspace, 1);
11851        split_pane(cx, &workspace);
11852        add_an_item_to_active_pane(cx, &workspace, 2);
11853        split_pane(cx, &workspace); // empty pane
11854        split_pane(cx, &workspace);
11855        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11856
11857        cx.executor().run_until_parked();
11858
11859        workspace.update(cx, |workspace, cx| {
11860            let num_panes = workspace.panes().len();
11861            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11862            let active_item = workspace
11863                .active_pane()
11864                .read(cx)
11865                .active_item()
11866                .expect("item is in focus");
11867
11868            assert_eq!(num_panes, 4);
11869            assert_eq!(num_items_in_current_pane, 1);
11870            assert_eq!(active_item.item_id(), last_item.item_id());
11871        });
11872
11873        workspace.update_in(cx, |workspace, window, cx| {
11874            workspace.join_all_panes(window, cx);
11875        });
11876
11877        workspace.update(cx, |workspace, cx| {
11878            let num_panes = workspace.panes().len();
11879            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11880            let active_item = workspace
11881                .active_pane()
11882                .read(cx)
11883                .active_item()
11884                .expect("item is in focus");
11885
11886            assert_eq!(num_panes, 1);
11887            assert_eq!(num_items_in_current_pane, 3);
11888            assert_eq!(active_item.item_id(), last_item.item_id());
11889        });
11890    }
11891    struct TestModal(FocusHandle);
11892
11893    impl TestModal {
11894        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11895            Self(cx.focus_handle())
11896        }
11897    }
11898
11899    impl EventEmitter<DismissEvent> for TestModal {}
11900
11901    impl Focusable for TestModal {
11902        fn focus_handle(&self, _cx: &App) -> FocusHandle {
11903            self.0.clone()
11904        }
11905    }
11906
11907    impl ModalView for TestModal {}
11908
11909    impl Render for TestModal {
11910        fn render(
11911            &mut self,
11912            _window: &mut Window,
11913            _cx: &mut Context<TestModal>,
11914        ) -> impl IntoElement {
11915            div().track_focus(&self.0)
11916        }
11917    }
11918
11919    #[gpui::test]
11920    async fn test_panels(cx: &mut gpui::TestAppContext) {
11921        init_test(cx);
11922        let fs = FakeFs::new(cx.executor());
11923
11924        let project = Project::test(fs, [], cx).await;
11925        let (multi_workspace, cx) =
11926            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11927        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11928
11929        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11930            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11931            workspace.add_panel(panel_1.clone(), window, cx);
11932            workspace.toggle_dock(DockPosition::Left, window, cx);
11933            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11934            workspace.add_panel(panel_2.clone(), window, cx);
11935            workspace.toggle_dock(DockPosition::Right, window, cx);
11936
11937            let left_dock = workspace.left_dock();
11938            assert_eq!(
11939                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11940                panel_1.panel_id()
11941            );
11942            assert_eq!(
11943                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11944                panel_1.size(window, cx)
11945            );
11946
11947            left_dock.update(cx, |left_dock, cx| {
11948                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11949            });
11950            assert_eq!(
11951                workspace
11952                    .right_dock()
11953                    .read(cx)
11954                    .visible_panel()
11955                    .unwrap()
11956                    .panel_id(),
11957                panel_2.panel_id(),
11958            );
11959
11960            (panel_1, panel_2)
11961        });
11962
11963        // Move panel_1 to the right
11964        panel_1.update_in(cx, |panel_1, window, cx| {
11965            panel_1.set_position(DockPosition::Right, window, cx)
11966        });
11967
11968        workspace.update_in(cx, |workspace, window, cx| {
11969            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11970            // Since it was the only panel on the left, the left dock should now be closed.
11971            assert!(!workspace.left_dock().read(cx).is_open());
11972            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11973            let right_dock = workspace.right_dock();
11974            assert_eq!(
11975                right_dock.read(cx).visible_panel().unwrap().panel_id(),
11976                panel_1.panel_id()
11977            );
11978            assert_eq!(
11979                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11980                px(1337.)
11981            );
11982
11983            // Now we move panel_2 to the left
11984            panel_2.set_position(DockPosition::Left, window, cx);
11985        });
11986
11987        workspace.update(cx, |workspace, cx| {
11988            // Since panel_2 was not visible on the right, we don't open the left dock.
11989            assert!(!workspace.left_dock().read(cx).is_open());
11990            // And the right dock is unaffected in its displaying of panel_1
11991            assert!(workspace.right_dock().read(cx).is_open());
11992            assert_eq!(
11993                workspace
11994                    .right_dock()
11995                    .read(cx)
11996                    .visible_panel()
11997                    .unwrap()
11998                    .panel_id(),
11999                panel_1.panel_id(),
12000            );
12001        });
12002
12003        // Move panel_1 back to the left
12004        panel_1.update_in(cx, |panel_1, window, cx| {
12005            panel_1.set_position(DockPosition::Left, window, cx)
12006        });
12007
12008        workspace.update_in(cx, |workspace, window, cx| {
12009            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12010            let left_dock = workspace.left_dock();
12011            assert!(left_dock.read(cx).is_open());
12012            assert_eq!(
12013                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12014                panel_1.panel_id()
12015            );
12016            assert_eq!(
12017                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
12018                px(1337.)
12019            );
12020            // And the right dock should be closed as it no longer has any panels.
12021            assert!(!workspace.right_dock().read(cx).is_open());
12022
12023            // Now we move panel_1 to the bottom
12024            panel_1.set_position(DockPosition::Bottom, window, cx);
12025        });
12026
12027        workspace.update_in(cx, |workspace, window, cx| {
12028            // Since panel_1 was visible on the left, we close the left dock.
12029            assert!(!workspace.left_dock().read(cx).is_open());
12030            // The bottom dock is sized based on the panel's default size,
12031            // since the panel orientation changed from vertical to horizontal.
12032            let bottom_dock = workspace.bottom_dock();
12033            assert_eq!(
12034                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
12035                panel_1.size(window, cx),
12036            );
12037            // Close bottom dock and move panel_1 back to the left.
12038            bottom_dock.update(cx, |bottom_dock, cx| {
12039                bottom_dock.set_open(false, window, cx)
12040            });
12041            panel_1.set_position(DockPosition::Left, window, cx);
12042        });
12043
12044        // Emit activated event on panel 1
12045        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12046
12047        // Now the left dock is open and panel_1 is active and focused.
12048        workspace.update_in(cx, |workspace, window, cx| {
12049            let left_dock = workspace.left_dock();
12050            assert!(left_dock.read(cx).is_open());
12051            assert_eq!(
12052                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12053                panel_1.panel_id(),
12054            );
12055            assert!(panel_1.focus_handle(cx).is_focused(window));
12056        });
12057
12058        // Emit closed event on panel 2, which is not active
12059        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12060
12061        // Wo don't close the left dock, because panel_2 wasn't the active panel
12062        workspace.update(cx, |workspace, cx| {
12063            let left_dock = workspace.left_dock();
12064            assert!(left_dock.read(cx).is_open());
12065            assert_eq!(
12066                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12067                panel_1.panel_id(),
12068            );
12069        });
12070
12071        // Emitting a ZoomIn event shows the panel as zoomed.
12072        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12073        workspace.read_with(cx, |workspace, _| {
12074            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12075            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12076        });
12077
12078        // Move panel to another dock while it is zoomed
12079        panel_1.update_in(cx, |panel, window, cx| {
12080            panel.set_position(DockPosition::Right, window, cx)
12081        });
12082        workspace.read_with(cx, |workspace, _| {
12083            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12084
12085            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12086        });
12087
12088        // This is a helper for getting a:
12089        // - valid focus on an element,
12090        // - that isn't a part of the panes and panels system of the Workspace,
12091        // - and doesn't trigger the 'on_focus_lost' API.
12092        let focus_other_view = {
12093            let workspace = workspace.clone();
12094            move |cx: &mut VisualTestContext| {
12095                workspace.update_in(cx, |workspace, window, cx| {
12096                    if workspace.active_modal::<TestModal>(cx).is_some() {
12097                        workspace.toggle_modal(window, cx, TestModal::new);
12098                        workspace.toggle_modal(window, cx, TestModal::new);
12099                    } else {
12100                        workspace.toggle_modal(window, cx, TestModal::new);
12101                    }
12102                })
12103            }
12104        };
12105
12106        // If focus is transferred to another view that's not a panel or another pane, we still show
12107        // the panel as zoomed.
12108        focus_other_view(cx);
12109        workspace.read_with(cx, |workspace, _| {
12110            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12111            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12112        });
12113
12114        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12115        workspace.update_in(cx, |_workspace, window, cx| {
12116            cx.focus_self(window);
12117        });
12118        workspace.read_with(cx, |workspace, _| {
12119            assert_eq!(workspace.zoomed, None);
12120            assert_eq!(workspace.zoomed_position, None);
12121        });
12122
12123        // If focus is transferred again to another view that's not a panel or a pane, we won't
12124        // show the panel as zoomed because it wasn't zoomed before.
12125        focus_other_view(cx);
12126        workspace.read_with(cx, |workspace, _| {
12127            assert_eq!(workspace.zoomed, None);
12128            assert_eq!(workspace.zoomed_position, None);
12129        });
12130
12131        // When the panel is activated, it is zoomed again.
12132        cx.dispatch_action(ToggleRightDock);
12133        workspace.read_with(cx, |workspace, _| {
12134            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12135            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12136        });
12137
12138        // Emitting a ZoomOut event unzooms the panel.
12139        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12140        workspace.read_with(cx, |workspace, _| {
12141            assert_eq!(workspace.zoomed, None);
12142            assert_eq!(workspace.zoomed_position, None);
12143        });
12144
12145        // Emit closed event on panel 1, which is active
12146        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12147
12148        // Now the left dock is closed, because panel_1 was the active panel
12149        workspace.update(cx, |workspace, cx| {
12150            let right_dock = workspace.right_dock();
12151            assert!(!right_dock.read(cx).is_open());
12152        });
12153    }
12154
12155    #[gpui::test]
12156    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12157        init_test(cx);
12158
12159        let fs = FakeFs::new(cx.background_executor.clone());
12160        let project = Project::test(fs, [], cx).await;
12161        let (workspace, cx) =
12162            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12163        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12164
12165        let dirty_regular_buffer = cx.new(|cx| {
12166            TestItem::new(cx)
12167                .with_dirty(true)
12168                .with_label("1.txt")
12169                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12170        });
12171        let dirty_regular_buffer_2 = cx.new(|cx| {
12172            TestItem::new(cx)
12173                .with_dirty(true)
12174                .with_label("2.txt")
12175                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12176        });
12177        let dirty_multi_buffer_with_both = cx.new(|cx| {
12178            TestItem::new(cx)
12179                .with_dirty(true)
12180                .with_buffer_kind(ItemBufferKind::Multibuffer)
12181                .with_label("Fake Project Search")
12182                .with_project_items(&[
12183                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12184                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12185                ])
12186        });
12187        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12188        workspace.update_in(cx, |workspace, window, cx| {
12189            workspace.add_item(
12190                pane.clone(),
12191                Box::new(dirty_regular_buffer.clone()),
12192                None,
12193                false,
12194                false,
12195                window,
12196                cx,
12197            );
12198            workspace.add_item(
12199                pane.clone(),
12200                Box::new(dirty_regular_buffer_2.clone()),
12201                None,
12202                false,
12203                false,
12204                window,
12205                cx,
12206            );
12207            workspace.add_item(
12208                pane.clone(),
12209                Box::new(dirty_multi_buffer_with_both.clone()),
12210                None,
12211                false,
12212                false,
12213                window,
12214                cx,
12215            );
12216        });
12217
12218        pane.update_in(cx, |pane, window, cx| {
12219            pane.activate_item(2, true, true, window, cx);
12220            assert_eq!(
12221                pane.active_item().unwrap().item_id(),
12222                multi_buffer_with_both_files_id,
12223                "Should select the multi buffer in the pane"
12224            );
12225        });
12226        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12227            pane.close_other_items(
12228                &CloseOtherItems {
12229                    save_intent: Some(SaveIntent::Save),
12230                    close_pinned: true,
12231                },
12232                None,
12233                window,
12234                cx,
12235            )
12236        });
12237        cx.background_executor.run_until_parked();
12238        assert!(!cx.has_pending_prompt());
12239        close_all_but_multi_buffer_task
12240            .await
12241            .expect("Closing all buffers but the multi buffer failed");
12242        pane.update(cx, |pane, cx| {
12243            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12244            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12245            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12246            assert_eq!(pane.items_len(), 1);
12247            assert_eq!(
12248                pane.active_item().unwrap().item_id(),
12249                multi_buffer_with_both_files_id,
12250                "Should have only the multi buffer left in the pane"
12251            );
12252            assert!(
12253                dirty_multi_buffer_with_both.read(cx).is_dirty,
12254                "The multi buffer containing the unsaved buffer should still be dirty"
12255            );
12256        });
12257
12258        dirty_regular_buffer.update(cx, |buffer, cx| {
12259            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12260        });
12261
12262        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12263            pane.close_active_item(
12264                &CloseActiveItem {
12265                    save_intent: Some(SaveIntent::Close),
12266                    close_pinned: false,
12267                },
12268                window,
12269                cx,
12270            )
12271        });
12272        cx.background_executor.run_until_parked();
12273        assert!(
12274            cx.has_pending_prompt(),
12275            "Dirty multi buffer should prompt a save dialog"
12276        );
12277        cx.simulate_prompt_answer("Save");
12278        cx.background_executor.run_until_parked();
12279        close_multi_buffer_task
12280            .await
12281            .expect("Closing the multi buffer failed");
12282        pane.update(cx, |pane, cx| {
12283            assert_eq!(
12284                dirty_multi_buffer_with_both.read(cx).save_count,
12285                1,
12286                "Multi buffer item should get be saved"
12287            );
12288            // Test impl does not save inner items, so we do not assert them
12289            assert_eq!(
12290                pane.items_len(),
12291                0,
12292                "No more items should be left in the pane"
12293            );
12294            assert!(pane.active_item().is_none());
12295        });
12296    }
12297
12298    #[gpui::test]
12299    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12300        cx: &mut TestAppContext,
12301    ) {
12302        init_test(cx);
12303
12304        let fs = FakeFs::new(cx.background_executor.clone());
12305        let project = Project::test(fs, [], cx).await;
12306        let (workspace, cx) =
12307            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12308        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12309
12310        let dirty_regular_buffer = cx.new(|cx| {
12311            TestItem::new(cx)
12312                .with_dirty(true)
12313                .with_label("1.txt")
12314                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12315        });
12316        let dirty_regular_buffer_2 = cx.new(|cx| {
12317            TestItem::new(cx)
12318                .with_dirty(true)
12319                .with_label("2.txt")
12320                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12321        });
12322        let clear_regular_buffer = cx.new(|cx| {
12323            TestItem::new(cx)
12324                .with_label("3.txt")
12325                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12326        });
12327
12328        let dirty_multi_buffer_with_both = cx.new(|cx| {
12329            TestItem::new(cx)
12330                .with_dirty(true)
12331                .with_buffer_kind(ItemBufferKind::Multibuffer)
12332                .with_label("Fake Project Search")
12333                .with_project_items(&[
12334                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12335                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12336                    clear_regular_buffer.read(cx).project_items[0].clone(),
12337                ])
12338        });
12339        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12340        workspace.update_in(cx, |workspace, window, cx| {
12341            workspace.add_item(
12342                pane.clone(),
12343                Box::new(dirty_regular_buffer.clone()),
12344                None,
12345                false,
12346                false,
12347                window,
12348                cx,
12349            );
12350            workspace.add_item(
12351                pane.clone(),
12352                Box::new(dirty_multi_buffer_with_both.clone()),
12353                None,
12354                false,
12355                false,
12356                window,
12357                cx,
12358            );
12359        });
12360
12361        pane.update_in(cx, |pane, window, cx| {
12362            pane.activate_item(1, true, true, window, cx);
12363            assert_eq!(
12364                pane.active_item().unwrap().item_id(),
12365                multi_buffer_with_both_files_id,
12366                "Should select the multi buffer in the pane"
12367            );
12368        });
12369        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12370            pane.close_active_item(
12371                &CloseActiveItem {
12372                    save_intent: None,
12373                    close_pinned: false,
12374                },
12375                window,
12376                cx,
12377            )
12378        });
12379        cx.background_executor.run_until_parked();
12380        assert!(
12381            cx.has_pending_prompt(),
12382            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12383        );
12384    }
12385
12386    /// Tests that when `close_on_file_delete` is enabled, files are automatically
12387    /// closed when they are deleted from disk.
12388    #[gpui::test]
12389    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12390        init_test(cx);
12391
12392        // Enable the close_on_disk_deletion setting
12393        cx.update_global(|store: &mut SettingsStore, cx| {
12394            store.update_user_settings(cx, |settings| {
12395                settings.workspace.close_on_file_delete = Some(true);
12396            });
12397        });
12398
12399        let fs = FakeFs::new(cx.background_executor.clone());
12400        let project = Project::test(fs, [], cx).await;
12401        let (workspace, cx) =
12402            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12403        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12404
12405        // Create a test item that simulates a file
12406        let item = cx.new(|cx| {
12407            TestItem::new(cx)
12408                .with_label("test.txt")
12409                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12410        });
12411
12412        // Add item to workspace
12413        workspace.update_in(cx, |workspace, window, cx| {
12414            workspace.add_item(
12415                pane.clone(),
12416                Box::new(item.clone()),
12417                None,
12418                false,
12419                false,
12420                window,
12421                cx,
12422            );
12423        });
12424
12425        // Verify the item is in the pane
12426        pane.read_with(cx, |pane, _| {
12427            assert_eq!(pane.items().count(), 1);
12428        });
12429
12430        // Simulate file deletion by setting the item's deleted state
12431        item.update(cx, |item, _| {
12432            item.set_has_deleted_file(true);
12433        });
12434
12435        // Emit UpdateTab event to trigger the close behavior
12436        cx.run_until_parked();
12437        item.update(cx, |_, cx| {
12438            cx.emit(ItemEvent::UpdateTab);
12439        });
12440
12441        // Allow the close operation to complete
12442        cx.run_until_parked();
12443
12444        // Verify the item was automatically closed
12445        pane.read_with(cx, |pane, _| {
12446            assert_eq!(
12447                pane.items().count(),
12448                0,
12449                "Item should be automatically closed when file is deleted"
12450            );
12451        });
12452    }
12453
12454    /// Tests that when `close_on_file_delete` is disabled (default), files remain
12455    /// open with a strikethrough when they are deleted from disk.
12456    #[gpui::test]
12457    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12458        init_test(cx);
12459
12460        // Ensure close_on_disk_deletion is disabled (default)
12461        cx.update_global(|store: &mut SettingsStore, cx| {
12462            store.update_user_settings(cx, |settings| {
12463                settings.workspace.close_on_file_delete = Some(false);
12464            });
12465        });
12466
12467        let fs = FakeFs::new(cx.background_executor.clone());
12468        let project = Project::test(fs, [], cx).await;
12469        let (workspace, cx) =
12470            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12471        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12472
12473        // Create a test item that simulates a file
12474        let item = cx.new(|cx| {
12475            TestItem::new(cx)
12476                .with_label("test.txt")
12477                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12478        });
12479
12480        // Add item to workspace
12481        workspace.update_in(cx, |workspace, window, cx| {
12482            workspace.add_item(
12483                pane.clone(),
12484                Box::new(item.clone()),
12485                None,
12486                false,
12487                false,
12488                window,
12489                cx,
12490            );
12491        });
12492
12493        // Verify the item is in the pane
12494        pane.read_with(cx, |pane, _| {
12495            assert_eq!(pane.items().count(), 1);
12496        });
12497
12498        // Simulate file deletion
12499        item.update(cx, |item, _| {
12500            item.set_has_deleted_file(true);
12501        });
12502
12503        // Emit UpdateTab event
12504        cx.run_until_parked();
12505        item.update(cx, |_, cx| {
12506            cx.emit(ItemEvent::UpdateTab);
12507        });
12508
12509        // Allow any potential close operation to complete
12510        cx.run_until_parked();
12511
12512        // Verify the item remains open (with strikethrough)
12513        pane.read_with(cx, |pane, _| {
12514            assert_eq!(
12515                pane.items().count(),
12516                1,
12517                "Item should remain open when close_on_disk_deletion is disabled"
12518            );
12519        });
12520
12521        // Verify the item shows as deleted
12522        item.read_with(cx, |item, _| {
12523            assert!(
12524                item.has_deleted_file,
12525                "Item should be marked as having deleted file"
12526            );
12527        });
12528    }
12529
12530    /// Tests that dirty files are not automatically closed when deleted from disk,
12531    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12532    /// unsaved changes without being prompted.
12533    #[gpui::test]
12534    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12535        init_test(cx);
12536
12537        // Enable the close_on_file_delete setting
12538        cx.update_global(|store: &mut SettingsStore, cx| {
12539            store.update_user_settings(cx, |settings| {
12540                settings.workspace.close_on_file_delete = Some(true);
12541            });
12542        });
12543
12544        let fs = FakeFs::new(cx.background_executor.clone());
12545        let project = Project::test(fs, [], cx).await;
12546        let (workspace, cx) =
12547            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12548        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12549
12550        // Create a dirty test item
12551        let item = cx.new(|cx| {
12552            TestItem::new(cx)
12553                .with_dirty(true)
12554                .with_label("test.txt")
12555                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12556        });
12557
12558        // Add item to workspace
12559        workspace.update_in(cx, |workspace, window, cx| {
12560            workspace.add_item(
12561                pane.clone(),
12562                Box::new(item.clone()),
12563                None,
12564                false,
12565                false,
12566                window,
12567                cx,
12568            );
12569        });
12570
12571        // Simulate file deletion
12572        item.update(cx, |item, _| {
12573            item.set_has_deleted_file(true);
12574        });
12575
12576        // Emit UpdateTab event to trigger the close behavior
12577        cx.run_until_parked();
12578        item.update(cx, |_, cx| {
12579            cx.emit(ItemEvent::UpdateTab);
12580        });
12581
12582        // Allow any potential close operation to complete
12583        cx.run_until_parked();
12584
12585        // Verify the item remains open (dirty files are not auto-closed)
12586        pane.read_with(cx, |pane, _| {
12587            assert_eq!(
12588                pane.items().count(),
12589                1,
12590                "Dirty items should not be automatically closed even when file is deleted"
12591            );
12592        });
12593
12594        // Verify the item is marked as deleted and still dirty
12595        item.read_with(cx, |item, _| {
12596            assert!(
12597                item.has_deleted_file,
12598                "Item should be marked as having deleted file"
12599            );
12600            assert!(item.is_dirty, "Item should still be dirty");
12601        });
12602    }
12603
12604    /// Tests that navigation history is cleaned up when files are auto-closed
12605    /// due to deletion from disk.
12606    #[gpui::test]
12607    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12608        init_test(cx);
12609
12610        // Enable the close_on_file_delete setting
12611        cx.update_global(|store: &mut SettingsStore, cx| {
12612            store.update_user_settings(cx, |settings| {
12613                settings.workspace.close_on_file_delete = Some(true);
12614            });
12615        });
12616
12617        let fs = FakeFs::new(cx.background_executor.clone());
12618        let project = Project::test(fs, [], cx).await;
12619        let (workspace, cx) =
12620            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12621        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12622
12623        // Create test items
12624        let item1 = cx.new(|cx| {
12625            TestItem::new(cx)
12626                .with_label("test1.txt")
12627                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12628        });
12629        let item1_id = item1.item_id();
12630
12631        let item2 = cx.new(|cx| {
12632            TestItem::new(cx)
12633                .with_label("test2.txt")
12634                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12635        });
12636
12637        // Add items to workspace
12638        workspace.update_in(cx, |workspace, window, cx| {
12639            workspace.add_item(
12640                pane.clone(),
12641                Box::new(item1.clone()),
12642                None,
12643                false,
12644                false,
12645                window,
12646                cx,
12647            );
12648            workspace.add_item(
12649                pane.clone(),
12650                Box::new(item2.clone()),
12651                None,
12652                false,
12653                false,
12654                window,
12655                cx,
12656            );
12657        });
12658
12659        // Activate item1 to ensure it gets navigation entries
12660        pane.update_in(cx, |pane, window, cx| {
12661            pane.activate_item(0, true, true, window, cx);
12662        });
12663
12664        // Switch to item2 and back to create navigation history
12665        pane.update_in(cx, |pane, window, cx| {
12666            pane.activate_item(1, true, true, window, cx);
12667        });
12668        cx.run_until_parked();
12669
12670        pane.update_in(cx, |pane, window, cx| {
12671            pane.activate_item(0, true, true, window, cx);
12672        });
12673        cx.run_until_parked();
12674
12675        // Simulate file deletion for item1
12676        item1.update(cx, |item, _| {
12677            item.set_has_deleted_file(true);
12678        });
12679
12680        // Emit UpdateTab event to trigger the close behavior
12681        item1.update(cx, |_, cx| {
12682            cx.emit(ItemEvent::UpdateTab);
12683        });
12684        cx.run_until_parked();
12685
12686        // Verify item1 was closed
12687        pane.read_with(cx, |pane, _| {
12688            assert_eq!(
12689                pane.items().count(),
12690                1,
12691                "Should have 1 item remaining after auto-close"
12692            );
12693        });
12694
12695        // Check navigation history after close
12696        let has_item = pane.read_with(cx, |pane, cx| {
12697            let mut has_item = false;
12698            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12699                if entry.item.id() == item1_id {
12700                    has_item = true;
12701                }
12702            });
12703            has_item
12704        });
12705
12706        assert!(
12707            !has_item,
12708            "Navigation history should not contain closed item entries"
12709        );
12710    }
12711
12712    #[gpui::test]
12713    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12714        cx: &mut TestAppContext,
12715    ) {
12716        init_test(cx);
12717
12718        let fs = FakeFs::new(cx.background_executor.clone());
12719        let project = Project::test(fs, [], cx).await;
12720        let (workspace, cx) =
12721            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12722        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12723
12724        let dirty_regular_buffer = cx.new(|cx| {
12725            TestItem::new(cx)
12726                .with_dirty(true)
12727                .with_label("1.txt")
12728                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12729        });
12730        let dirty_regular_buffer_2 = cx.new(|cx| {
12731            TestItem::new(cx)
12732                .with_dirty(true)
12733                .with_label("2.txt")
12734                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12735        });
12736        let clear_regular_buffer = cx.new(|cx| {
12737            TestItem::new(cx)
12738                .with_label("3.txt")
12739                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12740        });
12741
12742        let dirty_multi_buffer = cx.new(|cx| {
12743            TestItem::new(cx)
12744                .with_dirty(true)
12745                .with_buffer_kind(ItemBufferKind::Multibuffer)
12746                .with_label("Fake Project Search")
12747                .with_project_items(&[
12748                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12749                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12750                    clear_regular_buffer.read(cx).project_items[0].clone(),
12751                ])
12752        });
12753        workspace.update_in(cx, |workspace, window, cx| {
12754            workspace.add_item(
12755                pane.clone(),
12756                Box::new(dirty_regular_buffer.clone()),
12757                None,
12758                false,
12759                false,
12760                window,
12761                cx,
12762            );
12763            workspace.add_item(
12764                pane.clone(),
12765                Box::new(dirty_regular_buffer_2.clone()),
12766                None,
12767                false,
12768                false,
12769                window,
12770                cx,
12771            );
12772            workspace.add_item(
12773                pane.clone(),
12774                Box::new(dirty_multi_buffer.clone()),
12775                None,
12776                false,
12777                false,
12778                window,
12779                cx,
12780            );
12781        });
12782
12783        pane.update_in(cx, |pane, window, cx| {
12784            pane.activate_item(2, true, true, window, cx);
12785            assert_eq!(
12786                pane.active_item().unwrap().item_id(),
12787                dirty_multi_buffer.item_id(),
12788                "Should select the multi buffer in the pane"
12789            );
12790        });
12791        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12792            pane.close_active_item(
12793                &CloseActiveItem {
12794                    save_intent: None,
12795                    close_pinned: false,
12796                },
12797                window,
12798                cx,
12799            )
12800        });
12801        cx.background_executor.run_until_parked();
12802        assert!(
12803            !cx.has_pending_prompt(),
12804            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12805        );
12806        close_multi_buffer_task
12807            .await
12808            .expect("Closing multi buffer failed");
12809        pane.update(cx, |pane, cx| {
12810            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12811            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12812            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12813            assert_eq!(
12814                pane.items()
12815                    .map(|item| item.item_id())
12816                    .sorted()
12817                    .collect::<Vec<_>>(),
12818                vec![
12819                    dirty_regular_buffer.item_id(),
12820                    dirty_regular_buffer_2.item_id(),
12821                ],
12822                "Should have no multi buffer left in the pane"
12823            );
12824            assert!(dirty_regular_buffer.read(cx).is_dirty);
12825            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12826        });
12827    }
12828
12829    #[gpui::test]
12830    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12831        init_test(cx);
12832        let fs = FakeFs::new(cx.executor());
12833        let project = Project::test(fs, [], cx).await;
12834        let (multi_workspace, cx) =
12835            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12836        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12837
12838        // Add a new panel to the right dock, opening the dock and setting the
12839        // focus to the new panel.
12840        let panel = workspace.update_in(cx, |workspace, window, cx| {
12841            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12842            workspace.add_panel(panel.clone(), window, cx);
12843
12844            workspace
12845                .right_dock()
12846                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12847
12848            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12849
12850            panel
12851        });
12852
12853        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12854        // panel to the next valid position which, in this case, is the left
12855        // dock.
12856        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12857        workspace.update(cx, |workspace, cx| {
12858            assert!(workspace.left_dock().read(cx).is_open());
12859            assert_eq!(panel.read(cx).position, DockPosition::Left);
12860        });
12861
12862        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12863        // panel to the next valid position which, in this case, is the bottom
12864        // dock.
12865        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12866        workspace.update(cx, |workspace, cx| {
12867            assert!(workspace.bottom_dock().read(cx).is_open());
12868            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12869        });
12870
12871        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12872        // around moving the panel to its initial position, the right dock.
12873        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12874        workspace.update(cx, |workspace, cx| {
12875            assert!(workspace.right_dock().read(cx).is_open());
12876            assert_eq!(panel.read(cx).position, DockPosition::Right);
12877        });
12878
12879        // Remove focus from the panel, ensuring that, if the panel is not
12880        // focused, the `MoveFocusedPanelToNextPosition` action does not update
12881        // the panel's position, so the panel is still in the right dock.
12882        workspace.update_in(cx, |workspace, window, cx| {
12883            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12884        });
12885
12886        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12887        workspace.update(cx, |workspace, cx| {
12888            assert!(workspace.right_dock().read(cx).is_open());
12889            assert_eq!(panel.read(cx).position, DockPosition::Right);
12890        });
12891    }
12892
12893    #[gpui::test]
12894    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12895        init_test(cx);
12896
12897        let fs = FakeFs::new(cx.executor());
12898        let project = Project::test(fs, [], cx).await;
12899        let (workspace, cx) =
12900            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12901
12902        let item_1 = cx.new(|cx| {
12903            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12904        });
12905        workspace.update_in(cx, |workspace, window, cx| {
12906            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12907            workspace.move_item_to_pane_in_direction(
12908                &MoveItemToPaneInDirection {
12909                    direction: SplitDirection::Right,
12910                    focus: true,
12911                    clone: false,
12912                },
12913                window,
12914                cx,
12915            );
12916            workspace.move_item_to_pane_at_index(
12917                &MoveItemToPane {
12918                    destination: 3,
12919                    focus: true,
12920                    clone: false,
12921                },
12922                window,
12923                cx,
12924            );
12925
12926            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12927            assert_eq!(
12928                pane_items_paths(&workspace.active_pane, cx),
12929                vec!["first.txt".to_string()],
12930                "Single item was not moved anywhere"
12931            );
12932        });
12933
12934        let item_2 = cx.new(|cx| {
12935            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12936        });
12937        workspace.update_in(cx, |workspace, window, cx| {
12938            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12939            assert_eq!(
12940                pane_items_paths(&workspace.panes[0], cx),
12941                vec!["first.txt".to_string(), "second.txt".to_string()],
12942            );
12943            workspace.move_item_to_pane_in_direction(
12944                &MoveItemToPaneInDirection {
12945                    direction: SplitDirection::Right,
12946                    focus: true,
12947                    clone: false,
12948                },
12949                window,
12950                cx,
12951            );
12952
12953            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12954            assert_eq!(
12955                pane_items_paths(&workspace.panes[0], cx),
12956                vec!["first.txt".to_string()],
12957                "After moving, one item should be left in the original pane"
12958            );
12959            assert_eq!(
12960                pane_items_paths(&workspace.panes[1], cx),
12961                vec!["second.txt".to_string()],
12962                "New item should have been moved to the new pane"
12963            );
12964        });
12965
12966        let item_3 = cx.new(|cx| {
12967            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12968        });
12969        workspace.update_in(cx, |workspace, window, cx| {
12970            let original_pane = workspace.panes[0].clone();
12971            workspace.set_active_pane(&original_pane, window, cx);
12972            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12973            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12974            assert_eq!(
12975                pane_items_paths(&workspace.active_pane, cx),
12976                vec!["first.txt".to_string(), "third.txt".to_string()],
12977                "New pane should be ready to move one item out"
12978            );
12979
12980            workspace.move_item_to_pane_at_index(
12981                &MoveItemToPane {
12982                    destination: 3,
12983                    focus: true,
12984                    clone: false,
12985                },
12986                window,
12987                cx,
12988            );
12989            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12990            assert_eq!(
12991                pane_items_paths(&workspace.active_pane, cx),
12992                vec!["first.txt".to_string()],
12993                "After moving, one item should be left in the original pane"
12994            );
12995            assert_eq!(
12996                pane_items_paths(&workspace.panes[1], cx),
12997                vec!["second.txt".to_string()],
12998                "Previously created pane should be unchanged"
12999            );
13000            assert_eq!(
13001                pane_items_paths(&workspace.panes[2], cx),
13002                vec!["third.txt".to_string()],
13003                "New item should have been moved to the new pane"
13004            );
13005        });
13006    }
13007
13008    #[gpui::test]
13009    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13010        init_test(cx);
13011
13012        let fs = FakeFs::new(cx.executor());
13013        let project = Project::test(fs, [], cx).await;
13014        let (workspace, cx) =
13015            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13016
13017        let item_1 = cx.new(|cx| {
13018            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13019        });
13020        workspace.update_in(cx, |workspace, window, cx| {
13021            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13022            workspace.move_item_to_pane_in_direction(
13023                &MoveItemToPaneInDirection {
13024                    direction: SplitDirection::Right,
13025                    focus: true,
13026                    clone: true,
13027                },
13028                window,
13029                cx,
13030            );
13031        });
13032        cx.run_until_parked();
13033        workspace.update_in(cx, |workspace, window, cx| {
13034            workspace.move_item_to_pane_at_index(
13035                &MoveItemToPane {
13036                    destination: 3,
13037                    focus: true,
13038                    clone: true,
13039                },
13040                window,
13041                cx,
13042            );
13043        });
13044        cx.run_until_parked();
13045
13046        workspace.update(cx, |workspace, cx| {
13047            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13048            for pane in workspace.panes() {
13049                assert_eq!(
13050                    pane_items_paths(pane, cx),
13051                    vec!["first.txt".to_string()],
13052                    "Single item exists in all panes"
13053                );
13054            }
13055        });
13056
13057        // verify that the active pane has been updated after waiting for the
13058        // pane focus event to fire and resolve
13059        workspace.read_with(cx, |workspace, _app| {
13060            assert_eq!(
13061                workspace.active_pane(),
13062                &workspace.panes[2],
13063                "The third pane should be the active one: {:?}",
13064                workspace.panes
13065            );
13066        })
13067    }
13068
13069    #[gpui::test]
13070    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13071        init_test(cx);
13072
13073        let fs = FakeFs::new(cx.executor());
13074        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13075
13076        let project = Project::test(fs, ["root".as_ref()], cx).await;
13077        let (workspace, cx) =
13078            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13079
13080        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13081        // Add item to pane A with project path
13082        let item_a = cx.new(|cx| {
13083            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13084        });
13085        workspace.update_in(cx, |workspace, window, cx| {
13086            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13087        });
13088
13089        // Split to create pane B
13090        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13091            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13092        });
13093
13094        // Add item with SAME project path to pane B, and pin it
13095        let item_b = cx.new(|cx| {
13096            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13097        });
13098        pane_b.update_in(cx, |pane, window, cx| {
13099            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13100            pane.set_pinned_count(1);
13101        });
13102
13103        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13104        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13105
13106        // close_pinned: false should only close the unpinned copy
13107        workspace.update_in(cx, |workspace, window, cx| {
13108            workspace.close_item_in_all_panes(
13109                &CloseItemInAllPanes {
13110                    save_intent: Some(SaveIntent::Close),
13111                    close_pinned: false,
13112                },
13113                window,
13114                cx,
13115            )
13116        });
13117        cx.executor().run_until_parked();
13118
13119        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13120        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13121        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13122        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13123
13124        // Split again, seeing as closing the previous item also closed its
13125        // pane, so only pane remains, which does not allow us to properly test
13126        // that both items close when `close_pinned: true`.
13127        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13128            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13129        });
13130
13131        // Add an item with the same project path to pane C so that
13132        // close_item_in_all_panes can determine what to close across all panes
13133        // (it reads the active item from the active pane, and split_pane
13134        // creates an empty pane).
13135        let item_c = cx.new(|cx| {
13136            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13137        });
13138        pane_c.update_in(cx, |pane, window, cx| {
13139            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13140        });
13141
13142        // close_pinned: true should close the pinned copy too
13143        workspace.update_in(cx, |workspace, window, cx| {
13144            let panes_count = workspace.panes().len();
13145            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13146
13147            workspace.close_item_in_all_panes(
13148                &CloseItemInAllPanes {
13149                    save_intent: Some(SaveIntent::Close),
13150                    close_pinned: true,
13151                },
13152                window,
13153                cx,
13154            )
13155        });
13156        cx.executor().run_until_parked();
13157
13158        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13159        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13160        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13161        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13162    }
13163
13164    mod register_project_item_tests {
13165
13166        use super::*;
13167
13168        // View
13169        struct TestPngItemView {
13170            focus_handle: FocusHandle,
13171        }
13172        // Model
13173        struct TestPngItem {}
13174
13175        impl project::ProjectItem for TestPngItem {
13176            fn try_open(
13177                _project: &Entity<Project>,
13178                path: &ProjectPath,
13179                cx: &mut App,
13180            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13181                if path.path.extension().unwrap() == "png" {
13182                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13183                } else {
13184                    None
13185                }
13186            }
13187
13188            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13189                None
13190            }
13191
13192            fn project_path(&self, _: &App) -> Option<ProjectPath> {
13193                None
13194            }
13195
13196            fn is_dirty(&self) -> bool {
13197                false
13198            }
13199        }
13200
13201        impl Item for TestPngItemView {
13202            type Event = ();
13203            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13204                "".into()
13205            }
13206        }
13207        impl EventEmitter<()> for TestPngItemView {}
13208        impl Focusable for TestPngItemView {
13209            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13210                self.focus_handle.clone()
13211            }
13212        }
13213
13214        impl Render for TestPngItemView {
13215            fn render(
13216                &mut self,
13217                _window: &mut Window,
13218                _cx: &mut Context<Self>,
13219            ) -> impl IntoElement {
13220                Empty
13221            }
13222        }
13223
13224        impl ProjectItem for TestPngItemView {
13225            type Item = TestPngItem;
13226
13227            fn for_project_item(
13228                _project: Entity<Project>,
13229                _pane: Option<&Pane>,
13230                _item: Entity<Self::Item>,
13231                _: &mut Window,
13232                cx: &mut Context<Self>,
13233            ) -> Self
13234            where
13235                Self: Sized,
13236            {
13237                Self {
13238                    focus_handle: cx.focus_handle(),
13239                }
13240            }
13241        }
13242
13243        // View
13244        struct TestIpynbItemView {
13245            focus_handle: FocusHandle,
13246        }
13247        // Model
13248        struct TestIpynbItem {}
13249
13250        impl project::ProjectItem for TestIpynbItem {
13251            fn try_open(
13252                _project: &Entity<Project>,
13253                path: &ProjectPath,
13254                cx: &mut App,
13255            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13256                if path.path.extension().unwrap() == "ipynb" {
13257                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13258                } else {
13259                    None
13260                }
13261            }
13262
13263            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13264                None
13265            }
13266
13267            fn project_path(&self, _: &App) -> Option<ProjectPath> {
13268                None
13269            }
13270
13271            fn is_dirty(&self) -> bool {
13272                false
13273            }
13274        }
13275
13276        impl Item for TestIpynbItemView {
13277            type Event = ();
13278            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13279                "".into()
13280            }
13281        }
13282        impl EventEmitter<()> for TestIpynbItemView {}
13283        impl Focusable for TestIpynbItemView {
13284            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13285                self.focus_handle.clone()
13286            }
13287        }
13288
13289        impl Render for TestIpynbItemView {
13290            fn render(
13291                &mut self,
13292                _window: &mut Window,
13293                _cx: &mut Context<Self>,
13294            ) -> impl IntoElement {
13295                Empty
13296            }
13297        }
13298
13299        impl ProjectItem for TestIpynbItemView {
13300            type Item = TestIpynbItem;
13301
13302            fn for_project_item(
13303                _project: Entity<Project>,
13304                _pane: Option<&Pane>,
13305                _item: Entity<Self::Item>,
13306                _: &mut Window,
13307                cx: &mut Context<Self>,
13308            ) -> Self
13309            where
13310                Self: Sized,
13311            {
13312                Self {
13313                    focus_handle: cx.focus_handle(),
13314                }
13315            }
13316        }
13317
13318        struct TestAlternatePngItemView {
13319            focus_handle: FocusHandle,
13320        }
13321
13322        impl Item for TestAlternatePngItemView {
13323            type Event = ();
13324            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13325                "".into()
13326            }
13327        }
13328
13329        impl EventEmitter<()> for TestAlternatePngItemView {}
13330        impl Focusable for TestAlternatePngItemView {
13331            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13332                self.focus_handle.clone()
13333            }
13334        }
13335
13336        impl Render for TestAlternatePngItemView {
13337            fn render(
13338                &mut self,
13339                _window: &mut Window,
13340                _cx: &mut Context<Self>,
13341            ) -> impl IntoElement {
13342                Empty
13343            }
13344        }
13345
13346        impl ProjectItem for TestAlternatePngItemView {
13347            type Item = TestPngItem;
13348
13349            fn for_project_item(
13350                _project: Entity<Project>,
13351                _pane: Option<&Pane>,
13352                _item: Entity<Self::Item>,
13353                _: &mut Window,
13354                cx: &mut Context<Self>,
13355            ) -> Self
13356            where
13357                Self: Sized,
13358            {
13359                Self {
13360                    focus_handle: cx.focus_handle(),
13361                }
13362            }
13363        }
13364
13365        #[gpui::test]
13366        async fn test_register_project_item(cx: &mut TestAppContext) {
13367            init_test(cx);
13368
13369            cx.update(|cx| {
13370                register_project_item::<TestPngItemView>(cx);
13371                register_project_item::<TestIpynbItemView>(cx);
13372            });
13373
13374            let fs = FakeFs::new(cx.executor());
13375            fs.insert_tree(
13376                "/root1",
13377                json!({
13378                    "one.png": "BINARYDATAHERE",
13379                    "two.ipynb": "{ totally a notebook }",
13380                    "three.txt": "editing text, sure why not?"
13381                }),
13382            )
13383            .await;
13384
13385            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13386            let (workspace, cx) =
13387                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13388
13389            let worktree_id = project.update(cx, |project, cx| {
13390                project.worktrees(cx).next().unwrap().read(cx).id()
13391            });
13392
13393            let handle = workspace
13394                .update_in(cx, |workspace, window, cx| {
13395                    let project_path = (worktree_id, rel_path("one.png"));
13396                    workspace.open_path(project_path, None, true, window, cx)
13397                })
13398                .await
13399                .unwrap();
13400
13401            // Now we can check if the handle we got back errored or not
13402            assert_eq!(
13403                handle.to_any_view().entity_type(),
13404                TypeId::of::<TestPngItemView>()
13405            );
13406
13407            let handle = workspace
13408                .update_in(cx, |workspace, window, cx| {
13409                    let project_path = (worktree_id, rel_path("two.ipynb"));
13410                    workspace.open_path(project_path, None, true, window, cx)
13411                })
13412                .await
13413                .unwrap();
13414
13415            assert_eq!(
13416                handle.to_any_view().entity_type(),
13417                TypeId::of::<TestIpynbItemView>()
13418            );
13419
13420            let handle = workspace
13421                .update_in(cx, |workspace, window, cx| {
13422                    let project_path = (worktree_id, rel_path("three.txt"));
13423                    workspace.open_path(project_path, None, true, window, cx)
13424                })
13425                .await;
13426            assert!(handle.is_err());
13427        }
13428
13429        #[gpui::test]
13430        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13431            init_test(cx);
13432
13433            cx.update(|cx| {
13434                register_project_item::<TestPngItemView>(cx);
13435                register_project_item::<TestAlternatePngItemView>(cx);
13436            });
13437
13438            let fs = FakeFs::new(cx.executor());
13439            fs.insert_tree(
13440                "/root1",
13441                json!({
13442                    "one.png": "BINARYDATAHERE",
13443                    "two.ipynb": "{ totally a notebook }",
13444                    "three.txt": "editing text, sure why not?"
13445                }),
13446            )
13447            .await;
13448            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13449            let (workspace, cx) =
13450                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13451            let worktree_id = project.update(cx, |project, cx| {
13452                project.worktrees(cx).next().unwrap().read(cx).id()
13453            });
13454
13455            let handle = workspace
13456                .update_in(cx, |workspace, window, cx| {
13457                    let project_path = (worktree_id, rel_path("one.png"));
13458                    workspace.open_path(project_path, None, true, window, cx)
13459                })
13460                .await
13461                .unwrap();
13462
13463            // This _must_ be the second item registered
13464            assert_eq!(
13465                handle.to_any_view().entity_type(),
13466                TypeId::of::<TestAlternatePngItemView>()
13467            );
13468
13469            let handle = workspace
13470                .update_in(cx, |workspace, window, cx| {
13471                    let project_path = (worktree_id, rel_path("three.txt"));
13472                    workspace.open_path(project_path, None, true, window, cx)
13473                })
13474                .await;
13475            assert!(handle.is_err());
13476        }
13477    }
13478
13479    #[gpui::test]
13480    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13481        init_test(cx);
13482
13483        let fs = FakeFs::new(cx.executor());
13484        let project = Project::test(fs, [], cx).await;
13485        let (workspace, _cx) =
13486            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13487
13488        // Test with status bar shown (default)
13489        workspace.read_with(cx, |workspace, cx| {
13490            let visible = workspace.status_bar_visible(cx);
13491            assert!(visible, "Status bar should be visible by default");
13492        });
13493
13494        // Test with status bar hidden
13495        cx.update_global(|store: &mut SettingsStore, cx| {
13496            store.update_user_settings(cx, |settings| {
13497                settings.status_bar.get_or_insert_default().show = Some(false);
13498            });
13499        });
13500
13501        workspace.read_with(cx, |workspace, cx| {
13502            let visible = workspace.status_bar_visible(cx);
13503            assert!(!visible, "Status bar should be hidden when show is false");
13504        });
13505
13506        // Test with status bar shown explicitly
13507        cx.update_global(|store: &mut SettingsStore, cx| {
13508            store.update_user_settings(cx, |settings| {
13509                settings.status_bar.get_or_insert_default().show = Some(true);
13510            });
13511        });
13512
13513        workspace.read_with(cx, |workspace, cx| {
13514            let visible = workspace.status_bar_visible(cx);
13515            assert!(visible, "Status bar should be visible when show is true");
13516        });
13517    }
13518
13519    #[gpui::test]
13520    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13521        init_test(cx);
13522
13523        let fs = FakeFs::new(cx.executor());
13524        let project = Project::test(fs, [], cx).await;
13525        let (multi_workspace, cx) =
13526            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13527        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13528        let panel = workspace.update_in(cx, |workspace, window, cx| {
13529            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13530            workspace.add_panel(panel.clone(), window, cx);
13531
13532            workspace
13533                .right_dock()
13534                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13535
13536            panel
13537        });
13538
13539        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13540        let item_a = cx.new(TestItem::new);
13541        let item_b = cx.new(TestItem::new);
13542        let item_a_id = item_a.entity_id();
13543        let item_b_id = item_b.entity_id();
13544
13545        pane.update_in(cx, |pane, window, cx| {
13546            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13547            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13548        });
13549
13550        pane.read_with(cx, |pane, _| {
13551            assert_eq!(pane.items_len(), 2);
13552            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13553        });
13554
13555        workspace.update_in(cx, |workspace, window, cx| {
13556            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13557        });
13558
13559        workspace.update_in(cx, |_, window, cx| {
13560            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13561        });
13562
13563        // Assert that the `pane::CloseActiveItem` action is handled at the
13564        // workspace level when one of the dock panels is focused and, in that
13565        // case, the center pane's active item is closed but the focus is not
13566        // moved.
13567        cx.dispatch_action(pane::CloseActiveItem::default());
13568        cx.run_until_parked();
13569
13570        pane.read_with(cx, |pane, _| {
13571            assert_eq!(pane.items_len(), 1);
13572            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13573        });
13574
13575        workspace.update_in(cx, |workspace, window, cx| {
13576            assert!(workspace.right_dock().read(cx).is_open());
13577            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13578        });
13579    }
13580
13581    #[gpui::test]
13582    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13583        init_test(cx);
13584        let fs = FakeFs::new(cx.executor());
13585
13586        let project_a = Project::test(fs.clone(), [], cx).await;
13587        let project_b = Project::test(fs, [], cx).await;
13588
13589        let multi_workspace_handle =
13590            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13591        cx.run_until_parked();
13592
13593        let workspace_a = multi_workspace_handle
13594            .read_with(cx, |mw, _| mw.workspace().clone())
13595            .unwrap();
13596
13597        let _workspace_b = multi_workspace_handle
13598            .update(cx, |mw, window, cx| {
13599                mw.test_add_workspace(project_b, window, cx)
13600            })
13601            .unwrap();
13602
13603        // Switch to workspace A
13604        multi_workspace_handle
13605            .update(cx, |mw, window, cx| {
13606                mw.activate_index(0, window, cx);
13607            })
13608            .unwrap();
13609
13610        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13611
13612        // Add a panel to workspace A's right dock and open the dock
13613        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13614            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13615            workspace.add_panel(panel.clone(), window, cx);
13616            workspace
13617                .right_dock()
13618                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13619            panel
13620        });
13621
13622        // Focus the panel through the workspace (matching existing test pattern)
13623        workspace_a.update_in(cx, |workspace, window, cx| {
13624            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13625        });
13626
13627        // Zoom the panel
13628        panel.update_in(cx, |panel, window, cx| {
13629            panel.set_zoomed(true, window, cx);
13630        });
13631
13632        // Verify the panel is zoomed and the dock is open
13633        workspace_a.update_in(cx, |workspace, window, cx| {
13634            assert!(
13635                workspace.right_dock().read(cx).is_open(),
13636                "dock should be open before switch"
13637            );
13638            assert!(
13639                panel.is_zoomed(window, cx),
13640                "panel should be zoomed before switch"
13641            );
13642            assert!(
13643                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13644                "panel should be focused before switch"
13645            );
13646        });
13647
13648        // Switch to workspace B
13649        multi_workspace_handle
13650            .update(cx, |mw, window, cx| {
13651                mw.activate_index(1, window, cx);
13652            })
13653            .unwrap();
13654        cx.run_until_parked();
13655
13656        // Switch back to workspace A
13657        multi_workspace_handle
13658            .update(cx, |mw, window, cx| {
13659                mw.activate_index(0, window, cx);
13660            })
13661            .unwrap();
13662        cx.run_until_parked();
13663
13664        // Verify the panel is still zoomed and the dock is still open
13665        workspace_a.update_in(cx, |workspace, window, cx| {
13666            assert!(
13667                workspace.right_dock().read(cx).is_open(),
13668                "dock should still be open after switching back"
13669            );
13670            assert!(
13671                panel.is_zoomed(window, cx),
13672                "panel should still be zoomed after switching back"
13673            );
13674        });
13675    }
13676
13677    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13678        pane.read(cx)
13679            .items()
13680            .flat_map(|item| {
13681                item.project_paths(cx)
13682                    .into_iter()
13683                    .map(|path| path.path.display(PathStyle::local()).into_owned())
13684            })
13685            .collect()
13686    }
13687
13688    pub fn init_test(cx: &mut TestAppContext) {
13689        cx.update(|cx| {
13690            let settings_store = SettingsStore::test(cx);
13691            cx.set_global(settings_store);
13692            cx.set_global(db::AppDatabase::test_new());
13693            theme::init(theme::LoadThemes::JustBase, cx);
13694        });
13695    }
13696
13697    #[gpui::test]
13698    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
13699        use settings::{ThemeName, ThemeSelection};
13700        use theme::SystemAppearance;
13701        use zed_actions::theme::ToggleMode;
13702
13703        init_test(cx);
13704
13705        let fs = FakeFs::new(cx.executor());
13706        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
13707
13708        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
13709            .await;
13710
13711        // Build a test project and workspace view so the test can invoke
13712        // the workspace action handler the same way the UI would.
13713        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
13714        let (workspace, cx) =
13715            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13716
13717        // Seed the settings file with a plain static light theme so the
13718        // first toggle always starts from a known persisted state.
13719        workspace.update_in(cx, |_workspace, _window, cx| {
13720            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
13721            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
13722                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
13723            });
13724        });
13725        cx.executor().advance_clock(Duration::from_millis(200));
13726        cx.run_until_parked();
13727
13728        // Confirm the initial persisted settings contain the static theme
13729        // we just wrote before any toggling happens.
13730        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13731        assert!(settings_text.contains(r#""theme": "One Light""#));
13732
13733        // Toggle once. This should migrate the persisted theme settings
13734        // into light/dark slots and enable system mode.
13735        workspace.update_in(cx, |workspace, window, cx| {
13736            workspace.toggle_theme_mode(&ToggleMode, window, cx);
13737        });
13738        cx.executor().advance_clock(Duration::from_millis(200));
13739        cx.run_until_parked();
13740
13741        // 1. Static -> Dynamic
13742        // this assertion checks theme changed from static to dynamic.
13743        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13744        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
13745        assert_eq!(
13746            parsed["theme"],
13747            serde_json::json!({
13748                "mode": "system",
13749                "light": "One Light",
13750                "dark": "One Dark"
13751            })
13752        );
13753
13754        // 2. Toggle again, suppose it will change the mode to light
13755        workspace.update_in(cx, |workspace, window, cx| {
13756            workspace.toggle_theme_mode(&ToggleMode, window, cx);
13757        });
13758        cx.executor().advance_clock(Duration::from_millis(200));
13759        cx.run_until_parked();
13760
13761        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13762        assert!(settings_text.contains(r#""mode": "light""#));
13763    }
13764
13765    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13766        let item = TestProjectItem::new(id, path, cx);
13767        item.update(cx, |item, _| {
13768            item.is_dirty = true;
13769        });
13770        item
13771    }
13772
13773    #[gpui::test]
13774    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13775        cx: &mut gpui::TestAppContext,
13776    ) {
13777        init_test(cx);
13778        let fs = FakeFs::new(cx.executor());
13779
13780        let project = Project::test(fs, [], cx).await;
13781        let (workspace, cx) =
13782            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13783
13784        let panel = workspace.update_in(cx, |workspace, window, cx| {
13785            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13786            workspace.add_panel(panel.clone(), window, cx);
13787            workspace
13788                .right_dock()
13789                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13790            panel
13791        });
13792
13793        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13794        pane.update_in(cx, |pane, window, cx| {
13795            let item = cx.new(TestItem::new);
13796            pane.add_item(Box::new(item), true, true, None, window, cx);
13797        });
13798
13799        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13800        // mirrors the real-world flow and avoids side effects from directly
13801        // focusing the panel while the center pane is active.
13802        workspace.update_in(cx, |workspace, window, cx| {
13803            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13804        });
13805
13806        panel.update_in(cx, |panel, window, cx| {
13807            panel.set_zoomed(true, window, cx);
13808        });
13809
13810        workspace.update_in(cx, |workspace, window, cx| {
13811            assert!(workspace.right_dock().read(cx).is_open());
13812            assert!(panel.is_zoomed(window, cx));
13813            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13814        });
13815
13816        // Simulate a spurious pane::Event::Focus on the center pane while the
13817        // panel still has focus. This mirrors what happens during macOS window
13818        // activation: the center pane fires a focus event even though actual
13819        // focus remains on the dock panel.
13820        pane.update_in(cx, |_, _, cx| {
13821            cx.emit(pane::Event::Focus);
13822        });
13823
13824        // The dock must remain open because the panel had focus at the time the
13825        // event was processed. Before the fix, dock_to_preserve was None for
13826        // panels that don't implement pane(), causing the dock to close.
13827        workspace.update_in(cx, |workspace, window, cx| {
13828            assert!(
13829                workspace.right_dock().read(cx).is_open(),
13830                "Dock should stay open when its zoomed panel (without pane()) still has focus"
13831            );
13832            assert!(panel.is_zoomed(window, cx));
13833        });
13834    }
13835}