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    DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace, NewWorkspaceInWindow,
   31    NextWorkspaceInWindow, PreviousWorkspaceInWindow, Sidebar, SidebarEvent, 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::{DB, SerializedWindowBounds, model::SerializedWorkspace};
   80pub use persistence::{
   81    DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
   82    model::{
   83        DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
   84        SessionWorkspace,
   85    },
   86    read_serialized_multi_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};
  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
  212actions!(
  213    workspace,
  214    [
  215        /// Activates the next pane in the workspace.
  216        ActivateNextPane,
  217        /// Activates the previous pane in the workspace.
  218        ActivatePreviousPane,
  219        /// Activates the last pane in the workspace.
  220        ActivateLastPane,
  221        /// Switches to the next window.
  222        ActivateNextWindow,
  223        /// Switches to the previous window.
  224        ActivatePreviousWindow,
  225        /// Adds a folder to the current project.
  226        AddFolderToProject,
  227        /// Clears all notifications.
  228        ClearAllNotifications,
  229        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  230        ClearNavigationHistory,
  231        /// Closes the active dock.
  232        CloseActiveDock,
  233        /// Closes all docks.
  234        CloseAllDocks,
  235        /// Toggles all docks.
  236        ToggleAllDocks,
  237        /// Closes the current window.
  238        CloseWindow,
  239        /// Closes the current project.
  240        CloseProject,
  241        /// Opens the feedback dialog.
  242        Feedback,
  243        /// Follows the next collaborator in the session.
  244        FollowNextCollaborator,
  245        /// Moves the focused panel to the next position.
  246        MoveFocusedPanelToNextPosition,
  247        /// Creates a new file.
  248        NewFile,
  249        /// Creates a new file in a vertical split.
  250        NewFileSplitVertical,
  251        /// Creates a new file in a horizontal split.
  252        NewFileSplitHorizontal,
  253        /// Opens a new search.
  254        NewSearch,
  255        /// Opens a new window.
  256        NewWindow,
  257        /// Opens a file or directory.
  258        Open,
  259        /// Opens multiple files.
  260        OpenFiles,
  261        /// Opens the current location in terminal.
  262        OpenInTerminal,
  263        /// Opens the component preview.
  264        OpenComponentPreview,
  265        /// Reloads the active item.
  266        ReloadActiveItem,
  267        /// Resets the active dock to its default size.
  268        ResetActiveDockSize,
  269        /// Resets all open docks to their default sizes.
  270        ResetOpenDocksSize,
  271        /// Reloads the application
  272        Reload,
  273        /// Saves the current file with a new name.
  274        SaveAs,
  275        /// Saves without formatting.
  276        SaveWithoutFormat,
  277        /// Shuts down all debug adapters.
  278        ShutdownDebugAdapters,
  279        /// Suppresses the current notification.
  280        SuppressNotification,
  281        /// Toggles the bottom dock.
  282        ToggleBottomDock,
  283        /// Toggles centered layout mode.
  284        ToggleCenteredLayout,
  285        /// Toggles edit prediction feature globally for all files.
  286        ToggleEditPrediction,
  287        /// Toggles the left dock.
  288        ToggleLeftDock,
  289        /// Toggles the right dock.
  290        ToggleRightDock,
  291        /// Toggles zoom on the active pane.
  292        ToggleZoom,
  293        /// Toggles read-only mode for the active item (if supported by that item).
  294        ToggleReadOnlyFile,
  295        /// Zooms in on the active pane.
  296        ZoomIn,
  297        /// Zooms out of the active pane.
  298        ZoomOut,
  299        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  300        /// If the modal is shown already, closes it without trusting any worktree.
  301        ToggleWorktreeSecurity,
  302        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  303        /// Requires restart to take effect on already opened projects.
  304        ClearTrustedWorktrees,
  305        /// Stops following a collaborator.
  306        Unfollow,
  307        /// Restores the banner.
  308        RestoreBanner,
  309        /// Toggles expansion of the selected item.
  310        ToggleExpandItem,
  311    ]
  312);
  313
  314/// Activates a specific pane by its index.
  315#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  316#[action(namespace = workspace)]
  317pub struct ActivatePane(pub usize);
  318
  319/// Moves an item to a specific pane by index.
  320#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  321#[action(namespace = workspace)]
  322#[serde(deny_unknown_fields)]
  323pub struct MoveItemToPane {
  324    #[serde(default = "default_1")]
  325    pub destination: usize,
  326    #[serde(default = "default_true")]
  327    pub focus: bool,
  328    #[serde(default)]
  329    pub clone: bool,
  330}
  331
  332fn default_1() -> usize {
  333    1
  334}
  335
  336/// Moves an item to a pane in the specified direction.
  337#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  338#[action(namespace = workspace)]
  339#[serde(deny_unknown_fields)]
  340pub struct MoveItemToPaneInDirection {
  341    #[serde(default = "default_right")]
  342    pub direction: SplitDirection,
  343    #[serde(default = "default_true")]
  344    pub focus: bool,
  345    #[serde(default)]
  346    pub clone: bool,
  347}
  348
  349/// Creates a new file in a split of the desired direction.
  350#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  351#[action(namespace = workspace)]
  352#[serde(deny_unknown_fields)]
  353pub struct NewFileSplit(pub SplitDirection);
  354
  355fn default_right() -> SplitDirection {
  356    SplitDirection::Right
  357}
  358
  359/// Saves all open files in the workspace.
  360#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  361#[action(namespace = workspace)]
  362#[serde(deny_unknown_fields)]
  363pub struct SaveAll {
  364    #[serde(default)]
  365    pub save_intent: Option<SaveIntent>,
  366}
  367
  368/// Saves the current file with the specified options.
  369#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  370#[action(namespace = workspace)]
  371#[serde(deny_unknown_fields)]
  372pub struct Save {
  373    #[serde(default)]
  374    pub save_intent: Option<SaveIntent>,
  375}
  376
  377/// Closes all items and panes in the workspace.
  378#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  379#[action(namespace = workspace)]
  380#[serde(deny_unknown_fields)]
  381pub struct CloseAllItemsAndPanes {
  382    #[serde(default)]
  383    pub save_intent: Option<SaveIntent>,
  384}
  385
  386/// Closes all inactive tabs and panes in the workspace.
  387#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  388#[action(namespace = workspace)]
  389#[serde(deny_unknown_fields)]
  390pub struct CloseInactiveTabsAndPanes {
  391    #[serde(default)]
  392    pub save_intent: Option<SaveIntent>,
  393}
  394
  395/// Closes the active item across all panes.
  396#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  397#[action(namespace = workspace)]
  398#[serde(deny_unknown_fields)]
  399pub struct CloseItemInAllPanes {
  400    #[serde(default)]
  401    pub save_intent: Option<SaveIntent>,
  402    #[serde(default)]
  403    pub close_pinned: bool,
  404}
  405
  406/// Sends a sequence of keystrokes to the active element.
  407#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  408#[action(namespace = workspace)]
  409pub struct SendKeystrokes(pub String);
  410
  411actions!(
  412    project_symbols,
  413    [
  414        /// Toggles the project symbols search.
  415        #[action(name = "Toggle")]
  416        ToggleProjectSymbols
  417    ]
  418);
  419
  420/// Toggles the file finder interface.
  421#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  422#[action(namespace = file_finder, name = "Toggle")]
  423#[serde(deny_unknown_fields)]
  424pub struct ToggleFileFinder {
  425    #[serde(default)]
  426    pub separate_history: bool,
  427}
  428
  429/// Opens a new terminal in the center.
  430#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  431#[action(namespace = workspace)]
  432#[serde(deny_unknown_fields)]
  433pub struct NewCenterTerminal {
  434    /// If true, creates a local terminal even in remote projects.
  435    #[serde(default)]
  436    pub local: bool,
  437}
  438
  439/// Opens a new terminal.
  440#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  441#[action(namespace = workspace)]
  442#[serde(deny_unknown_fields)]
  443pub struct NewTerminal {
  444    /// If true, creates a local terminal even in remote projects.
  445    #[serde(default)]
  446    pub local: bool,
  447}
  448
  449/// Increases size of a currently focused dock by a given amount of pixels.
  450#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  451#[action(namespace = workspace)]
  452#[serde(deny_unknown_fields)]
  453pub struct IncreaseActiveDockSize {
  454    /// For 0px parameter, uses UI font size value.
  455    #[serde(default)]
  456    pub px: u32,
  457}
  458
  459/// Decreases size of a currently focused dock by a given amount of pixels.
  460#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  461#[action(namespace = workspace)]
  462#[serde(deny_unknown_fields)]
  463pub struct DecreaseActiveDockSize {
  464    /// For 0px parameter, uses UI font size value.
  465    #[serde(default)]
  466    pub px: u32,
  467}
  468
  469/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  470#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  471#[action(namespace = workspace)]
  472#[serde(deny_unknown_fields)]
  473pub struct IncreaseOpenDocksSize {
  474    /// For 0px parameter, uses UI font size value.
  475    #[serde(default)]
  476    pub px: u32,
  477}
  478
  479/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  480#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  481#[action(namespace = workspace)]
  482#[serde(deny_unknown_fields)]
  483pub struct DecreaseOpenDocksSize {
  484    /// For 0px parameter, uses UI font size value.
  485    #[serde(default)]
  486    pub px: u32,
  487}
  488
  489actions!(
  490    workspace,
  491    [
  492        /// Activates the pane to the left.
  493        ActivatePaneLeft,
  494        /// Activates the pane to the right.
  495        ActivatePaneRight,
  496        /// Activates the pane above.
  497        ActivatePaneUp,
  498        /// Activates the pane below.
  499        ActivatePaneDown,
  500        /// Swaps the current pane with the one to the left.
  501        SwapPaneLeft,
  502        /// Swaps the current pane with the one to the right.
  503        SwapPaneRight,
  504        /// Swaps the current pane with the one above.
  505        SwapPaneUp,
  506        /// Swaps the current pane with the one below.
  507        SwapPaneDown,
  508        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  509        SwapPaneAdjacent,
  510        /// Move the current pane to be at the far left.
  511        MovePaneLeft,
  512        /// Move the current pane to be at the far right.
  513        MovePaneRight,
  514        /// Move the current pane to be at the very top.
  515        MovePaneUp,
  516        /// Move the current pane to be at the very bottom.
  517        MovePaneDown,
  518    ]
  519);
  520
  521#[derive(PartialEq, Eq, Debug)]
  522pub enum CloseIntent {
  523    /// Quit the program entirely.
  524    Quit,
  525    /// Close a window.
  526    CloseWindow,
  527    /// Replace the workspace in an existing window.
  528    ReplaceWindow,
  529}
  530
  531#[derive(Clone)]
  532pub struct Toast {
  533    id: NotificationId,
  534    msg: Cow<'static, str>,
  535    autohide: bool,
  536    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  537}
  538
  539impl Toast {
  540    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  541        Toast {
  542            id,
  543            msg: msg.into(),
  544            on_click: None,
  545            autohide: false,
  546        }
  547    }
  548
  549    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  550    where
  551        M: Into<Cow<'static, str>>,
  552        F: Fn(&mut Window, &mut App) + 'static,
  553    {
  554        self.on_click = Some((message.into(), Arc::new(on_click)));
  555        self
  556    }
  557
  558    pub fn autohide(mut self) -> Self {
  559        self.autohide = true;
  560        self
  561    }
  562}
  563
  564impl PartialEq for Toast {
  565    fn eq(&self, other: &Self) -> bool {
  566        self.id == other.id
  567            && self.msg == other.msg
  568            && self.on_click.is_some() == other.on_click.is_some()
  569    }
  570}
  571
  572/// Opens a new terminal with the specified working directory.
  573#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  574#[action(namespace = workspace)]
  575#[serde(deny_unknown_fields)]
  576pub struct OpenTerminal {
  577    pub working_directory: PathBuf,
  578    /// If true, creates a local terminal even in remote projects.
  579    #[serde(default)]
  580    pub local: bool,
  581}
  582
  583#[derive(
  584    Clone,
  585    Copy,
  586    Debug,
  587    Default,
  588    Hash,
  589    PartialEq,
  590    Eq,
  591    PartialOrd,
  592    Ord,
  593    serde::Serialize,
  594    serde::Deserialize,
  595)]
  596pub struct WorkspaceId(i64);
  597
  598impl WorkspaceId {
  599    pub fn from_i64(value: i64) -> Self {
  600        Self(value)
  601    }
  602}
  603
  604impl StaticColumnCount for WorkspaceId {}
  605impl Bind for WorkspaceId {
  606    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  607        self.0.bind(statement, start_index)
  608    }
  609}
  610impl Column for WorkspaceId {
  611    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  612        i64::column(statement, start_index)
  613            .map(|(i, next_index)| (Self(i), next_index))
  614            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  615    }
  616}
  617impl From<WorkspaceId> for i64 {
  618    fn from(val: WorkspaceId) -> Self {
  619        val.0
  620    }
  621}
  622
  623fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
  624    if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
  625        workspace_window
  626            .update(cx, |multi_workspace, window, cx| {
  627                let workspace = multi_workspace.workspace().clone();
  628                workspace.update(cx, |workspace, cx| {
  629                    prompt_for_open_path_and_open(workspace, app_state, options, window, cx);
  630                });
  631            })
  632            .ok();
  633    } else {
  634        let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, true, cx);
  635        cx.spawn(async move |cx| {
  636            let (window, _) = task.await?;
  637            window.update(cx, |multi_workspace, window, cx| {
  638                window.activate_window();
  639                let workspace = multi_workspace.workspace().clone();
  640                workspace.update(cx, |workspace, cx| {
  641                    prompt_for_open_path_and_open(workspace, app_state, options, window, cx);
  642                });
  643            })?;
  644            anyhow::Ok(())
  645        })
  646        .detach_and_log_err(cx);
  647    }
  648}
  649
  650pub fn prompt_for_open_path_and_open(
  651    workspace: &mut Workspace,
  652    app_state: Arc<AppState>,
  653    options: PathPromptOptions,
  654    window: &mut Window,
  655    cx: &mut Context<Workspace>,
  656) {
  657    let paths = workspace.prompt_for_open_path(
  658        options,
  659        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  660        window,
  661        cx,
  662    );
  663    cx.spawn_in(window, async move |this, cx| {
  664        let Some(paths) = paths.await.log_err().flatten() else {
  665            return;
  666        };
  667        if let Some(task) = this
  668            .update_in(cx, |this, window, cx| {
  669                this.open_workspace_for_paths(false, paths, window, cx)
  670            })
  671            .log_err()
  672        {
  673            task.await.log_err();
  674        }
  675    })
  676    .detach();
  677}
  678
  679pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  680    component::init();
  681    theme_preview::init(cx);
  682    toast_layer::init(cx);
  683    history_manager::init(app_state.fs.clone(), cx);
  684
  685    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  686        .on_action(|_: &Reload, cx| reload(cx))
  687        .on_action({
  688            let app_state = Arc::downgrade(&app_state);
  689            move |_: &Open, cx: &mut App| {
  690                if let Some(app_state) = app_state.upgrade() {
  691                    prompt_and_open_paths(
  692                        app_state,
  693                        PathPromptOptions {
  694                            files: true,
  695                            directories: true,
  696                            multiple: true,
  697                            prompt: None,
  698                        },
  699                        cx,
  700                    );
  701                }
  702            }
  703        })
  704        .on_action({
  705            let app_state = Arc::downgrade(&app_state);
  706            move |_: &OpenFiles, cx: &mut App| {
  707                let directories = cx.can_select_mixed_files_and_dirs();
  708                if let Some(app_state) = app_state.upgrade() {
  709                    prompt_and_open_paths(
  710                        app_state,
  711                        PathPromptOptions {
  712                            files: true,
  713                            directories,
  714                            multiple: true,
  715                            prompt: None,
  716                        },
  717                        cx,
  718                    );
  719                }
  720            }
  721        });
  722}
  723
  724type BuildProjectItemFn =
  725    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  726
  727type BuildProjectItemForPathFn =
  728    fn(
  729        &Entity<Project>,
  730        &ProjectPath,
  731        &mut Window,
  732        &mut App,
  733    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  734
  735#[derive(Clone, Default)]
  736struct ProjectItemRegistry {
  737    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  738    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  739}
  740
  741impl ProjectItemRegistry {
  742    fn register<T: ProjectItem>(&mut self) {
  743        self.build_project_item_fns_by_type.insert(
  744            TypeId::of::<T::Item>(),
  745            |item, project, pane, window, cx| {
  746                let item = item.downcast().unwrap();
  747                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  748                    as Box<dyn ItemHandle>
  749            },
  750        );
  751        self.build_project_item_for_path_fns
  752            .push(|project, project_path, window, cx| {
  753                let project_path = project_path.clone();
  754                let is_file = project
  755                    .read(cx)
  756                    .entry_for_path(&project_path, cx)
  757                    .is_some_and(|entry| entry.is_file());
  758                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  759                let is_local = project.read(cx).is_local();
  760                let project_item =
  761                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  762                let project = project.clone();
  763                Some(window.spawn(cx, async move |cx| {
  764                    match project_item.await.with_context(|| {
  765                        format!(
  766                            "opening project path {:?}",
  767                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  768                        )
  769                    }) {
  770                        Ok(project_item) => {
  771                            let project_item = project_item;
  772                            let project_entry_id: Option<ProjectEntryId> =
  773                                project_item.read_with(cx, project::ProjectItem::entry_id);
  774                            let build_workspace_item = Box::new(
  775                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  776                                    Box::new(cx.new(|cx| {
  777                                        T::for_project_item(
  778                                            project,
  779                                            Some(pane),
  780                                            project_item,
  781                                            window,
  782                                            cx,
  783                                        )
  784                                    })) as Box<dyn ItemHandle>
  785                                },
  786                            ) as Box<_>;
  787                            Ok((project_entry_id, build_workspace_item))
  788                        }
  789                        Err(e) => {
  790                            log::warn!("Failed to open a project item: {e:#}");
  791                            if e.error_code() == ErrorCode::Internal {
  792                                if let Some(abs_path) =
  793                                    entry_abs_path.as_deref().filter(|_| is_file)
  794                                {
  795                                    if let Some(broken_project_item_view) =
  796                                        cx.update(|window, cx| {
  797                                            T::for_broken_project_item(
  798                                                abs_path, is_local, &e, window, cx,
  799                                            )
  800                                        })?
  801                                    {
  802                                        let build_workspace_item = Box::new(
  803                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  804                                                cx.new(|_| broken_project_item_view).boxed_clone()
  805                                            },
  806                                        )
  807                                        as Box<_>;
  808                                        return Ok((None, build_workspace_item));
  809                                    }
  810                                }
  811                            }
  812                            Err(e)
  813                        }
  814                    }
  815                }))
  816            });
  817    }
  818
  819    fn open_path(
  820        &self,
  821        project: &Entity<Project>,
  822        path: &ProjectPath,
  823        window: &mut Window,
  824        cx: &mut App,
  825    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  826        let Some(open_project_item) = self
  827            .build_project_item_for_path_fns
  828            .iter()
  829            .rev()
  830            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  831        else {
  832            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  833        };
  834        open_project_item
  835    }
  836
  837    fn build_item<T: project::ProjectItem>(
  838        &self,
  839        item: Entity<T>,
  840        project: Entity<Project>,
  841        pane: Option<&Pane>,
  842        window: &mut Window,
  843        cx: &mut App,
  844    ) -> Option<Box<dyn ItemHandle>> {
  845        let build = self
  846            .build_project_item_fns_by_type
  847            .get(&TypeId::of::<T>())?;
  848        Some(build(item.into_any(), project, pane, window, cx))
  849    }
  850}
  851
  852type WorkspaceItemBuilder =
  853    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  854
  855impl Global for ProjectItemRegistry {}
  856
  857/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  858/// items will get a chance to open the file, starting from the project item that
  859/// was added last.
  860pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  861    cx.default_global::<ProjectItemRegistry>().register::<I>();
  862}
  863
  864#[derive(Default)]
  865pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  866
  867struct FollowableViewDescriptor {
  868    from_state_proto: fn(
  869        Entity<Workspace>,
  870        ViewId,
  871        &mut Option<proto::view::Variant>,
  872        &mut Window,
  873        &mut App,
  874    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  875    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  876}
  877
  878impl Global for FollowableViewRegistry {}
  879
  880impl FollowableViewRegistry {
  881    pub fn register<I: FollowableItem>(cx: &mut App) {
  882        cx.default_global::<Self>().0.insert(
  883            TypeId::of::<I>(),
  884            FollowableViewDescriptor {
  885                from_state_proto: |workspace, id, state, window, cx| {
  886                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  887                        cx.foreground_executor()
  888                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  889                    })
  890                },
  891                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  892            },
  893        );
  894    }
  895
  896    pub fn from_state_proto(
  897        workspace: Entity<Workspace>,
  898        view_id: ViewId,
  899        mut state: Option<proto::view::Variant>,
  900        window: &mut Window,
  901        cx: &mut App,
  902    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  903        cx.update_default_global(|this: &mut Self, cx| {
  904            this.0.values().find_map(|descriptor| {
  905                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  906            })
  907        })
  908    }
  909
  910    pub fn to_followable_view(
  911        view: impl Into<AnyView>,
  912        cx: &App,
  913    ) -> Option<Box<dyn FollowableItemHandle>> {
  914        let this = cx.try_global::<Self>()?;
  915        let view = view.into();
  916        let descriptor = this.0.get(&view.entity_type())?;
  917        Some((descriptor.to_followable_view)(&view))
  918    }
  919}
  920
  921#[derive(Copy, Clone)]
  922struct SerializableItemDescriptor {
  923    deserialize: fn(
  924        Entity<Project>,
  925        WeakEntity<Workspace>,
  926        WorkspaceId,
  927        ItemId,
  928        &mut Window,
  929        &mut Context<Pane>,
  930    ) -> Task<Result<Box<dyn ItemHandle>>>,
  931    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  932    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  933}
  934
  935#[derive(Default)]
  936struct SerializableItemRegistry {
  937    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  938    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  939}
  940
  941impl Global for SerializableItemRegistry {}
  942
  943impl SerializableItemRegistry {
  944    fn deserialize(
  945        item_kind: &str,
  946        project: Entity<Project>,
  947        workspace: WeakEntity<Workspace>,
  948        workspace_id: WorkspaceId,
  949        item_item: ItemId,
  950        window: &mut Window,
  951        cx: &mut Context<Pane>,
  952    ) -> Task<Result<Box<dyn ItemHandle>>> {
  953        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  954            return Task::ready(Err(anyhow!(
  955                "cannot deserialize {}, descriptor not found",
  956                item_kind
  957            )));
  958        };
  959
  960        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
  961    }
  962
  963    fn cleanup(
  964        item_kind: &str,
  965        workspace_id: WorkspaceId,
  966        loaded_items: Vec<ItemId>,
  967        window: &mut Window,
  968        cx: &mut App,
  969    ) -> Task<Result<()>> {
  970        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  971            return Task::ready(Err(anyhow!(
  972                "cannot cleanup {}, descriptor not found",
  973                item_kind
  974            )));
  975        };
  976
  977        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
  978    }
  979
  980    fn view_to_serializable_item_handle(
  981        view: AnyView,
  982        cx: &App,
  983    ) -> Option<Box<dyn SerializableItemHandle>> {
  984        let this = cx.try_global::<Self>()?;
  985        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
  986        Some((descriptor.view_to_serializable_item)(view))
  987    }
  988
  989    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
  990        let this = cx.try_global::<Self>()?;
  991        this.descriptors_by_kind.get(item_kind).copied()
  992    }
  993}
  994
  995pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
  996    let serialized_item_kind = I::serialized_item_kind();
  997
  998    let registry = cx.default_global::<SerializableItemRegistry>();
  999    let descriptor = SerializableItemDescriptor {
 1000        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
 1001            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
 1002            cx.foreground_executor()
 1003                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 1004        },
 1005        cleanup: |workspace_id, loaded_items, window, cx| {
 1006            I::cleanup(workspace_id, loaded_items, window, cx)
 1007        },
 1008        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1009    };
 1010    registry
 1011        .descriptors_by_kind
 1012        .insert(Arc::from(serialized_item_kind), descriptor);
 1013    registry
 1014        .descriptors_by_type
 1015        .insert(TypeId::of::<I>(), descriptor);
 1016}
 1017
 1018pub struct AppState {
 1019    pub languages: Arc<LanguageRegistry>,
 1020    pub client: Arc<Client>,
 1021    pub user_store: Entity<UserStore>,
 1022    pub workspace_store: Entity<WorkspaceStore>,
 1023    pub fs: Arc<dyn fs::Fs>,
 1024    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1025    pub node_runtime: NodeRuntime,
 1026    pub session: Entity<AppSession>,
 1027}
 1028
 1029struct GlobalAppState(Weak<AppState>);
 1030
 1031impl Global for GlobalAppState {}
 1032
 1033pub struct WorkspaceStore {
 1034    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1035    client: Arc<Client>,
 1036    _subscriptions: Vec<client::Subscription>,
 1037}
 1038
 1039#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1040pub enum CollaboratorId {
 1041    PeerId(PeerId),
 1042    Agent,
 1043}
 1044
 1045impl From<PeerId> for CollaboratorId {
 1046    fn from(peer_id: PeerId) -> Self {
 1047        CollaboratorId::PeerId(peer_id)
 1048    }
 1049}
 1050
 1051impl From<&PeerId> for CollaboratorId {
 1052    fn from(peer_id: &PeerId) -> Self {
 1053        CollaboratorId::PeerId(*peer_id)
 1054    }
 1055}
 1056
 1057#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1058struct Follower {
 1059    project_id: Option<u64>,
 1060    peer_id: PeerId,
 1061}
 1062
 1063impl AppState {
 1064    #[track_caller]
 1065    pub fn global(cx: &App) -> Weak<Self> {
 1066        cx.global::<GlobalAppState>().0.clone()
 1067    }
 1068    pub fn try_global(cx: &App) -> Option<Weak<Self>> {
 1069        cx.try_global::<GlobalAppState>()
 1070            .map(|state| state.0.clone())
 1071    }
 1072    pub fn set_global(state: Weak<AppState>, cx: &mut App) {
 1073        cx.set_global(GlobalAppState(state));
 1074    }
 1075
 1076    #[cfg(any(test, feature = "test-support"))]
 1077    pub fn test(cx: &mut App) -> Arc<Self> {
 1078        use fs::Fs;
 1079        use node_runtime::NodeRuntime;
 1080        use session::Session;
 1081        use settings::SettingsStore;
 1082
 1083        if !cx.has_global::<SettingsStore>() {
 1084            let settings_store = SettingsStore::test(cx);
 1085            cx.set_global(settings_store);
 1086        }
 1087
 1088        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1089        <dyn Fs>::set_global(fs.clone(), cx);
 1090        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1091        let clock = Arc::new(clock::FakeSystemClock::new());
 1092        let http_client = http_client::FakeHttpClient::with_404_response();
 1093        let client = Client::new(clock, http_client, cx);
 1094        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1095        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1096        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1097
 1098        theme::init(theme::LoadThemes::JustBase, cx);
 1099        client::init(&client, cx);
 1100
 1101        Arc::new(Self {
 1102            client,
 1103            fs,
 1104            languages,
 1105            user_store,
 1106            workspace_store,
 1107            node_runtime: NodeRuntime::unavailable(),
 1108            build_window_options: |_, _| Default::default(),
 1109            session,
 1110        })
 1111    }
 1112}
 1113
 1114struct DelayedDebouncedEditAction {
 1115    task: Option<Task<()>>,
 1116    cancel_channel: Option<oneshot::Sender<()>>,
 1117}
 1118
 1119impl DelayedDebouncedEditAction {
 1120    fn new() -> DelayedDebouncedEditAction {
 1121        DelayedDebouncedEditAction {
 1122            task: None,
 1123            cancel_channel: None,
 1124        }
 1125    }
 1126
 1127    fn fire_new<F>(
 1128        &mut self,
 1129        delay: Duration,
 1130        window: &mut Window,
 1131        cx: &mut Context<Workspace>,
 1132        func: F,
 1133    ) where
 1134        F: 'static
 1135            + Send
 1136            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1137    {
 1138        if let Some(channel) = self.cancel_channel.take() {
 1139            _ = channel.send(());
 1140        }
 1141
 1142        let (sender, mut receiver) = oneshot::channel::<()>();
 1143        self.cancel_channel = Some(sender);
 1144
 1145        let previous_task = self.task.take();
 1146        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1147            let mut timer = cx.background_executor().timer(delay).fuse();
 1148            if let Some(previous_task) = previous_task {
 1149                previous_task.await;
 1150            }
 1151
 1152            futures::select_biased! {
 1153                _ = receiver => return,
 1154                    _ = timer => {}
 1155            }
 1156
 1157            if let Some(result) = workspace
 1158                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1159                .log_err()
 1160            {
 1161                result.await.log_err();
 1162            }
 1163        }));
 1164    }
 1165}
 1166
 1167pub enum Event {
 1168    PaneAdded(Entity<Pane>),
 1169    PaneRemoved,
 1170    ItemAdded {
 1171        item: Box<dyn ItemHandle>,
 1172    },
 1173    ActiveItemChanged,
 1174    ItemRemoved {
 1175        item_id: EntityId,
 1176    },
 1177    UserSavedItem {
 1178        pane: WeakEntity<Pane>,
 1179        item: Box<dyn WeakItemHandle>,
 1180        save_intent: SaveIntent,
 1181    },
 1182    ContactRequestedJoin(u64),
 1183    WorkspaceCreated(WeakEntity<Workspace>),
 1184    OpenBundledFile {
 1185        text: Cow<'static, str>,
 1186        title: &'static str,
 1187        language: &'static str,
 1188    },
 1189    ZoomChanged,
 1190    ModalOpened,
 1191    Activate,
 1192}
 1193
 1194#[derive(Debug, Clone)]
 1195pub enum OpenVisible {
 1196    All,
 1197    None,
 1198    OnlyFiles,
 1199    OnlyDirectories,
 1200}
 1201
 1202enum WorkspaceLocation {
 1203    // Valid local paths or SSH project to serialize
 1204    Location(SerializedWorkspaceLocation, PathList),
 1205    // No valid location found hence clear session id
 1206    DetachFromSession,
 1207    // No valid location found to serialize
 1208    None,
 1209}
 1210
 1211type PromptForNewPath = Box<
 1212    dyn Fn(
 1213        &mut Workspace,
 1214        DirectoryLister,
 1215        Option<String>,
 1216        &mut Window,
 1217        &mut Context<Workspace>,
 1218    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1219>;
 1220
 1221type PromptForOpenPath = Box<
 1222    dyn Fn(
 1223        &mut Workspace,
 1224        DirectoryLister,
 1225        &mut Window,
 1226        &mut Context<Workspace>,
 1227    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1228>;
 1229
 1230#[derive(Default)]
 1231struct DispatchingKeystrokes {
 1232    dispatched: HashSet<Vec<Keystroke>>,
 1233    queue: VecDeque<Keystroke>,
 1234    task: Option<Shared<Task<()>>>,
 1235}
 1236
 1237/// Collects everything project-related for a certain window opened.
 1238/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1239///
 1240/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1241/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1242/// that can be used to register a global action to be triggered from any place in the window.
 1243pub struct Workspace {
 1244    weak_self: WeakEntity<Self>,
 1245    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1246    zoomed: Option<AnyWeakView>,
 1247    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1248    zoomed_position: Option<DockPosition>,
 1249    center: PaneGroup,
 1250    left_dock: Entity<Dock>,
 1251    bottom_dock: Entity<Dock>,
 1252    right_dock: Entity<Dock>,
 1253    panes: Vec<Entity<Pane>>,
 1254    active_worktree_override: Option<WorktreeId>,
 1255    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1256    active_pane: Entity<Pane>,
 1257    last_active_center_pane: Option<WeakEntity<Pane>>,
 1258    last_active_view_id: Option<proto::ViewId>,
 1259    status_bar: Entity<StatusBar>,
 1260    pub(crate) modal_layer: Entity<ModalLayer>,
 1261    toast_layer: Entity<ToastLayer>,
 1262    titlebar_item: Option<AnyView>,
 1263    notifications: Notifications,
 1264    suppressed_notifications: HashSet<NotificationId>,
 1265    project: Entity<Project>,
 1266    follower_states: HashMap<CollaboratorId, FollowerState>,
 1267    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1268    window_edited: bool,
 1269    last_window_title: Option<String>,
 1270    dirty_items: HashMap<EntityId, Subscription>,
 1271    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1272    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1273    database_id: Option<WorkspaceId>,
 1274    app_state: Arc<AppState>,
 1275    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1276    _subscriptions: Vec<Subscription>,
 1277    _apply_leader_updates: Task<Result<()>>,
 1278    _observe_current_user: Task<Result<()>>,
 1279    _schedule_serialize_workspace: Option<Task<()>>,
 1280    _serialize_workspace_task: Option<Task<()>>,
 1281    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1282    pane_history_timestamp: Arc<AtomicUsize>,
 1283    bounds: Bounds<Pixels>,
 1284    pub centered_layout: bool,
 1285    bounds_save_task_queued: Option<Task<()>>,
 1286    on_prompt_for_new_path: Option<PromptForNewPath>,
 1287    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1288    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1289    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1290    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1291    _items_serializer: Task<Result<()>>,
 1292    session_id: Option<String>,
 1293    scheduled_tasks: Vec<Task<()>>,
 1294    last_open_dock_positions: Vec<DockPosition>,
 1295    removing: bool,
 1296    _panels_task: Option<Task<Result<()>>>,
 1297}
 1298
 1299impl EventEmitter<Event> for Workspace {}
 1300
 1301#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1302pub struct ViewId {
 1303    pub creator: CollaboratorId,
 1304    pub id: u64,
 1305}
 1306
 1307pub struct FollowerState {
 1308    center_pane: Entity<Pane>,
 1309    dock_pane: Option<Entity<Pane>>,
 1310    active_view_id: Option<ViewId>,
 1311    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1312}
 1313
 1314struct FollowerView {
 1315    view: Box<dyn FollowableItemHandle>,
 1316    location: Option<proto::PanelId>,
 1317}
 1318
 1319impl Workspace {
 1320    pub fn new(
 1321        workspace_id: Option<WorkspaceId>,
 1322        project: Entity<Project>,
 1323        app_state: Arc<AppState>,
 1324        window: &mut Window,
 1325        cx: &mut Context<Self>,
 1326    ) -> Self {
 1327        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1328            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1329                if let TrustedWorktreesEvent::Trusted(..) = e {
 1330                    // Do not persist auto trusted worktrees
 1331                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1332                        worktrees_store.update(cx, |worktrees_store, cx| {
 1333                            worktrees_store.schedule_serialization(
 1334                                cx,
 1335                                |new_trusted_worktrees, cx| {
 1336                                    let timeout =
 1337                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1338                                    cx.background_spawn(async move {
 1339                                        timeout.await;
 1340                                        persistence::DB
 1341                                            .save_trusted_worktrees(new_trusted_worktrees)
 1342                                            .await
 1343                                            .log_err();
 1344                                    })
 1345                                },
 1346                            )
 1347                        });
 1348                    }
 1349                }
 1350            })
 1351            .detach();
 1352
 1353            cx.observe_global::<SettingsStore>(|_, cx| {
 1354                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1355                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1356                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1357                            trusted_worktrees.auto_trust_all(cx);
 1358                        })
 1359                    }
 1360                }
 1361            })
 1362            .detach();
 1363        }
 1364
 1365        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1366            match event {
 1367                project::Event::RemoteIdChanged(_) => {
 1368                    this.update_window_title(window, cx);
 1369                }
 1370
 1371                project::Event::CollaboratorLeft(peer_id) => {
 1372                    this.collaborator_left(*peer_id, window, cx);
 1373                }
 1374
 1375                &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
 1376                    this.update_window_title(window, cx);
 1377                    if this
 1378                        .project()
 1379                        .read(cx)
 1380                        .worktree_for_id(id, cx)
 1381                        .is_some_and(|wt| wt.read(cx).is_visible())
 1382                    {
 1383                        this.serialize_workspace(window, cx);
 1384                        this.update_history(cx);
 1385                    }
 1386                }
 1387                project::Event::WorktreeUpdatedEntries(..) => {
 1388                    this.update_window_title(window, cx);
 1389                    this.serialize_workspace(window, cx);
 1390                }
 1391
 1392                project::Event::DisconnectedFromHost => {
 1393                    this.update_window_edited(window, cx);
 1394                    let leaders_to_unfollow =
 1395                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1396                    for leader_id in leaders_to_unfollow {
 1397                        this.unfollow(leader_id, window, cx);
 1398                    }
 1399                }
 1400
 1401                project::Event::DisconnectedFromRemote {
 1402                    server_not_running: _,
 1403                } => {
 1404                    this.update_window_edited(window, cx);
 1405                }
 1406
 1407                project::Event::Closed => {
 1408                    window.remove_window();
 1409                }
 1410
 1411                project::Event::DeletedEntry(_, entry_id) => {
 1412                    for pane in this.panes.iter() {
 1413                        pane.update(cx, |pane, cx| {
 1414                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1415                        });
 1416                    }
 1417                }
 1418
 1419                project::Event::Toast {
 1420                    notification_id,
 1421                    message,
 1422                    link,
 1423                } => this.show_notification(
 1424                    NotificationId::named(notification_id.clone()),
 1425                    cx,
 1426                    |cx| {
 1427                        let mut notification = MessageNotification::new(message.clone(), cx);
 1428                        if let Some(link) = link {
 1429                            notification = notification
 1430                                .more_info_message(link.label)
 1431                                .more_info_url(link.url);
 1432                        }
 1433
 1434                        cx.new(|_| notification)
 1435                    },
 1436                ),
 1437
 1438                project::Event::HideToast { notification_id } => {
 1439                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1440                }
 1441
 1442                project::Event::LanguageServerPrompt(request) => {
 1443                    struct LanguageServerPrompt;
 1444
 1445                    this.show_notification(
 1446                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1447                        cx,
 1448                        |cx| {
 1449                            cx.new(|cx| {
 1450                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1451                            })
 1452                        },
 1453                    );
 1454                }
 1455
 1456                project::Event::AgentLocationChanged => {
 1457                    this.handle_agent_location_changed(window, cx)
 1458                }
 1459
 1460                _ => {}
 1461            }
 1462            cx.notify()
 1463        })
 1464        .detach();
 1465
 1466        cx.subscribe_in(
 1467            &project.read(cx).breakpoint_store(),
 1468            window,
 1469            |workspace, _, event, window, cx| match event {
 1470                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1471                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1472                    workspace.serialize_workspace(window, cx);
 1473                }
 1474                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1475            },
 1476        )
 1477        .detach();
 1478        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1479            cx.subscribe_in(
 1480                &toolchain_store,
 1481                window,
 1482                |workspace, _, event, window, cx| match event {
 1483                    ToolchainStoreEvent::CustomToolchainsModified => {
 1484                        workspace.serialize_workspace(window, cx);
 1485                    }
 1486                    _ => {}
 1487                },
 1488            )
 1489            .detach();
 1490        }
 1491
 1492        cx.on_focus_lost(window, |this, window, cx| {
 1493            let focus_handle = this.focus_handle(cx);
 1494            window.focus(&focus_handle, cx);
 1495        })
 1496        .detach();
 1497
 1498        let weak_handle = cx.entity().downgrade();
 1499        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1500
 1501        let center_pane = cx.new(|cx| {
 1502            let mut center_pane = Pane::new(
 1503                weak_handle.clone(),
 1504                project.clone(),
 1505                pane_history_timestamp.clone(),
 1506                None,
 1507                NewFile.boxed_clone(),
 1508                true,
 1509                window,
 1510                cx,
 1511            );
 1512            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1513            center_pane.set_should_display_welcome_page(true);
 1514            center_pane
 1515        });
 1516        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1517            .detach();
 1518
 1519        window.focus(&center_pane.focus_handle(cx), cx);
 1520
 1521        cx.emit(Event::PaneAdded(center_pane.clone()));
 1522
 1523        let any_window_handle = window.window_handle();
 1524        app_state.workspace_store.update(cx, |store, _| {
 1525            store
 1526                .workspaces
 1527                .insert((any_window_handle, weak_handle.clone()));
 1528        });
 1529
 1530        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1531        let mut connection_status = app_state.client.status();
 1532        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1533            current_user.next().await;
 1534            connection_status.next().await;
 1535            let mut stream =
 1536                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1537
 1538            while stream.recv().await.is_some() {
 1539                this.update(cx, |_, cx| cx.notify())?;
 1540            }
 1541            anyhow::Ok(())
 1542        });
 1543
 1544        // All leader updates are enqueued and then processed in a single task, so
 1545        // that each asynchronous operation can be run in order.
 1546        let (leader_updates_tx, mut leader_updates_rx) =
 1547            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1548        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1549            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1550                Self::process_leader_update(&this, leader_id, update, cx)
 1551                    .await
 1552                    .log_err();
 1553            }
 1554
 1555            Ok(())
 1556        });
 1557
 1558        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1559        let modal_layer = cx.new(|_| ModalLayer::new());
 1560        let toast_layer = cx.new(|_| ToastLayer::new());
 1561        cx.subscribe(
 1562            &modal_layer,
 1563            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1564                cx.emit(Event::ModalOpened);
 1565            },
 1566        )
 1567        .detach();
 1568
 1569        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1570        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1571        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1572        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1573        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1574        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1575        let status_bar = cx.new(|cx| {
 1576            let mut status_bar = StatusBar::new(&center_pane.clone(), window, cx);
 1577            status_bar.add_left_item(left_dock_buttons, window, cx);
 1578            status_bar.add_right_item(right_dock_buttons, window, cx);
 1579            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1580            status_bar
 1581        });
 1582
 1583        let session_id = app_state.session.read(cx).id().to_owned();
 1584
 1585        let mut active_call = None;
 1586        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1587            let subscriptions =
 1588                vec![
 1589                    call.0
 1590                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1591                ];
 1592            active_call = Some((call, subscriptions));
 1593        }
 1594
 1595        let (serializable_items_tx, serializable_items_rx) =
 1596            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1597        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1598            Self::serialize_items(&this, serializable_items_rx, cx).await
 1599        });
 1600
 1601        let subscriptions = vec![
 1602            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1603            cx.observe_window_bounds(window, move |this, window, cx| {
 1604                if this.bounds_save_task_queued.is_some() {
 1605                    return;
 1606                }
 1607                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1608                    cx.background_executor()
 1609                        .timer(Duration::from_millis(100))
 1610                        .await;
 1611                    this.update_in(cx, |this, window, cx| {
 1612                        this.save_window_bounds(window, cx).detach();
 1613                        this.bounds_save_task_queued.take();
 1614                    })
 1615                    .ok();
 1616                }));
 1617                cx.notify();
 1618            }),
 1619            cx.observe_window_appearance(window, |_, window, cx| {
 1620                let window_appearance = window.appearance();
 1621
 1622                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1623
 1624                GlobalTheme::reload_theme(cx);
 1625                GlobalTheme::reload_icon_theme(cx);
 1626            }),
 1627            cx.on_release({
 1628                let weak_handle = weak_handle.clone();
 1629                move |this, cx| {
 1630                    this.app_state.workspace_store.update(cx, move |store, _| {
 1631                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1632                    })
 1633                }
 1634            }),
 1635        ];
 1636
 1637        cx.defer_in(window, move |this, window, cx| {
 1638            this.update_window_title(window, cx);
 1639            this.show_initial_notifications(cx);
 1640        });
 1641
 1642        let mut center = PaneGroup::new(center_pane.clone());
 1643        center.set_is_center(true);
 1644        center.mark_positions(cx);
 1645
 1646        Workspace {
 1647            weak_self: weak_handle.clone(),
 1648            zoomed: None,
 1649            zoomed_position: None,
 1650            previous_dock_drag_coordinates: None,
 1651            center,
 1652            panes: vec![center_pane.clone()],
 1653            panes_by_item: Default::default(),
 1654            active_pane: center_pane.clone(),
 1655            last_active_center_pane: Some(center_pane.downgrade()),
 1656            last_active_view_id: None,
 1657            status_bar,
 1658            modal_layer,
 1659            toast_layer,
 1660            titlebar_item: None,
 1661            active_worktree_override: None,
 1662            notifications: Notifications::default(),
 1663            suppressed_notifications: HashSet::default(),
 1664            left_dock,
 1665            bottom_dock,
 1666            right_dock,
 1667            _panels_task: None,
 1668            project: project.clone(),
 1669            follower_states: Default::default(),
 1670            last_leaders_by_pane: Default::default(),
 1671            dispatching_keystrokes: Default::default(),
 1672            window_edited: false,
 1673            last_window_title: None,
 1674            dirty_items: Default::default(),
 1675            active_call,
 1676            database_id: workspace_id,
 1677            app_state,
 1678            _observe_current_user,
 1679            _apply_leader_updates,
 1680            _schedule_serialize_workspace: None,
 1681            _serialize_workspace_task: None,
 1682            _schedule_serialize_ssh_paths: None,
 1683            leader_updates_tx,
 1684            _subscriptions: subscriptions,
 1685            pane_history_timestamp,
 1686            workspace_actions: Default::default(),
 1687            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1688            bounds: Default::default(),
 1689            centered_layout: false,
 1690            bounds_save_task_queued: None,
 1691            on_prompt_for_new_path: None,
 1692            on_prompt_for_open_path: None,
 1693            terminal_provider: None,
 1694            debugger_provider: None,
 1695            serializable_items_tx,
 1696            _items_serializer,
 1697            session_id: Some(session_id),
 1698
 1699            scheduled_tasks: Vec::new(),
 1700            last_open_dock_positions: Vec::new(),
 1701            removing: false,
 1702        }
 1703    }
 1704
 1705    pub fn new_local(
 1706        abs_paths: Vec<PathBuf>,
 1707        app_state: Arc<AppState>,
 1708        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1709        env: Option<HashMap<String, String>>,
 1710        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1711        activate: bool,
 1712        cx: &mut App,
 1713    ) -> Task<
 1714        anyhow::Result<(
 1715            WindowHandle<MultiWorkspace>,
 1716            Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 1717        )>,
 1718    > {
 1719        let project_handle = Project::local(
 1720            app_state.client.clone(),
 1721            app_state.node_runtime.clone(),
 1722            app_state.user_store.clone(),
 1723            app_state.languages.clone(),
 1724            app_state.fs.clone(),
 1725            env,
 1726            Default::default(),
 1727            cx,
 1728        );
 1729
 1730        cx.spawn(async move |cx| {
 1731            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1732            for path in abs_paths.into_iter() {
 1733                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1734                    paths_to_open.push(canonical)
 1735                } else {
 1736                    paths_to_open.push(path)
 1737                }
 1738            }
 1739
 1740            let serialized_workspace =
 1741                persistence::DB.workspace_for_roots(paths_to_open.as_slice());
 1742
 1743            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1744                paths_to_open = paths.ordered_paths().cloned().collect();
 1745                if !paths.is_lexicographically_ordered() {
 1746                    project_handle.update(cx, |project, cx| {
 1747                        project.set_worktrees_reordered(true, cx);
 1748                    });
 1749                }
 1750            }
 1751
 1752            // Get project paths for all of the abs_paths
 1753            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1754                Vec::with_capacity(paths_to_open.len());
 1755
 1756            for path in paths_to_open.into_iter() {
 1757                if let Some((_, project_entry)) = cx
 1758                    .update(|cx| {
 1759                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1760                    })
 1761                    .await
 1762                    .log_err()
 1763                {
 1764                    project_paths.push((path, Some(project_entry)));
 1765                } else {
 1766                    project_paths.push((path, None));
 1767                }
 1768            }
 1769
 1770            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1771                serialized_workspace.id
 1772            } else {
 1773                DB.next_id().await.unwrap_or_else(|_| Default::default())
 1774            };
 1775
 1776            let toolchains = DB.toolchains(workspace_id).await?;
 1777
 1778            for (toolchain, worktree_path, path) in toolchains {
 1779                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1780                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1781                    this.find_worktree(&worktree_path, cx)
 1782                        .and_then(|(worktree, rel_path)| {
 1783                            if rel_path.is_empty() {
 1784                                Some(worktree.read(cx).id())
 1785                            } else {
 1786                                None
 1787                            }
 1788                        })
 1789                }) else {
 1790                    // We did not find a worktree with a given path, but that's whatever.
 1791                    continue;
 1792                };
 1793                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1794                    continue;
 1795                }
 1796
 1797                project_handle
 1798                    .update(cx, |this, cx| {
 1799                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1800                    })
 1801                    .await;
 1802            }
 1803            if let Some(workspace) = serialized_workspace.as_ref() {
 1804                project_handle.update(cx, |this, cx| {
 1805                    for (scope, toolchains) in &workspace.user_toolchains {
 1806                        for toolchain in toolchains {
 1807                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1808                        }
 1809                    }
 1810                });
 1811            }
 1812
 1813            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1814                if let Some(window) = requesting_window {
 1815                    let centered_layout = serialized_workspace
 1816                        .as_ref()
 1817                        .map(|w| w.centered_layout)
 1818                        .unwrap_or(false);
 1819
 1820                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1821                        let workspace = cx.new(|cx| {
 1822                            let mut workspace = Workspace::new(
 1823                                Some(workspace_id),
 1824                                project_handle.clone(),
 1825                                app_state.clone(),
 1826                                window,
 1827                                cx,
 1828                            );
 1829
 1830                            workspace.centered_layout = centered_layout;
 1831
 1832                            // Call init callback to add items before window renders
 1833                            if let Some(init) = init {
 1834                                init(&mut workspace, window, cx);
 1835                            }
 1836
 1837                            workspace
 1838                        });
 1839                        if activate {
 1840                            multi_workspace.activate(workspace.clone(), cx);
 1841                        } else {
 1842                            multi_workspace.add_workspace(workspace.clone(), cx);
 1843                        }
 1844                        workspace
 1845                    })?;
 1846                    (window, workspace)
 1847                } else {
 1848                    let window_bounds_override = window_bounds_env_override();
 1849
 1850                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1851                        (Some(WindowBounds::Windowed(bounds)), None)
 1852                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1853                        && let Some(display) = workspace.display
 1854                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1855                    {
 1856                        // Reopening an existing workspace - restore its saved bounds
 1857                        (Some(bounds.0), Some(display))
 1858                    } else if let Some((display, bounds)) =
 1859                        persistence::read_default_window_bounds()
 1860                    {
 1861                        // New or empty workspace - use the last known window bounds
 1862                        (Some(bounds), Some(display))
 1863                    } else {
 1864                        // New window - let GPUI's default_bounds() handle cascading
 1865                        (None, None)
 1866                    };
 1867
 1868                    // Use the serialized workspace to construct the new window
 1869                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1870                    options.window_bounds = window_bounds;
 1871                    let centered_layout = serialized_workspace
 1872                        .as_ref()
 1873                        .map(|w| w.centered_layout)
 1874                        .unwrap_or(false);
 1875                    let window = cx.open_window(options, {
 1876                        let app_state = app_state.clone();
 1877                        let project_handle = project_handle.clone();
 1878                        move |window, cx| {
 1879                            let workspace = cx.new(|cx| {
 1880                                let mut workspace = Workspace::new(
 1881                                    Some(workspace_id),
 1882                                    project_handle,
 1883                                    app_state,
 1884                                    window,
 1885                                    cx,
 1886                                );
 1887                                workspace.centered_layout = centered_layout;
 1888
 1889                                // Call init callback to add items before window renders
 1890                                if let Some(init) = init {
 1891                                    init(&mut workspace, window, cx);
 1892                                }
 1893
 1894                                workspace
 1895                            });
 1896                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 1897                        }
 1898                    })?;
 1899                    let workspace =
 1900                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 1901                            multi_workspace.workspace().clone()
 1902                        })?;
 1903                    (window, workspace)
 1904                };
 1905
 1906            notify_if_database_failed(window, cx);
 1907            // Check if this is an empty workspace (no paths to open)
 1908            // An empty workspace is one where project_paths is empty
 1909            let is_empty_workspace = project_paths.is_empty();
 1910            // Check if serialized workspace has paths before it's moved
 1911            let serialized_workspace_has_paths = serialized_workspace
 1912                .as_ref()
 1913                .map(|ws| !ws.paths.is_empty())
 1914                .unwrap_or(false);
 1915
 1916            let opened_items = window
 1917                .update(cx, |_, window, cx| {
 1918                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 1919                        open_items(serialized_workspace, project_paths, window, cx)
 1920                    })
 1921                })?
 1922                .await
 1923                .unwrap_or_default();
 1924
 1925            // Restore default dock state for empty workspaces
 1926            // Only restore if:
 1927            // 1. This is an empty workspace (no paths), AND
 1928            // 2. The serialized workspace either doesn't exist or has no paths
 1929            if is_empty_workspace && !serialized_workspace_has_paths {
 1930                if let Some(default_docks) = persistence::read_default_dock_state() {
 1931                    window
 1932                        .update(cx, |_, window, cx| {
 1933                            workspace.update(cx, |workspace, cx| {
 1934                                for (dock, serialized_dock) in [
 1935                                    (&workspace.right_dock, &default_docks.right),
 1936                                    (&workspace.left_dock, &default_docks.left),
 1937                                    (&workspace.bottom_dock, &default_docks.bottom),
 1938                                ] {
 1939                                    dock.update(cx, |dock, cx| {
 1940                                        dock.serialized_dock = Some(serialized_dock.clone());
 1941                                        dock.restore_state(window, cx);
 1942                                    });
 1943                                }
 1944                                cx.notify();
 1945                            });
 1946                        })
 1947                        .log_err();
 1948                }
 1949            }
 1950
 1951            window
 1952                .update(cx, |_, _window, cx| {
 1953                    workspace.update(cx, |this: &mut Workspace, cx| {
 1954                        this.update_history(cx);
 1955                    });
 1956                })
 1957                .log_err();
 1958            Ok((window, opened_items))
 1959        })
 1960    }
 1961
 1962    pub fn weak_handle(&self) -> WeakEntity<Self> {
 1963        self.weak_self.clone()
 1964    }
 1965
 1966    pub fn left_dock(&self) -> &Entity<Dock> {
 1967        &self.left_dock
 1968    }
 1969
 1970    pub fn bottom_dock(&self) -> &Entity<Dock> {
 1971        &self.bottom_dock
 1972    }
 1973
 1974    pub fn set_bottom_dock_layout(
 1975        &mut self,
 1976        layout: BottomDockLayout,
 1977        window: &mut Window,
 1978        cx: &mut Context<Self>,
 1979    ) {
 1980        let fs = self.project().read(cx).fs();
 1981        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 1982            content.workspace.bottom_dock_layout = Some(layout);
 1983        });
 1984
 1985        cx.notify();
 1986        self.serialize_workspace(window, cx);
 1987    }
 1988
 1989    pub fn right_dock(&self) -> &Entity<Dock> {
 1990        &self.right_dock
 1991    }
 1992
 1993    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 1994        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 1995    }
 1996
 1997    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 1998        let left_dock = self.left_dock.read(cx);
 1999        let left_visible = left_dock.is_open();
 2000        let left_active_panel = left_dock
 2001            .active_panel()
 2002            .map(|panel| panel.persistent_name().to_string());
 2003        // `zoomed_position` is kept in sync with individual panel zoom state
 2004        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2005        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2006
 2007        let right_dock = self.right_dock.read(cx);
 2008        let right_visible = right_dock.is_open();
 2009        let right_active_panel = right_dock
 2010            .active_panel()
 2011            .map(|panel| panel.persistent_name().to_string());
 2012        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2013
 2014        let bottom_dock = self.bottom_dock.read(cx);
 2015        let bottom_visible = bottom_dock.is_open();
 2016        let bottom_active_panel = bottom_dock
 2017            .active_panel()
 2018            .map(|panel| panel.persistent_name().to_string());
 2019        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2020
 2021        DockStructure {
 2022            left: DockData {
 2023                visible: left_visible,
 2024                active_panel: left_active_panel,
 2025                zoom: left_dock_zoom,
 2026            },
 2027            right: DockData {
 2028                visible: right_visible,
 2029                active_panel: right_active_panel,
 2030                zoom: right_dock_zoom,
 2031            },
 2032            bottom: DockData {
 2033                visible: bottom_visible,
 2034                active_panel: bottom_active_panel,
 2035                zoom: bottom_dock_zoom,
 2036            },
 2037        }
 2038    }
 2039
 2040    pub fn set_dock_structure(
 2041        &self,
 2042        docks: DockStructure,
 2043        window: &mut Window,
 2044        cx: &mut Context<Self>,
 2045    ) {
 2046        for (dock, data) in [
 2047            (&self.left_dock, docks.left),
 2048            (&self.bottom_dock, docks.bottom),
 2049            (&self.right_dock, docks.right),
 2050        ] {
 2051            dock.update(cx, |dock, cx| {
 2052                dock.serialized_dock = Some(data);
 2053                dock.restore_state(window, cx);
 2054            });
 2055        }
 2056    }
 2057
 2058    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2059        self.items(cx)
 2060            .filter_map(|item| {
 2061                let project_path = item.project_path(cx)?;
 2062                self.project.read(cx).absolute_path(&project_path, cx)
 2063            })
 2064            .collect()
 2065    }
 2066
 2067    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2068        match position {
 2069            DockPosition::Left => &self.left_dock,
 2070            DockPosition::Bottom => &self.bottom_dock,
 2071            DockPosition::Right => &self.right_dock,
 2072        }
 2073    }
 2074
 2075    pub fn is_edited(&self) -> bool {
 2076        self.window_edited
 2077    }
 2078
 2079    pub fn add_panel<T: Panel>(
 2080        &mut self,
 2081        panel: Entity<T>,
 2082        window: &mut Window,
 2083        cx: &mut Context<Self>,
 2084    ) {
 2085        let focus_handle = panel.panel_focus_handle(cx);
 2086        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2087            .detach();
 2088
 2089        let dock_position = panel.position(window, cx);
 2090        let dock = self.dock_at_position(dock_position);
 2091
 2092        dock.update(cx, |dock, cx| {
 2093            dock.add_panel(panel, self.weak_self.clone(), window, cx)
 2094        });
 2095    }
 2096
 2097    pub fn remove_panel<T: Panel>(
 2098        &mut self,
 2099        panel: &Entity<T>,
 2100        window: &mut Window,
 2101        cx: &mut Context<Self>,
 2102    ) {
 2103        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2104            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2105        }
 2106    }
 2107
 2108    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2109        &self.status_bar
 2110    }
 2111
 2112    pub fn set_workspace_sidebar_open(&self, open: bool, cx: &mut App) {
 2113        self.status_bar.update(cx, |status_bar, cx| {
 2114            status_bar.set_workspace_sidebar_open(open, cx);
 2115        });
 2116    }
 2117
 2118    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2119        StatusBarSettings::get_global(cx).show
 2120    }
 2121
 2122    pub fn app_state(&self) -> &Arc<AppState> {
 2123        &self.app_state
 2124    }
 2125
 2126    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2127        self._panels_task = Some(task);
 2128    }
 2129
 2130    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2131        self._panels_task.take()
 2132    }
 2133
 2134    pub fn user_store(&self) -> &Entity<UserStore> {
 2135        &self.app_state.user_store
 2136    }
 2137
 2138    pub fn project(&self) -> &Entity<Project> {
 2139        &self.project
 2140    }
 2141
 2142    pub fn path_style(&self, cx: &App) -> PathStyle {
 2143        self.project.read(cx).path_style(cx)
 2144    }
 2145
 2146    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2147        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2148
 2149        for pane_handle in &self.panes {
 2150            let pane = pane_handle.read(cx);
 2151
 2152            for entry in pane.activation_history() {
 2153                history.insert(
 2154                    entry.entity_id,
 2155                    history
 2156                        .get(&entry.entity_id)
 2157                        .cloned()
 2158                        .unwrap_or(0)
 2159                        .max(entry.timestamp),
 2160                );
 2161            }
 2162        }
 2163
 2164        history
 2165    }
 2166
 2167    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2168        let mut recent_item: Option<Entity<T>> = None;
 2169        let mut recent_timestamp = 0;
 2170        for pane_handle in &self.panes {
 2171            let pane = pane_handle.read(cx);
 2172            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2173                pane.items().map(|item| (item.item_id(), item)).collect();
 2174            for entry in pane.activation_history() {
 2175                if entry.timestamp > recent_timestamp
 2176                    && let Some(&item) = item_map.get(&entry.entity_id)
 2177                    && let Some(typed_item) = item.act_as::<T>(cx)
 2178                {
 2179                    recent_timestamp = entry.timestamp;
 2180                    recent_item = Some(typed_item);
 2181                }
 2182            }
 2183        }
 2184        recent_item
 2185    }
 2186
 2187    pub fn recent_navigation_history_iter(
 2188        &self,
 2189        cx: &App,
 2190    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2191        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2192        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2193
 2194        for pane in &self.panes {
 2195            let pane = pane.read(cx);
 2196
 2197            pane.nav_history()
 2198                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2199                    if let Some(fs_path) = &fs_path {
 2200                        abs_paths_opened
 2201                            .entry(fs_path.clone())
 2202                            .or_default()
 2203                            .insert(project_path.clone());
 2204                    }
 2205                    let timestamp = entry.timestamp;
 2206                    match history.entry(project_path) {
 2207                        hash_map::Entry::Occupied(mut entry) => {
 2208                            let (_, old_timestamp) = entry.get();
 2209                            if &timestamp > old_timestamp {
 2210                                entry.insert((fs_path, timestamp));
 2211                            }
 2212                        }
 2213                        hash_map::Entry::Vacant(entry) => {
 2214                            entry.insert((fs_path, timestamp));
 2215                        }
 2216                    }
 2217                });
 2218
 2219            if let Some(item) = pane.active_item()
 2220                && let Some(project_path) = item.project_path(cx)
 2221            {
 2222                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2223
 2224                if let Some(fs_path) = &fs_path {
 2225                    abs_paths_opened
 2226                        .entry(fs_path.clone())
 2227                        .or_default()
 2228                        .insert(project_path.clone());
 2229                }
 2230
 2231                history.insert(project_path, (fs_path, std::usize::MAX));
 2232            }
 2233        }
 2234
 2235        history
 2236            .into_iter()
 2237            .sorted_by_key(|(_, (_, order))| *order)
 2238            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2239            .rev()
 2240            .filter(move |(history_path, abs_path)| {
 2241                let latest_project_path_opened = abs_path
 2242                    .as_ref()
 2243                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2244                    .and_then(|project_paths| {
 2245                        project_paths
 2246                            .iter()
 2247                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2248                    });
 2249
 2250                latest_project_path_opened.is_none_or(|path| path == history_path)
 2251            })
 2252    }
 2253
 2254    pub fn recent_navigation_history(
 2255        &self,
 2256        limit: Option<usize>,
 2257        cx: &App,
 2258    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2259        self.recent_navigation_history_iter(cx)
 2260            .take(limit.unwrap_or(usize::MAX))
 2261            .collect()
 2262    }
 2263
 2264    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2265        for pane in &self.panes {
 2266            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2267        }
 2268    }
 2269
 2270    fn navigate_history(
 2271        &mut self,
 2272        pane: WeakEntity<Pane>,
 2273        mode: NavigationMode,
 2274        window: &mut Window,
 2275        cx: &mut Context<Workspace>,
 2276    ) -> Task<Result<()>> {
 2277        self.navigate_history_impl(
 2278            pane,
 2279            mode,
 2280            window,
 2281            &mut |history, cx| history.pop(mode, cx),
 2282            cx,
 2283        )
 2284    }
 2285
 2286    fn navigate_tag_history(
 2287        &mut self,
 2288        pane: WeakEntity<Pane>,
 2289        mode: TagNavigationMode,
 2290        window: &mut Window,
 2291        cx: &mut Context<Workspace>,
 2292    ) -> Task<Result<()>> {
 2293        self.navigate_history_impl(
 2294            pane,
 2295            NavigationMode::Normal,
 2296            window,
 2297            &mut |history, _cx| history.pop_tag(mode),
 2298            cx,
 2299        )
 2300    }
 2301
 2302    fn navigate_history_impl(
 2303        &mut self,
 2304        pane: WeakEntity<Pane>,
 2305        mode: NavigationMode,
 2306        window: &mut Window,
 2307        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2308        cx: &mut Context<Workspace>,
 2309    ) -> Task<Result<()>> {
 2310        let to_load = if let Some(pane) = pane.upgrade() {
 2311            pane.update(cx, |pane, cx| {
 2312                window.focus(&pane.focus_handle(cx), cx);
 2313                loop {
 2314                    // Retrieve the weak item handle from the history.
 2315                    let entry = cb(pane.nav_history_mut(), cx)?;
 2316
 2317                    // If the item is still present in this pane, then activate it.
 2318                    if let Some(index) = entry
 2319                        .item
 2320                        .upgrade()
 2321                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2322                    {
 2323                        let prev_active_item_index = pane.active_item_index();
 2324                        pane.nav_history_mut().set_mode(mode);
 2325                        pane.activate_item(index, true, true, window, cx);
 2326                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2327
 2328                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2329                        if let Some(data) = entry.data {
 2330                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2331                        }
 2332
 2333                        if navigated {
 2334                            break None;
 2335                        }
 2336                    } else {
 2337                        // If the item is no longer present in this pane, then retrieve its
 2338                        // path info in order to reopen it.
 2339                        break pane
 2340                            .nav_history()
 2341                            .path_for_item(entry.item.id())
 2342                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2343                    }
 2344                }
 2345            })
 2346        } else {
 2347            None
 2348        };
 2349
 2350        if let Some((project_path, abs_path, entry)) = to_load {
 2351            // If the item was no longer present, then load it again from its previous path, first try the local path
 2352            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2353
 2354            cx.spawn_in(window, async move  |workspace, cx| {
 2355                let open_by_project_path = open_by_project_path.await;
 2356                let mut navigated = false;
 2357                match open_by_project_path
 2358                    .with_context(|| format!("Navigating to {project_path:?}"))
 2359                {
 2360                    Ok((project_entry_id, build_item)) => {
 2361                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2362                            pane.nav_history_mut().set_mode(mode);
 2363                            pane.active_item().map(|p| p.item_id())
 2364                        })?;
 2365
 2366                        pane.update_in(cx, |pane, window, cx| {
 2367                            let item = pane.open_item(
 2368                                project_entry_id,
 2369                                project_path,
 2370                                true,
 2371                                entry.is_preview,
 2372                                true,
 2373                                None,
 2374                                window, cx,
 2375                                build_item,
 2376                            );
 2377                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2378                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2379                            if let Some(data) = entry.data {
 2380                                navigated |= item.navigate(data, window, cx);
 2381                            }
 2382                        })?;
 2383                    }
 2384                    Err(open_by_project_path_e) => {
 2385                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2386                        // and its worktree is now dropped
 2387                        if let Some(abs_path) = abs_path {
 2388                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2389                                pane.nav_history_mut().set_mode(mode);
 2390                                pane.active_item().map(|p| p.item_id())
 2391                            })?;
 2392                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2393                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2394                            })?;
 2395                            match open_by_abs_path
 2396                                .await
 2397                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2398                            {
 2399                                Ok(item) => {
 2400                                    pane.update_in(cx, |pane, window, cx| {
 2401                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2402                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2403                                        if let Some(data) = entry.data {
 2404                                            navigated |= item.navigate(data, window, cx);
 2405                                        }
 2406                                    })?;
 2407                                }
 2408                                Err(open_by_abs_path_e) => {
 2409                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2410                                }
 2411                            }
 2412                        }
 2413                    }
 2414                }
 2415
 2416                if !navigated {
 2417                    workspace
 2418                        .update_in(cx, |workspace, window, cx| {
 2419                            Self::navigate_history(workspace, pane, mode, window, cx)
 2420                        })?
 2421                        .await?;
 2422                }
 2423
 2424                Ok(())
 2425            })
 2426        } else {
 2427            Task::ready(Ok(()))
 2428        }
 2429    }
 2430
 2431    pub fn go_back(
 2432        &mut self,
 2433        pane: WeakEntity<Pane>,
 2434        window: &mut Window,
 2435        cx: &mut Context<Workspace>,
 2436    ) -> Task<Result<()>> {
 2437        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2438    }
 2439
 2440    pub fn go_forward(
 2441        &mut self,
 2442        pane: WeakEntity<Pane>,
 2443        window: &mut Window,
 2444        cx: &mut Context<Workspace>,
 2445    ) -> Task<Result<()>> {
 2446        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2447    }
 2448
 2449    pub fn reopen_closed_item(
 2450        &mut self,
 2451        window: &mut Window,
 2452        cx: &mut Context<Workspace>,
 2453    ) -> Task<Result<()>> {
 2454        self.navigate_history(
 2455            self.active_pane().downgrade(),
 2456            NavigationMode::ReopeningClosedItem,
 2457            window,
 2458            cx,
 2459        )
 2460    }
 2461
 2462    pub fn client(&self) -> &Arc<Client> {
 2463        &self.app_state.client
 2464    }
 2465
 2466    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2467        self.titlebar_item = Some(item);
 2468        cx.notify();
 2469    }
 2470
 2471    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2472        self.on_prompt_for_new_path = Some(prompt)
 2473    }
 2474
 2475    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2476        self.on_prompt_for_open_path = Some(prompt)
 2477    }
 2478
 2479    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2480        self.terminal_provider = Some(Box::new(provider));
 2481    }
 2482
 2483    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2484        self.debugger_provider = Some(Arc::new(provider));
 2485    }
 2486
 2487    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2488        self.debugger_provider.clone()
 2489    }
 2490
 2491    pub fn prompt_for_open_path(
 2492        &mut self,
 2493        path_prompt_options: PathPromptOptions,
 2494        lister: DirectoryLister,
 2495        window: &mut Window,
 2496        cx: &mut Context<Self>,
 2497    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2498        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2499            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2500            let rx = prompt(self, lister, window, cx);
 2501            self.on_prompt_for_open_path = Some(prompt);
 2502            rx
 2503        } else {
 2504            let (tx, rx) = oneshot::channel();
 2505            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2506
 2507            cx.spawn_in(window, async move |workspace, cx| {
 2508                let Ok(result) = abs_path.await else {
 2509                    return Ok(());
 2510                };
 2511
 2512                match result {
 2513                    Ok(result) => {
 2514                        tx.send(result).ok();
 2515                    }
 2516                    Err(err) => {
 2517                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2518                            workspace.show_portal_error(err.to_string(), cx);
 2519                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2520                            let rx = prompt(workspace, lister, window, cx);
 2521                            workspace.on_prompt_for_open_path = Some(prompt);
 2522                            rx
 2523                        })?;
 2524                        if let Ok(path) = rx.await {
 2525                            tx.send(path).ok();
 2526                        }
 2527                    }
 2528                };
 2529                anyhow::Ok(())
 2530            })
 2531            .detach();
 2532
 2533            rx
 2534        }
 2535    }
 2536
 2537    pub fn prompt_for_new_path(
 2538        &mut self,
 2539        lister: DirectoryLister,
 2540        suggested_name: Option<String>,
 2541        window: &mut Window,
 2542        cx: &mut Context<Self>,
 2543    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2544        if self.project.read(cx).is_via_collab()
 2545            || self.project.read(cx).is_via_remote_server()
 2546            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2547        {
 2548            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2549            let rx = prompt(self, lister, suggested_name, window, cx);
 2550            self.on_prompt_for_new_path = Some(prompt);
 2551            return rx;
 2552        }
 2553
 2554        let (tx, rx) = oneshot::channel();
 2555        cx.spawn_in(window, async move |workspace, cx| {
 2556            let abs_path = workspace.update(cx, |workspace, cx| {
 2557                let relative_to = workspace
 2558                    .most_recent_active_path(cx)
 2559                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2560                    .or_else(|| {
 2561                        let project = workspace.project.read(cx);
 2562                        project.visible_worktrees(cx).find_map(|worktree| {
 2563                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2564                        })
 2565                    })
 2566                    .or_else(std::env::home_dir)
 2567                    .unwrap_or_else(|| PathBuf::from(""));
 2568                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2569            })?;
 2570            let abs_path = match abs_path.await? {
 2571                Ok(path) => path,
 2572                Err(err) => {
 2573                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2574                        workspace.show_portal_error(err.to_string(), cx);
 2575
 2576                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2577                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2578                        workspace.on_prompt_for_new_path = Some(prompt);
 2579                        rx
 2580                    })?;
 2581                    if let Ok(path) = rx.await {
 2582                        tx.send(path).ok();
 2583                    }
 2584                    return anyhow::Ok(());
 2585                }
 2586            };
 2587
 2588            tx.send(abs_path.map(|path| vec![path])).ok();
 2589            anyhow::Ok(())
 2590        })
 2591        .detach();
 2592
 2593        rx
 2594    }
 2595
 2596    pub fn titlebar_item(&self) -> Option<AnyView> {
 2597        self.titlebar_item.clone()
 2598    }
 2599
 2600    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2601    /// When set, git-related operations should use this worktree instead of deriving
 2602    /// the active worktree from the focused file.
 2603    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2604        self.active_worktree_override
 2605    }
 2606
 2607    pub fn set_active_worktree_override(
 2608        &mut self,
 2609        worktree_id: Option<WorktreeId>,
 2610        cx: &mut Context<Self>,
 2611    ) {
 2612        self.active_worktree_override = worktree_id;
 2613        cx.notify();
 2614    }
 2615
 2616    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2617        self.active_worktree_override = None;
 2618        cx.notify();
 2619    }
 2620
 2621    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2622    ///
 2623    /// If the given workspace has a local project, then it will be passed
 2624    /// to the callback. Otherwise, a new empty window will be created.
 2625    pub fn with_local_workspace<T, F>(
 2626        &mut self,
 2627        window: &mut Window,
 2628        cx: &mut Context<Self>,
 2629        callback: F,
 2630    ) -> Task<Result<T>>
 2631    where
 2632        T: 'static,
 2633        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2634    {
 2635        if self.project.read(cx).is_local() {
 2636            Task::ready(Ok(callback(self, window, cx)))
 2637        } else {
 2638            let env = self.project.read(cx).cli_environment(cx);
 2639            let task = Self::new_local(
 2640                Vec::new(),
 2641                self.app_state.clone(),
 2642                None,
 2643                env,
 2644                None,
 2645                true,
 2646                cx,
 2647            );
 2648            cx.spawn_in(window, async move |_vh, cx| {
 2649                let (multi_workspace_window, _) = task.await?;
 2650                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2651                    let workspace = multi_workspace.workspace().clone();
 2652                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2653                })
 2654            })
 2655        }
 2656    }
 2657
 2658    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2659    ///
 2660    /// If the given workspace has a local project, then it will be passed
 2661    /// to the callback. Otherwise, a new empty window will be created.
 2662    pub fn with_local_or_wsl_workspace<T, F>(
 2663        &mut self,
 2664        window: &mut Window,
 2665        cx: &mut Context<Self>,
 2666        callback: F,
 2667    ) -> Task<Result<T>>
 2668    where
 2669        T: 'static,
 2670        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2671    {
 2672        let project = self.project.read(cx);
 2673        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 2674            Task::ready(Ok(callback(self, window, cx)))
 2675        } else {
 2676            let env = self.project.read(cx).cli_environment(cx);
 2677            let task = Self::new_local(
 2678                Vec::new(),
 2679                self.app_state.clone(),
 2680                None,
 2681                env,
 2682                None,
 2683                true,
 2684                cx,
 2685            );
 2686            cx.spawn_in(window, async move |_vh, cx| {
 2687                let (multi_workspace_window, _) = task.await?;
 2688                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2689                    let workspace = multi_workspace.workspace().clone();
 2690                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2691                })
 2692            })
 2693        }
 2694    }
 2695
 2696    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2697        self.project.read(cx).worktrees(cx)
 2698    }
 2699
 2700    pub fn visible_worktrees<'a>(
 2701        &self,
 2702        cx: &'a App,
 2703    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2704        self.project.read(cx).visible_worktrees(cx)
 2705    }
 2706
 2707    #[cfg(any(test, feature = "test-support"))]
 2708    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2709        let futures = self
 2710            .worktrees(cx)
 2711            .filter_map(|worktree| worktree.read(cx).as_local())
 2712            .map(|worktree| worktree.scan_complete())
 2713            .collect::<Vec<_>>();
 2714        async move {
 2715            for future in futures {
 2716                future.await;
 2717            }
 2718        }
 2719    }
 2720
 2721    pub fn close_global(cx: &mut App) {
 2722        cx.defer(|cx| {
 2723            cx.windows().iter().find(|window| {
 2724                window
 2725                    .update(cx, |_, window, _| {
 2726                        if window.is_window_active() {
 2727                            //This can only get called when the window's project connection has been lost
 2728                            //so we don't need to prompt the user for anything and instead just close the window
 2729                            window.remove_window();
 2730                            true
 2731                        } else {
 2732                            false
 2733                        }
 2734                    })
 2735                    .unwrap_or(false)
 2736            });
 2737        });
 2738    }
 2739
 2740    pub fn move_focused_panel_to_next_position(
 2741        &mut self,
 2742        _: &MoveFocusedPanelToNextPosition,
 2743        window: &mut Window,
 2744        cx: &mut Context<Self>,
 2745    ) {
 2746        let docks = self.all_docks();
 2747        let active_dock = docks
 2748            .into_iter()
 2749            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 2750
 2751        if let Some(dock) = active_dock {
 2752            dock.update(cx, |dock, cx| {
 2753                let active_panel = dock
 2754                    .active_panel()
 2755                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 2756
 2757                if let Some(panel) = active_panel {
 2758                    panel.move_to_next_position(window, cx);
 2759                }
 2760            })
 2761        }
 2762    }
 2763
 2764    pub fn prepare_to_close(
 2765        &mut self,
 2766        close_intent: CloseIntent,
 2767        window: &mut Window,
 2768        cx: &mut Context<Self>,
 2769    ) -> Task<Result<bool>> {
 2770        let active_call = self.active_global_call();
 2771
 2772        cx.spawn_in(window, async move |this, cx| {
 2773            this.update(cx, |this, _| {
 2774                if close_intent == CloseIntent::CloseWindow {
 2775                    this.removing = true;
 2776                }
 2777            })?;
 2778
 2779            let workspace_count = cx.update(|_window, cx| {
 2780                cx.windows()
 2781                    .iter()
 2782                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 2783                    .count()
 2784            })?;
 2785
 2786            #[cfg(target_os = "macos")]
 2787            let save_last_workspace = false;
 2788
 2789            // On Linux and Windows, closing the last window should restore the last workspace.
 2790            #[cfg(not(target_os = "macos"))]
 2791            let save_last_workspace = {
 2792                let remaining_workspaces = cx.update(|_window, cx| {
 2793                    cx.windows()
 2794                        .iter()
 2795                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 2796                        .filter_map(|multi_workspace| {
 2797                            multi_workspace
 2798                                .update(cx, |multi_workspace, _, cx| {
 2799                                    multi_workspace.workspace().read(cx).removing
 2800                                })
 2801                                .ok()
 2802                        })
 2803                        .filter(|removing| !removing)
 2804                        .count()
 2805                })?;
 2806
 2807                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 2808            };
 2809
 2810            if let Some(active_call) = active_call
 2811                && workspace_count == 1
 2812                && cx
 2813                    .update(|_window, cx| active_call.0.is_in_room(cx))
 2814                    .unwrap_or(false)
 2815            {
 2816                if close_intent == CloseIntent::CloseWindow {
 2817                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 2818                    let answer = cx.update(|window, cx| {
 2819                        window.prompt(
 2820                            PromptLevel::Warning,
 2821                            "Do you want to leave the current call?",
 2822                            None,
 2823                            &["Close window and hang up", "Cancel"],
 2824                            cx,
 2825                        )
 2826                    })?;
 2827
 2828                    if answer.await.log_err() == Some(1) {
 2829                        return anyhow::Ok(false);
 2830                    } else {
 2831                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 2832                            task.await.log_err();
 2833                        }
 2834                    }
 2835                }
 2836                if close_intent == CloseIntent::ReplaceWindow {
 2837                    _ = cx.update(|_window, cx| {
 2838                        let multi_workspace = cx
 2839                            .windows()
 2840                            .iter()
 2841                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 2842                            .next()
 2843                            .unwrap();
 2844                        let project = multi_workspace
 2845                            .read(cx)?
 2846                            .workspace()
 2847                            .read(cx)
 2848                            .project
 2849                            .clone();
 2850                        if project.read(cx).is_shared() {
 2851                            active_call.0.unshare_project(project, cx)?;
 2852                        }
 2853                        Ok::<_, anyhow::Error>(())
 2854                    });
 2855                }
 2856            }
 2857
 2858            let save_result = this
 2859                .update_in(cx, |this, window, cx| {
 2860                    this.save_all_internal(SaveIntent::Close, window, cx)
 2861                })?
 2862                .await;
 2863
 2864            // If we're not quitting, but closing, we remove the workspace from
 2865            // the current session.
 2866            if close_intent != CloseIntent::Quit
 2867                && !save_last_workspace
 2868                && save_result.as_ref().is_ok_and(|&res| res)
 2869            {
 2870                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 2871                    .await;
 2872            }
 2873
 2874            save_result
 2875        })
 2876    }
 2877
 2878    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 2879        self.save_all_internal(
 2880            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 2881            window,
 2882            cx,
 2883        )
 2884        .detach_and_log_err(cx);
 2885    }
 2886
 2887    fn send_keystrokes(
 2888        &mut self,
 2889        action: &SendKeystrokes,
 2890        window: &mut Window,
 2891        cx: &mut Context<Self>,
 2892    ) {
 2893        let keystrokes: Vec<Keystroke> = action
 2894            .0
 2895            .split(' ')
 2896            .flat_map(|k| Keystroke::parse(k).log_err())
 2897            .map(|k| {
 2898                cx.keyboard_mapper()
 2899                    .map_key_equivalent(k, false)
 2900                    .inner()
 2901                    .clone()
 2902            })
 2903            .collect();
 2904        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 2905    }
 2906
 2907    pub fn send_keystrokes_impl(
 2908        &mut self,
 2909        keystrokes: Vec<Keystroke>,
 2910        window: &mut Window,
 2911        cx: &mut Context<Self>,
 2912    ) -> Shared<Task<()>> {
 2913        let mut state = self.dispatching_keystrokes.borrow_mut();
 2914        if !state.dispatched.insert(keystrokes.clone()) {
 2915            cx.propagate();
 2916            return state.task.clone().unwrap();
 2917        }
 2918
 2919        state.queue.extend(keystrokes);
 2920
 2921        let keystrokes = self.dispatching_keystrokes.clone();
 2922        if state.task.is_none() {
 2923            state.task = Some(
 2924                window
 2925                    .spawn(cx, async move |cx| {
 2926                        // limit to 100 keystrokes to avoid infinite recursion.
 2927                        for _ in 0..100 {
 2928                            let keystroke = {
 2929                                let mut state = keystrokes.borrow_mut();
 2930                                let Some(keystroke) = state.queue.pop_front() else {
 2931                                    state.dispatched.clear();
 2932                                    state.task.take();
 2933                                    return;
 2934                                };
 2935                                keystroke
 2936                            };
 2937                            cx.update(|window, cx| {
 2938                                let focused = window.focused(cx);
 2939                                window.dispatch_keystroke(keystroke.clone(), cx);
 2940                                if window.focused(cx) != focused {
 2941                                    // dispatch_keystroke may cause the focus to change.
 2942                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 2943                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 2944                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 2945                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 2946                                    // )
 2947                                    window.draw(cx).clear();
 2948                                }
 2949                            })
 2950                            .ok();
 2951
 2952                            // Yield between synthetic keystrokes so deferred focus and
 2953                            // other effects can settle before dispatching the next key.
 2954                            yield_now().await;
 2955                        }
 2956
 2957                        *keystrokes.borrow_mut() = Default::default();
 2958                        log::error!("over 100 keystrokes passed to send_keystrokes");
 2959                    })
 2960                    .shared(),
 2961            );
 2962        }
 2963        state.task.clone().unwrap()
 2964    }
 2965
 2966    fn save_all_internal(
 2967        &mut self,
 2968        mut save_intent: SaveIntent,
 2969        window: &mut Window,
 2970        cx: &mut Context<Self>,
 2971    ) -> Task<Result<bool>> {
 2972        if self.project.read(cx).is_disconnected(cx) {
 2973            return Task::ready(Ok(true));
 2974        }
 2975        let dirty_items = self
 2976            .panes
 2977            .iter()
 2978            .flat_map(|pane| {
 2979                pane.read(cx).items().filter_map(|item| {
 2980                    if item.is_dirty(cx) {
 2981                        item.tab_content_text(0, cx);
 2982                        Some((pane.downgrade(), item.boxed_clone()))
 2983                    } else {
 2984                        None
 2985                    }
 2986                })
 2987            })
 2988            .collect::<Vec<_>>();
 2989
 2990        let project = self.project.clone();
 2991        cx.spawn_in(window, async move |workspace, cx| {
 2992            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 2993                let (serialize_tasks, remaining_dirty_items) =
 2994                    workspace.update_in(cx, |workspace, window, cx| {
 2995                        let mut remaining_dirty_items = Vec::new();
 2996                        let mut serialize_tasks = Vec::new();
 2997                        for (pane, item) in dirty_items {
 2998                            if let Some(task) = item
 2999                                .to_serializable_item_handle(cx)
 3000                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3001                            {
 3002                                serialize_tasks.push(task);
 3003                            } else {
 3004                                remaining_dirty_items.push((pane, item));
 3005                            }
 3006                        }
 3007                        (serialize_tasks, remaining_dirty_items)
 3008                    })?;
 3009
 3010                futures::future::try_join_all(serialize_tasks).await?;
 3011
 3012                if !remaining_dirty_items.is_empty() {
 3013                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3014                }
 3015
 3016                if remaining_dirty_items.len() > 1 {
 3017                    let answer = workspace.update_in(cx, |_, window, cx| {
 3018                        let detail = Pane::file_names_for_prompt(
 3019                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3020                            cx,
 3021                        );
 3022                        window.prompt(
 3023                            PromptLevel::Warning,
 3024                            "Do you want to save all changes in the following files?",
 3025                            Some(&detail),
 3026                            &["Save all", "Discard all", "Cancel"],
 3027                            cx,
 3028                        )
 3029                    })?;
 3030                    match answer.await.log_err() {
 3031                        Some(0) => save_intent = SaveIntent::SaveAll,
 3032                        Some(1) => save_intent = SaveIntent::Skip,
 3033                        Some(2) => return Ok(false),
 3034                        _ => {}
 3035                    }
 3036                }
 3037
 3038                remaining_dirty_items
 3039            } else {
 3040                dirty_items
 3041            };
 3042
 3043            for (pane, item) in dirty_items {
 3044                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3045                    (
 3046                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3047                        item.project_entry_ids(cx),
 3048                    )
 3049                })?;
 3050                if (singleton || !project_entry_ids.is_empty())
 3051                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3052                {
 3053                    return Ok(false);
 3054                }
 3055            }
 3056            Ok(true)
 3057        })
 3058    }
 3059
 3060    pub fn open_workspace_for_paths(
 3061        &mut self,
 3062        replace_current_window: bool,
 3063        paths: Vec<PathBuf>,
 3064        window: &mut Window,
 3065        cx: &mut Context<Self>,
 3066    ) -> Task<Result<()>> {
 3067        let window_handle = window.window_handle().downcast::<MultiWorkspace>();
 3068        let is_remote = self.project.read(cx).is_via_collab();
 3069        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3070        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3071
 3072        let window_to_replace = if replace_current_window {
 3073            window_handle
 3074        } else if is_remote || has_worktree || has_dirty_items {
 3075            None
 3076        } else {
 3077            window_handle
 3078        };
 3079        let app_state = self.app_state.clone();
 3080
 3081        cx.spawn(async move |_, cx| {
 3082            cx.update(|cx| {
 3083                open_paths(
 3084                    &paths,
 3085                    app_state,
 3086                    OpenOptions {
 3087                        replace_window: window_to_replace,
 3088                        ..Default::default()
 3089                    },
 3090                    cx,
 3091                )
 3092            })
 3093            .await?;
 3094            Ok(())
 3095        })
 3096    }
 3097
 3098    #[allow(clippy::type_complexity)]
 3099    pub fn open_paths(
 3100        &mut self,
 3101        mut abs_paths: Vec<PathBuf>,
 3102        options: OpenOptions,
 3103        pane: Option<WeakEntity<Pane>>,
 3104        window: &mut Window,
 3105        cx: &mut Context<Self>,
 3106    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3107        let fs = self.app_state.fs.clone();
 3108
 3109        let caller_ordered_abs_paths = abs_paths.clone();
 3110
 3111        // Sort the paths to ensure we add worktrees for parents before their children.
 3112        abs_paths.sort_unstable();
 3113        cx.spawn_in(window, async move |this, cx| {
 3114            let mut tasks = Vec::with_capacity(abs_paths.len());
 3115
 3116            for abs_path in &abs_paths {
 3117                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3118                    OpenVisible::All => Some(true),
 3119                    OpenVisible::None => Some(false),
 3120                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3121                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3122                        Some(None) => Some(true),
 3123                        None => None,
 3124                    },
 3125                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3126                        Some(Some(metadata)) => Some(metadata.is_dir),
 3127                        Some(None) => Some(false),
 3128                        None => None,
 3129                    },
 3130                };
 3131                let project_path = match visible {
 3132                    Some(visible) => match this
 3133                        .update(cx, |this, cx| {
 3134                            Workspace::project_path_for_path(
 3135                                this.project.clone(),
 3136                                abs_path,
 3137                                visible,
 3138                                cx,
 3139                            )
 3140                        })
 3141                        .log_err()
 3142                    {
 3143                        Some(project_path) => project_path.await.log_err(),
 3144                        None => None,
 3145                    },
 3146                    None => None,
 3147                };
 3148
 3149                let this = this.clone();
 3150                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3151                let fs = fs.clone();
 3152                let pane = pane.clone();
 3153                let task = cx.spawn(async move |cx| {
 3154                    let (_worktree, project_path) = project_path?;
 3155                    if fs.is_dir(&abs_path).await {
 3156                        // Opening a directory should not race to update the active entry.
 3157                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3158                        None
 3159                    } else {
 3160                        Some(
 3161                            this.update_in(cx, |this, window, cx| {
 3162                                this.open_path(
 3163                                    project_path,
 3164                                    pane,
 3165                                    options.focus.unwrap_or(true),
 3166                                    window,
 3167                                    cx,
 3168                                )
 3169                            })
 3170                            .ok()?
 3171                            .await,
 3172                        )
 3173                    }
 3174                });
 3175                tasks.push(task);
 3176            }
 3177
 3178            let results = futures::future::join_all(tasks).await;
 3179
 3180            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3181            let mut winner: Option<(PathBuf, bool)> = None;
 3182            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3183                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3184                    if !metadata.is_dir {
 3185                        winner = Some((abs_path, false));
 3186                        break;
 3187                    }
 3188                    if winner.is_none() {
 3189                        winner = Some((abs_path, true));
 3190                    }
 3191                } else if winner.is_none() {
 3192                    winner = Some((abs_path, false));
 3193                }
 3194            }
 3195
 3196            // Compute the winner entry id on the foreground thread and emit once, after all
 3197            // paths finish opening. This avoids races between concurrently-opening paths
 3198            // (directories in particular) and makes the resulting project panel selection
 3199            // deterministic.
 3200            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3201                'emit_winner: {
 3202                    let winner_abs_path: Arc<Path> =
 3203                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3204
 3205                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3206                        OpenVisible::All => true,
 3207                        OpenVisible::None => false,
 3208                        OpenVisible::OnlyFiles => !winner_is_dir,
 3209                        OpenVisible::OnlyDirectories => winner_is_dir,
 3210                    };
 3211
 3212                    let Some(worktree_task) = this
 3213                        .update(cx, |workspace, cx| {
 3214                            workspace.project.update(cx, |project, cx| {
 3215                                project.find_or_create_worktree(
 3216                                    winner_abs_path.as_ref(),
 3217                                    visible,
 3218                                    cx,
 3219                                )
 3220                            })
 3221                        })
 3222                        .ok()
 3223                    else {
 3224                        break 'emit_winner;
 3225                    };
 3226
 3227                    let Ok((worktree, _)) = worktree_task.await else {
 3228                        break 'emit_winner;
 3229                    };
 3230
 3231                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3232                        let worktree = worktree.read(cx);
 3233                        let worktree_abs_path = worktree.abs_path();
 3234                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3235                            worktree.root_entry()
 3236                        } else {
 3237                            winner_abs_path
 3238                                .strip_prefix(worktree_abs_path.as_ref())
 3239                                .ok()
 3240                                .and_then(|relative_path| {
 3241                                    let relative_path =
 3242                                        RelPath::new(relative_path, PathStyle::local())
 3243                                            .log_err()?;
 3244                                    worktree.entry_for_path(&relative_path)
 3245                                })
 3246                        }?;
 3247                        Some(entry.id)
 3248                    }) else {
 3249                        break 'emit_winner;
 3250                    };
 3251
 3252                    this.update(cx, |workspace, cx| {
 3253                        workspace.project.update(cx, |_, cx| {
 3254                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3255                        });
 3256                    })
 3257                    .ok();
 3258                }
 3259            }
 3260
 3261            results
 3262        })
 3263    }
 3264
 3265    pub fn open_resolved_path(
 3266        &mut self,
 3267        path: ResolvedPath,
 3268        window: &mut Window,
 3269        cx: &mut Context<Self>,
 3270    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3271        match path {
 3272            ResolvedPath::ProjectPath { project_path, .. } => {
 3273                self.open_path(project_path, None, true, window, cx)
 3274            }
 3275            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3276                PathBuf::from(path),
 3277                OpenOptions {
 3278                    visible: Some(OpenVisible::None),
 3279                    ..Default::default()
 3280                },
 3281                window,
 3282                cx,
 3283            ),
 3284        }
 3285    }
 3286
 3287    pub fn absolute_path_of_worktree(
 3288        &self,
 3289        worktree_id: WorktreeId,
 3290        cx: &mut Context<Self>,
 3291    ) -> Option<PathBuf> {
 3292        self.project
 3293            .read(cx)
 3294            .worktree_for_id(worktree_id, cx)
 3295            // TODO: use `abs_path` or `root_dir`
 3296            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3297    }
 3298
 3299    fn add_folder_to_project(
 3300        &mut self,
 3301        _: &AddFolderToProject,
 3302        window: &mut Window,
 3303        cx: &mut Context<Self>,
 3304    ) {
 3305        let project = self.project.read(cx);
 3306        if project.is_via_collab() {
 3307            self.show_error(
 3308                &anyhow!("You cannot add folders to someone else's project"),
 3309                cx,
 3310            );
 3311            return;
 3312        }
 3313        let paths = self.prompt_for_open_path(
 3314            PathPromptOptions {
 3315                files: false,
 3316                directories: true,
 3317                multiple: true,
 3318                prompt: None,
 3319            },
 3320            DirectoryLister::Project(self.project.clone()),
 3321            window,
 3322            cx,
 3323        );
 3324        cx.spawn_in(window, async move |this, cx| {
 3325            if let Some(paths) = paths.await.log_err().flatten() {
 3326                let results = this
 3327                    .update_in(cx, |this, window, cx| {
 3328                        this.open_paths(
 3329                            paths,
 3330                            OpenOptions {
 3331                                visible: Some(OpenVisible::All),
 3332                                ..Default::default()
 3333                            },
 3334                            None,
 3335                            window,
 3336                            cx,
 3337                        )
 3338                    })?
 3339                    .await;
 3340                for result in results.into_iter().flatten() {
 3341                    result.log_err();
 3342                }
 3343            }
 3344            anyhow::Ok(())
 3345        })
 3346        .detach_and_log_err(cx);
 3347    }
 3348
 3349    pub fn project_path_for_path(
 3350        project: Entity<Project>,
 3351        abs_path: &Path,
 3352        visible: bool,
 3353        cx: &mut App,
 3354    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3355        let entry = project.update(cx, |project, cx| {
 3356            project.find_or_create_worktree(abs_path, visible, cx)
 3357        });
 3358        cx.spawn(async move |cx| {
 3359            let (worktree, path) = entry.await?;
 3360            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3361            Ok((worktree, ProjectPath { worktree_id, path }))
 3362        })
 3363    }
 3364
 3365    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3366        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3367    }
 3368
 3369    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3370        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3371    }
 3372
 3373    pub fn items_of_type<'a, T: Item>(
 3374        &'a self,
 3375        cx: &'a App,
 3376    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3377        self.panes
 3378            .iter()
 3379            .flat_map(|pane| pane.read(cx).items_of_type())
 3380    }
 3381
 3382    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3383        self.active_pane().read(cx).active_item()
 3384    }
 3385
 3386    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3387        let item = self.active_item(cx)?;
 3388        item.to_any_view().downcast::<I>().ok()
 3389    }
 3390
 3391    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3392        self.active_item(cx).and_then(|item| item.project_path(cx))
 3393    }
 3394
 3395    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3396        self.recent_navigation_history_iter(cx)
 3397            .filter_map(|(path, abs_path)| {
 3398                let worktree = self
 3399                    .project
 3400                    .read(cx)
 3401                    .worktree_for_id(path.worktree_id, cx)?;
 3402                if worktree.read(cx).is_visible() {
 3403                    abs_path
 3404                } else {
 3405                    None
 3406                }
 3407            })
 3408            .next()
 3409    }
 3410
 3411    pub fn save_active_item(
 3412        &mut self,
 3413        save_intent: SaveIntent,
 3414        window: &mut Window,
 3415        cx: &mut App,
 3416    ) -> Task<Result<()>> {
 3417        let project = self.project.clone();
 3418        let pane = self.active_pane();
 3419        let item = pane.read(cx).active_item();
 3420        let pane = pane.downgrade();
 3421
 3422        window.spawn(cx, async move |cx| {
 3423            if let Some(item) = item {
 3424                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3425                    .await
 3426                    .map(|_| ())
 3427            } else {
 3428                Ok(())
 3429            }
 3430        })
 3431    }
 3432
 3433    pub fn close_inactive_items_and_panes(
 3434        &mut self,
 3435        action: &CloseInactiveTabsAndPanes,
 3436        window: &mut Window,
 3437        cx: &mut Context<Self>,
 3438    ) {
 3439        if let Some(task) = self.close_all_internal(
 3440            true,
 3441            action.save_intent.unwrap_or(SaveIntent::Close),
 3442            window,
 3443            cx,
 3444        ) {
 3445            task.detach_and_log_err(cx)
 3446        }
 3447    }
 3448
 3449    pub fn close_all_items_and_panes(
 3450        &mut self,
 3451        action: &CloseAllItemsAndPanes,
 3452        window: &mut Window,
 3453        cx: &mut Context<Self>,
 3454    ) {
 3455        if let Some(task) = self.close_all_internal(
 3456            false,
 3457            action.save_intent.unwrap_or(SaveIntent::Close),
 3458            window,
 3459            cx,
 3460        ) {
 3461            task.detach_and_log_err(cx)
 3462        }
 3463    }
 3464
 3465    /// Closes the active item across all panes.
 3466    pub fn close_item_in_all_panes(
 3467        &mut self,
 3468        action: &CloseItemInAllPanes,
 3469        window: &mut Window,
 3470        cx: &mut Context<Self>,
 3471    ) {
 3472        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3473            return;
 3474        };
 3475
 3476        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3477        let close_pinned = action.close_pinned;
 3478
 3479        if let Some(project_path) = active_item.project_path(cx) {
 3480            self.close_items_with_project_path(
 3481                &project_path,
 3482                save_intent,
 3483                close_pinned,
 3484                window,
 3485                cx,
 3486            );
 3487        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3488            let item_id = active_item.item_id();
 3489            self.active_pane().update(cx, |pane, cx| {
 3490                pane.close_item_by_id(item_id, save_intent, window, cx)
 3491                    .detach_and_log_err(cx);
 3492            });
 3493        }
 3494    }
 3495
 3496    /// Closes all items with the given project path across all panes.
 3497    pub fn close_items_with_project_path(
 3498        &mut self,
 3499        project_path: &ProjectPath,
 3500        save_intent: SaveIntent,
 3501        close_pinned: bool,
 3502        window: &mut Window,
 3503        cx: &mut Context<Self>,
 3504    ) {
 3505        let panes = self.panes().to_vec();
 3506        for pane in panes {
 3507            pane.update(cx, |pane, cx| {
 3508                pane.close_items_for_project_path(
 3509                    project_path,
 3510                    save_intent,
 3511                    close_pinned,
 3512                    window,
 3513                    cx,
 3514                )
 3515                .detach_and_log_err(cx);
 3516            });
 3517        }
 3518    }
 3519
 3520    fn close_all_internal(
 3521        &mut self,
 3522        retain_active_pane: bool,
 3523        save_intent: SaveIntent,
 3524        window: &mut Window,
 3525        cx: &mut Context<Self>,
 3526    ) -> Option<Task<Result<()>>> {
 3527        let current_pane = self.active_pane();
 3528
 3529        let mut tasks = Vec::new();
 3530
 3531        if retain_active_pane {
 3532            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3533                pane.close_other_items(
 3534                    &CloseOtherItems {
 3535                        save_intent: None,
 3536                        close_pinned: false,
 3537                    },
 3538                    None,
 3539                    window,
 3540                    cx,
 3541                )
 3542            });
 3543
 3544            tasks.push(current_pane_close);
 3545        }
 3546
 3547        for pane in self.panes() {
 3548            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3549                continue;
 3550            }
 3551
 3552            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3553                pane.close_all_items(
 3554                    &CloseAllItems {
 3555                        save_intent: Some(save_intent),
 3556                        close_pinned: false,
 3557                    },
 3558                    window,
 3559                    cx,
 3560                )
 3561            });
 3562
 3563            tasks.push(close_pane_items)
 3564        }
 3565
 3566        if tasks.is_empty() {
 3567            None
 3568        } else {
 3569            Some(cx.spawn_in(window, async move |_, _| {
 3570                for task in tasks {
 3571                    task.await?
 3572                }
 3573                Ok(())
 3574            }))
 3575        }
 3576    }
 3577
 3578    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3579        self.dock_at_position(position).read(cx).is_open()
 3580    }
 3581
 3582    pub fn toggle_dock(
 3583        &mut self,
 3584        dock_side: DockPosition,
 3585        window: &mut Window,
 3586        cx: &mut Context<Self>,
 3587    ) {
 3588        let mut focus_center = false;
 3589        let mut reveal_dock = false;
 3590
 3591        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3592        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3593
 3594        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3595            telemetry::event!(
 3596                "Panel Button Clicked",
 3597                name = panel.persistent_name(),
 3598                toggle_state = !was_visible
 3599            );
 3600        }
 3601        if was_visible {
 3602            self.save_open_dock_positions(cx);
 3603        }
 3604
 3605        let dock = self.dock_at_position(dock_side);
 3606        dock.update(cx, |dock, cx| {
 3607            dock.set_open(!was_visible, window, cx);
 3608
 3609            if dock.active_panel().is_none() {
 3610                let Some(panel_ix) = dock
 3611                    .first_enabled_panel_idx(cx)
 3612                    .log_with_level(log::Level::Info)
 3613                else {
 3614                    return;
 3615                };
 3616                dock.activate_panel(panel_ix, window, cx);
 3617            }
 3618
 3619            if let Some(active_panel) = dock.active_panel() {
 3620                if was_visible {
 3621                    if active_panel
 3622                        .panel_focus_handle(cx)
 3623                        .contains_focused(window, cx)
 3624                    {
 3625                        focus_center = true;
 3626                    }
 3627                } else {
 3628                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3629                    window.focus(focus_handle, cx);
 3630                    reveal_dock = true;
 3631                }
 3632            }
 3633        });
 3634
 3635        if reveal_dock {
 3636            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3637        }
 3638
 3639        if focus_center {
 3640            self.active_pane
 3641                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3642        }
 3643
 3644        cx.notify();
 3645        self.serialize_workspace(window, cx);
 3646    }
 3647
 3648    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3649        self.all_docks().into_iter().find(|&dock| {
 3650            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3651        })
 3652    }
 3653
 3654    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3655        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3656            self.save_open_dock_positions(cx);
 3657            dock.update(cx, |dock, cx| {
 3658                dock.set_open(false, window, cx);
 3659            });
 3660            return true;
 3661        }
 3662        false
 3663    }
 3664
 3665    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3666        self.save_open_dock_positions(cx);
 3667        for dock in self.all_docks() {
 3668            dock.update(cx, |dock, cx| {
 3669                dock.set_open(false, window, cx);
 3670            });
 3671        }
 3672
 3673        cx.focus_self(window);
 3674        cx.notify();
 3675        self.serialize_workspace(window, cx);
 3676    }
 3677
 3678    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 3679        self.all_docks()
 3680            .into_iter()
 3681            .filter_map(|dock| {
 3682                let dock_ref = dock.read(cx);
 3683                if dock_ref.is_open() {
 3684                    Some(dock_ref.position())
 3685                } else {
 3686                    None
 3687                }
 3688            })
 3689            .collect()
 3690    }
 3691
 3692    /// Saves the positions of currently open docks.
 3693    ///
 3694    /// Updates `last_open_dock_positions` with positions of all currently open
 3695    /// docks, to later be restored by the 'Toggle All Docks' action.
 3696    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 3697        let open_dock_positions = self.get_open_dock_positions(cx);
 3698        if !open_dock_positions.is_empty() {
 3699            self.last_open_dock_positions = open_dock_positions;
 3700        }
 3701    }
 3702
 3703    /// Toggles all docks between open and closed states.
 3704    ///
 3705    /// If any docks are open, closes all and remembers their positions. If all
 3706    /// docks are closed, restores the last remembered dock configuration.
 3707    fn toggle_all_docks(
 3708        &mut self,
 3709        _: &ToggleAllDocks,
 3710        window: &mut Window,
 3711        cx: &mut Context<Self>,
 3712    ) {
 3713        let open_dock_positions = self.get_open_dock_positions(cx);
 3714
 3715        if !open_dock_positions.is_empty() {
 3716            self.close_all_docks(window, cx);
 3717        } else if !self.last_open_dock_positions.is_empty() {
 3718            self.restore_last_open_docks(window, cx);
 3719        }
 3720    }
 3721
 3722    /// Reopens docks from the most recently remembered configuration.
 3723    ///
 3724    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 3725    /// and clears the stored positions.
 3726    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3727        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 3728
 3729        for position in positions_to_open {
 3730            let dock = self.dock_at_position(position);
 3731            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 3732        }
 3733
 3734        cx.focus_self(window);
 3735        cx.notify();
 3736        self.serialize_workspace(window, cx);
 3737    }
 3738
 3739    /// Transfer focus to the panel of the given type.
 3740    pub fn focus_panel<T: Panel>(
 3741        &mut self,
 3742        window: &mut Window,
 3743        cx: &mut Context<Self>,
 3744    ) -> Option<Entity<T>> {
 3745        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 3746        panel.to_any().downcast().ok()
 3747    }
 3748
 3749    /// Focus the panel of the given type if it isn't already focused. If it is
 3750    /// already focused, then transfer focus back to the workspace center.
 3751    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 3752    /// panel when transferring focus back to the center.
 3753    pub fn toggle_panel_focus<T: Panel>(
 3754        &mut self,
 3755        window: &mut Window,
 3756        cx: &mut Context<Self>,
 3757    ) -> bool {
 3758        let mut did_focus_panel = false;
 3759        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 3760            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 3761            did_focus_panel
 3762        });
 3763
 3764        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 3765            self.close_panel::<T>(window, cx);
 3766        }
 3767
 3768        telemetry::event!(
 3769            "Panel Button Clicked",
 3770            name = T::persistent_name(),
 3771            toggle_state = did_focus_panel
 3772        );
 3773
 3774        did_focus_panel
 3775    }
 3776
 3777    pub fn activate_panel_for_proto_id(
 3778        &mut self,
 3779        panel_id: PanelId,
 3780        window: &mut Window,
 3781        cx: &mut Context<Self>,
 3782    ) -> Option<Arc<dyn PanelHandle>> {
 3783        let mut panel = None;
 3784        for dock in self.all_docks() {
 3785            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 3786                panel = dock.update(cx, |dock, cx| {
 3787                    dock.activate_panel(panel_index, window, cx);
 3788                    dock.set_open(true, window, cx);
 3789                    dock.active_panel().cloned()
 3790                });
 3791                break;
 3792            }
 3793        }
 3794
 3795        if panel.is_some() {
 3796            cx.notify();
 3797            self.serialize_workspace(window, cx);
 3798        }
 3799
 3800        panel
 3801    }
 3802
 3803    /// Focus or unfocus the given panel type, depending on the given callback.
 3804    fn focus_or_unfocus_panel<T: Panel>(
 3805        &mut self,
 3806        window: &mut Window,
 3807        cx: &mut Context<Self>,
 3808        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 3809    ) -> Option<Arc<dyn PanelHandle>> {
 3810        let mut result_panel = None;
 3811        let mut serialize = false;
 3812        for dock in self.all_docks() {
 3813            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3814                let mut focus_center = false;
 3815                let panel = dock.update(cx, |dock, cx| {
 3816                    dock.activate_panel(panel_index, window, cx);
 3817
 3818                    let panel = dock.active_panel().cloned();
 3819                    if let Some(panel) = panel.as_ref() {
 3820                        if should_focus(&**panel, window, cx) {
 3821                            dock.set_open(true, window, cx);
 3822                            panel.panel_focus_handle(cx).focus(window, cx);
 3823                        } else {
 3824                            focus_center = true;
 3825                        }
 3826                    }
 3827                    panel
 3828                });
 3829
 3830                if focus_center {
 3831                    self.active_pane
 3832                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3833                }
 3834
 3835                result_panel = panel;
 3836                serialize = true;
 3837                break;
 3838            }
 3839        }
 3840
 3841        if serialize {
 3842            self.serialize_workspace(window, cx);
 3843        }
 3844
 3845        cx.notify();
 3846        result_panel
 3847    }
 3848
 3849    /// Open the panel of the given type
 3850    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3851        for dock in self.all_docks() {
 3852            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3853                dock.update(cx, |dock, cx| {
 3854                    dock.activate_panel(panel_index, window, cx);
 3855                    dock.set_open(true, window, cx);
 3856                });
 3857            }
 3858        }
 3859    }
 3860
 3861    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 3862        for dock in self.all_docks().iter() {
 3863            dock.update(cx, |dock, cx| {
 3864                if dock.panel::<T>().is_some() {
 3865                    dock.set_open(false, window, cx)
 3866                }
 3867            })
 3868        }
 3869    }
 3870
 3871    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 3872        self.all_docks()
 3873            .iter()
 3874            .find_map(|dock| dock.read(cx).panel::<T>())
 3875    }
 3876
 3877    fn dismiss_zoomed_items_to_reveal(
 3878        &mut self,
 3879        dock_to_reveal: Option<DockPosition>,
 3880        window: &mut Window,
 3881        cx: &mut Context<Self>,
 3882    ) {
 3883        // If a center pane is zoomed, unzoom it.
 3884        for pane in &self.panes {
 3885            if pane != &self.active_pane || dock_to_reveal.is_some() {
 3886                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 3887            }
 3888        }
 3889
 3890        // If another dock is zoomed, hide it.
 3891        let mut focus_center = false;
 3892        for dock in self.all_docks() {
 3893            dock.update(cx, |dock, cx| {
 3894                if Some(dock.position()) != dock_to_reveal
 3895                    && let Some(panel) = dock.active_panel()
 3896                    && panel.is_zoomed(window, cx)
 3897                {
 3898                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 3899                    dock.set_open(false, window, cx);
 3900                }
 3901            });
 3902        }
 3903
 3904        if focus_center {
 3905            self.active_pane
 3906                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3907        }
 3908
 3909        if self.zoomed_position != dock_to_reveal {
 3910            self.zoomed = None;
 3911            self.zoomed_position = None;
 3912            cx.emit(Event::ZoomChanged);
 3913        }
 3914
 3915        cx.notify();
 3916    }
 3917
 3918    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 3919        let pane = cx.new(|cx| {
 3920            let mut pane = Pane::new(
 3921                self.weak_handle(),
 3922                self.project.clone(),
 3923                self.pane_history_timestamp.clone(),
 3924                None,
 3925                NewFile.boxed_clone(),
 3926                true,
 3927                window,
 3928                cx,
 3929            );
 3930            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 3931            pane
 3932        });
 3933        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 3934            .detach();
 3935        self.panes.push(pane.clone());
 3936
 3937        window.focus(&pane.focus_handle(cx), cx);
 3938
 3939        cx.emit(Event::PaneAdded(pane.clone()));
 3940        pane
 3941    }
 3942
 3943    pub fn add_item_to_center(
 3944        &mut self,
 3945        item: Box<dyn ItemHandle>,
 3946        window: &mut Window,
 3947        cx: &mut Context<Self>,
 3948    ) -> bool {
 3949        if let Some(center_pane) = self.last_active_center_pane.clone() {
 3950            if let Some(center_pane) = center_pane.upgrade() {
 3951                center_pane.update(cx, |pane, cx| {
 3952                    pane.add_item(item, true, true, None, window, cx)
 3953                });
 3954                true
 3955            } else {
 3956                false
 3957            }
 3958        } else {
 3959            false
 3960        }
 3961    }
 3962
 3963    pub fn add_item_to_active_pane(
 3964        &mut self,
 3965        item: Box<dyn ItemHandle>,
 3966        destination_index: Option<usize>,
 3967        focus_item: bool,
 3968        window: &mut Window,
 3969        cx: &mut App,
 3970    ) {
 3971        self.add_item(
 3972            self.active_pane.clone(),
 3973            item,
 3974            destination_index,
 3975            false,
 3976            focus_item,
 3977            window,
 3978            cx,
 3979        )
 3980    }
 3981
 3982    pub fn add_item(
 3983        &mut self,
 3984        pane: Entity<Pane>,
 3985        item: Box<dyn ItemHandle>,
 3986        destination_index: Option<usize>,
 3987        activate_pane: bool,
 3988        focus_item: bool,
 3989        window: &mut Window,
 3990        cx: &mut App,
 3991    ) {
 3992        pane.update(cx, |pane, cx| {
 3993            pane.add_item(
 3994                item,
 3995                activate_pane,
 3996                focus_item,
 3997                destination_index,
 3998                window,
 3999                cx,
 4000            )
 4001        });
 4002    }
 4003
 4004    pub fn split_item(
 4005        &mut self,
 4006        split_direction: SplitDirection,
 4007        item: Box<dyn ItemHandle>,
 4008        window: &mut Window,
 4009        cx: &mut Context<Self>,
 4010    ) {
 4011        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4012        self.add_item(new_pane, item, None, true, true, window, cx);
 4013    }
 4014
 4015    pub fn open_abs_path(
 4016        &mut self,
 4017        abs_path: PathBuf,
 4018        options: OpenOptions,
 4019        window: &mut Window,
 4020        cx: &mut Context<Self>,
 4021    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4022        cx.spawn_in(window, async move |workspace, cx| {
 4023            let open_paths_task_result = workspace
 4024                .update_in(cx, |workspace, window, cx| {
 4025                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4026                })
 4027                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4028                .await;
 4029            anyhow::ensure!(
 4030                open_paths_task_result.len() == 1,
 4031                "open abs path {abs_path:?} task returned incorrect number of results"
 4032            );
 4033            match open_paths_task_result
 4034                .into_iter()
 4035                .next()
 4036                .expect("ensured single task result")
 4037            {
 4038                Some(open_result) => {
 4039                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4040                }
 4041                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4042            }
 4043        })
 4044    }
 4045
 4046    pub fn split_abs_path(
 4047        &mut self,
 4048        abs_path: PathBuf,
 4049        visible: bool,
 4050        window: &mut Window,
 4051        cx: &mut Context<Self>,
 4052    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4053        let project_path_task =
 4054            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4055        cx.spawn_in(window, async move |this, cx| {
 4056            let (_, path) = project_path_task.await?;
 4057            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4058                .await
 4059        })
 4060    }
 4061
 4062    pub fn open_path(
 4063        &mut self,
 4064        path: impl Into<ProjectPath>,
 4065        pane: Option<WeakEntity<Pane>>,
 4066        focus_item: bool,
 4067        window: &mut Window,
 4068        cx: &mut App,
 4069    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4070        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4071    }
 4072
 4073    pub fn open_path_preview(
 4074        &mut self,
 4075        path: impl Into<ProjectPath>,
 4076        pane: Option<WeakEntity<Pane>>,
 4077        focus_item: bool,
 4078        allow_preview: bool,
 4079        activate: bool,
 4080        window: &mut Window,
 4081        cx: &mut App,
 4082    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4083        let pane = pane.unwrap_or_else(|| {
 4084            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4085                self.panes
 4086                    .first()
 4087                    .expect("There must be an active pane")
 4088                    .downgrade()
 4089            })
 4090        });
 4091
 4092        let project_path = path.into();
 4093        let task = self.load_path(project_path.clone(), window, cx);
 4094        window.spawn(cx, async move |cx| {
 4095            let (project_entry_id, build_item) = task.await?;
 4096
 4097            pane.update_in(cx, |pane, window, cx| {
 4098                pane.open_item(
 4099                    project_entry_id,
 4100                    project_path,
 4101                    focus_item,
 4102                    allow_preview,
 4103                    activate,
 4104                    None,
 4105                    window,
 4106                    cx,
 4107                    build_item,
 4108                )
 4109            })
 4110        })
 4111    }
 4112
 4113    pub fn split_path(
 4114        &mut self,
 4115        path: impl Into<ProjectPath>,
 4116        window: &mut Window,
 4117        cx: &mut Context<Self>,
 4118    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4119        self.split_path_preview(path, false, None, window, cx)
 4120    }
 4121
 4122    pub fn split_path_preview(
 4123        &mut self,
 4124        path: impl Into<ProjectPath>,
 4125        allow_preview: bool,
 4126        split_direction: Option<SplitDirection>,
 4127        window: &mut Window,
 4128        cx: &mut Context<Self>,
 4129    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4130        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4131            self.panes
 4132                .first()
 4133                .expect("There must be an active pane")
 4134                .downgrade()
 4135        });
 4136
 4137        if let Member::Pane(center_pane) = &self.center.root
 4138            && center_pane.read(cx).items_len() == 0
 4139        {
 4140            return self.open_path(path, Some(pane), true, window, cx);
 4141        }
 4142
 4143        let project_path = path.into();
 4144        let task = self.load_path(project_path.clone(), window, cx);
 4145        cx.spawn_in(window, async move |this, cx| {
 4146            let (project_entry_id, build_item) = task.await?;
 4147            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4148                let pane = pane.upgrade()?;
 4149                let new_pane = this.split_pane(
 4150                    pane,
 4151                    split_direction.unwrap_or(SplitDirection::Right),
 4152                    window,
 4153                    cx,
 4154                );
 4155                new_pane.update(cx, |new_pane, cx| {
 4156                    Some(new_pane.open_item(
 4157                        project_entry_id,
 4158                        project_path,
 4159                        true,
 4160                        allow_preview,
 4161                        true,
 4162                        None,
 4163                        window,
 4164                        cx,
 4165                        build_item,
 4166                    ))
 4167                })
 4168            })
 4169            .map(|option| option.context("pane was dropped"))?
 4170        })
 4171    }
 4172
 4173    fn load_path(
 4174        &mut self,
 4175        path: ProjectPath,
 4176        window: &mut Window,
 4177        cx: &mut App,
 4178    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4179        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4180        registry.open_path(self.project(), &path, window, cx)
 4181    }
 4182
 4183    pub fn find_project_item<T>(
 4184        &self,
 4185        pane: &Entity<Pane>,
 4186        project_item: &Entity<T::Item>,
 4187        cx: &App,
 4188    ) -> Option<Entity<T>>
 4189    where
 4190        T: ProjectItem,
 4191    {
 4192        use project::ProjectItem as _;
 4193        let project_item = project_item.read(cx);
 4194        let entry_id = project_item.entry_id(cx);
 4195        let project_path = project_item.project_path(cx);
 4196
 4197        let mut item = None;
 4198        if let Some(entry_id) = entry_id {
 4199            item = pane.read(cx).item_for_entry(entry_id, cx);
 4200        }
 4201        if item.is_none()
 4202            && let Some(project_path) = project_path
 4203        {
 4204            item = pane.read(cx).item_for_path(project_path, cx);
 4205        }
 4206
 4207        item.and_then(|item| item.downcast::<T>())
 4208    }
 4209
 4210    pub fn is_project_item_open<T>(
 4211        &self,
 4212        pane: &Entity<Pane>,
 4213        project_item: &Entity<T::Item>,
 4214        cx: &App,
 4215    ) -> bool
 4216    where
 4217        T: ProjectItem,
 4218    {
 4219        self.find_project_item::<T>(pane, project_item, cx)
 4220            .is_some()
 4221    }
 4222
 4223    pub fn open_project_item<T>(
 4224        &mut self,
 4225        pane: Entity<Pane>,
 4226        project_item: Entity<T::Item>,
 4227        activate_pane: bool,
 4228        focus_item: bool,
 4229        keep_old_preview: bool,
 4230        allow_new_preview: bool,
 4231        window: &mut Window,
 4232        cx: &mut Context<Self>,
 4233    ) -> Entity<T>
 4234    where
 4235        T: ProjectItem,
 4236    {
 4237        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4238
 4239        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4240            if !keep_old_preview
 4241                && let Some(old_id) = old_item_id
 4242                && old_id != item.item_id()
 4243            {
 4244                // switching to a different item, so unpreview old active item
 4245                pane.update(cx, |pane, _| {
 4246                    pane.unpreview_item_if_preview(old_id);
 4247                });
 4248            }
 4249
 4250            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4251            if !allow_new_preview {
 4252                pane.update(cx, |pane, _| {
 4253                    pane.unpreview_item_if_preview(item.item_id());
 4254                });
 4255            }
 4256            return item;
 4257        }
 4258
 4259        let item = pane.update(cx, |pane, cx| {
 4260            cx.new(|cx| {
 4261                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4262            })
 4263        });
 4264        let mut destination_index = None;
 4265        pane.update(cx, |pane, cx| {
 4266            if !keep_old_preview && let Some(old_id) = old_item_id {
 4267                pane.unpreview_item_if_preview(old_id);
 4268            }
 4269            if allow_new_preview {
 4270                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4271            }
 4272        });
 4273
 4274        self.add_item(
 4275            pane,
 4276            Box::new(item.clone()),
 4277            destination_index,
 4278            activate_pane,
 4279            focus_item,
 4280            window,
 4281            cx,
 4282        );
 4283        item
 4284    }
 4285
 4286    pub fn open_shared_screen(
 4287        &mut self,
 4288        peer_id: PeerId,
 4289        window: &mut Window,
 4290        cx: &mut Context<Self>,
 4291    ) {
 4292        if let Some(shared_screen) =
 4293            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4294        {
 4295            self.active_pane.update(cx, |pane, cx| {
 4296                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4297            });
 4298        }
 4299    }
 4300
 4301    pub fn activate_item(
 4302        &mut self,
 4303        item: &dyn ItemHandle,
 4304        activate_pane: bool,
 4305        focus_item: bool,
 4306        window: &mut Window,
 4307        cx: &mut App,
 4308    ) -> bool {
 4309        let result = self.panes.iter().find_map(|pane| {
 4310            pane.read(cx)
 4311                .index_for_item(item)
 4312                .map(|ix| (pane.clone(), ix))
 4313        });
 4314        if let Some((pane, ix)) = result {
 4315            pane.update(cx, |pane, cx| {
 4316                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4317            });
 4318            true
 4319        } else {
 4320            false
 4321        }
 4322    }
 4323
 4324    fn activate_pane_at_index(
 4325        &mut self,
 4326        action: &ActivatePane,
 4327        window: &mut Window,
 4328        cx: &mut Context<Self>,
 4329    ) {
 4330        let panes = self.center.panes();
 4331        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4332            window.focus(&pane.focus_handle(cx), cx);
 4333        } else {
 4334            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4335                .detach();
 4336        }
 4337    }
 4338
 4339    fn move_item_to_pane_at_index(
 4340        &mut self,
 4341        action: &MoveItemToPane,
 4342        window: &mut Window,
 4343        cx: &mut Context<Self>,
 4344    ) {
 4345        let panes = self.center.panes();
 4346        let destination = match panes.get(action.destination) {
 4347            Some(&destination) => destination.clone(),
 4348            None => {
 4349                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4350                    return;
 4351                }
 4352                let direction = SplitDirection::Right;
 4353                let split_off_pane = self
 4354                    .find_pane_in_direction(direction, cx)
 4355                    .unwrap_or_else(|| self.active_pane.clone());
 4356                let new_pane = self.add_pane(window, cx);
 4357                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4358                new_pane
 4359            }
 4360        };
 4361
 4362        if action.clone {
 4363            if self
 4364                .active_pane
 4365                .read(cx)
 4366                .active_item()
 4367                .is_some_and(|item| item.can_split(cx))
 4368            {
 4369                clone_active_item(
 4370                    self.database_id(),
 4371                    &self.active_pane,
 4372                    &destination,
 4373                    action.focus,
 4374                    window,
 4375                    cx,
 4376                );
 4377                return;
 4378            }
 4379        }
 4380        move_active_item(
 4381            &self.active_pane,
 4382            &destination,
 4383            action.focus,
 4384            true,
 4385            window,
 4386            cx,
 4387        )
 4388    }
 4389
 4390    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4391        let panes = self.center.panes();
 4392        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4393            let next_ix = (ix + 1) % panes.len();
 4394            let next_pane = panes[next_ix].clone();
 4395            window.focus(&next_pane.focus_handle(cx), cx);
 4396        }
 4397    }
 4398
 4399    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4400        let panes = self.center.panes();
 4401        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4402            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4403            let prev_pane = panes[prev_ix].clone();
 4404            window.focus(&prev_pane.focus_handle(cx), cx);
 4405        }
 4406    }
 4407
 4408    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4409        let last_pane = self.center.last_pane();
 4410        window.focus(&last_pane.focus_handle(cx), cx);
 4411    }
 4412
 4413    pub fn activate_pane_in_direction(
 4414        &mut self,
 4415        direction: SplitDirection,
 4416        window: &mut Window,
 4417        cx: &mut App,
 4418    ) {
 4419        use ActivateInDirectionTarget as Target;
 4420        enum Origin {
 4421            LeftDock,
 4422            RightDock,
 4423            BottomDock,
 4424            Center,
 4425        }
 4426
 4427        let origin: Origin = [
 4428            (&self.left_dock, Origin::LeftDock),
 4429            (&self.right_dock, Origin::RightDock),
 4430            (&self.bottom_dock, Origin::BottomDock),
 4431        ]
 4432        .into_iter()
 4433        .find_map(|(dock, origin)| {
 4434            if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4435                Some(origin)
 4436            } else {
 4437                None
 4438            }
 4439        })
 4440        .unwrap_or(Origin::Center);
 4441
 4442        let get_last_active_pane = || {
 4443            let pane = self
 4444                .last_active_center_pane
 4445                .clone()
 4446                .unwrap_or_else(|| {
 4447                    self.panes
 4448                        .first()
 4449                        .expect("There must be an active pane")
 4450                        .downgrade()
 4451                })
 4452                .upgrade()?;
 4453            (pane.read(cx).items_len() != 0).then_some(pane)
 4454        };
 4455
 4456        let try_dock =
 4457            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4458
 4459        let target = match (origin, direction) {
 4460            // We're in the center, so we first try to go to a different pane,
 4461            // otherwise try to go to a dock.
 4462            (Origin::Center, direction) => {
 4463                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4464                    Some(Target::Pane(pane))
 4465                } else {
 4466                    match direction {
 4467                        SplitDirection::Up => None,
 4468                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4469                        SplitDirection::Left => try_dock(&self.left_dock),
 4470                        SplitDirection::Right => try_dock(&self.right_dock),
 4471                    }
 4472                }
 4473            }
 4474
 4475            (Origin::LeftDock, SplitDirection::Right) => {
 4476                if let Some(last_active_pane) = get_last_active_pane() {
 4477                    Some(Target::Pane(last_active_pane))
 4478                } else {
 4479                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4480                }
 4481            }
 4482
 4483            (Origin::LeftDock, SplitDirection::Down)
 4484            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4485
 4486            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4487            (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
 4488            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4489
 4490            (Origin::RightDock, SplitDirection::Left) => {
 4491                if let Some(last_active_pane) = get_last_active_pane() {
 4492                    Some(Target::Pane(last_active_pane))
 4493                } else {
 4494                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 4495                }
 4496            }
 4497
 4498            _ => None,
 4499        };
 4500
 4501        match target {
 4502            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4503                let pane = pane.read(cx);
 4504                if let Some(item) = pane.active_item() {
 4505                    item.item_focus_handle(cx).focus(window, cx);
 4506                } else {
 4507                    log::error!(
 4508                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4509                    );
 4510                }
 4511            }
 4512            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4513                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4514                window.defer(cx, move |window, cx| {
 4515                    let dock = dock.read(cx);
 4516                    if let Some(panel) = dock.active_panel() {
 4517                        panel.panel_focus_handle(cx).focus(window, cx);
 4518                    } else {
 4519                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4520                    }
 4521                })
 4522            }
 4523            None => {}
 4524        }
 4525    }
 4526
 4527    pub fn move_item_to_pane_in_direction(
 4528        &mut self,
 4529        action: &MoveItemToPaneInDirection,
 4530        window: &mut Window,
 4531        cx: &mut Context<Self>,
 4532    ) {
 4533        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4534            Some(destination) => destination,
 4535            None => {
 4536                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4537                    return;
 4538                }
 4539                let new_pane = self.add_pane(window, cx);
 4540                self.center
 4541                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4542                new_pane
 4543            }
 4544        };
 4545
 4546        if action.clone {
 4547            if self
 4548                .active_pane
 4549                .read(cx)
 4550                .active_item()
 4551                .is_some_and(|item| item.can_split(cx))
 4552            {
 4553                clone_active_item(
 4554                    self.database_id(),
 4555                    &self.active_pane,
 4556                    &destination,
 4557                    action.focus,
 4558                    window,
 4559                    cx,
 4560                );
 4561                return;
 4562            }
 4563        }
 4564        move_active_item(
 4565            &self.active_pane,
 4566            &destination,
 4567            action.focus,
 4568            true,
 4569            window,
 4570            cx,
 4571        );
 4572    }
 4573
 4574    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4575        self.center.bounding_box_for_pane(pane)
 4576    }
 4577
 4578    pub fn find_pane_in_direction(
 4579        &mut self,
 4580        direction: SplitDirection,
 4581        cx: &App,
 4582    ) -> Option<Entity<Pane>> {
 4583        self.center
 4584            .find_pane_in_direction(&self.active_pane, direction, cx)
 4585            .cloned()
 4586    }
 4587
 4588    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4589        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4590            self.center.swap(&self.active_pane, &to, cx);
 4591            cx.notify();
 4592        }
 4593    }
 4594
 4595    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4596        if self
 4597            .center
 4598            .move_to_border(&self.active_pane, direction, cx)
 4599            .unwrap()
 4600        {
 4601            cx.notify();
 4602        }
 4603    }
 4604
 4605    pub fn resize_pane(
 4606        &mut self,
 4607        axis: gpui::Axis,
 4608        amount: Pixels,
 4609        window: &mut Window,
 4610        cx: &mut Context<Self>,
 4611    ) {
 4612        let docks = self.all_docks();
 4613        let active_dock = docks
 4614            .into_iter()
 4615            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4616
 4617        if let Some(dock) = active_dock {
 4618            let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
 4619                return;
 4620            };
 4621            match dock.read(cx).position() {
 4622                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4623                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4624                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4625            }
 4626        } else {
 4627            self.center
 4628                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 4629        }
 4630        cx.notify();
 4631    }
 4632
 4633    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 4634        self.center.reset_pane_sizes(cx);
 4635        cx.notify();
 4636    }
 4637
 4638    fn handle_pane_focused(
 4639        &mut self,
 4640        pane: Entity<Pane>,
 4641        window: &mut Window,
 4642        cx: &mut Context<Self>,
 4643    ) {
 4644        // This is explicitly hoisted out of the following check for pane identity as
 4645        // terminal panel panes are not registered as a center panes.
 4646        self.status_bar.update(cx, |status_bar, cx| {
 4647            status_bar.set_active_pane(&pane, window, cx);
 4648        });
 4649        if self.active_pane != pane {
 4650            self.set_active_pane(&pane, window, cx);
 4651        }
 4652
 4653        if self.last_active_center_pane.is_none() {
 4654            self.last_active_center_pane = Some(pane.downgrade());
 4655        }
 4656
 4657        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 4658        // This prevents the dock from closing when focus events fire during window activation.
 4659        // We also preserve any dock whose active panel itself has focus — this covers
 4660        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 4661        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 4662            let dock_read = dock.read(cx);
 4663            if let Some(panel) = dock_read.active_panel() {
 4664                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 4665                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 4666                {
 4667                    return Some(dock_read.position());
 4668                }
 4669            }
 4670            None
 4671        });
 4672
 4673        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 4674        if pane.read(cx).is_zoomed() {
 4675            self.zoomed = Some(pane.downgrade().into());
 4676        } else {
 4677            self.zoomed = None;
 4678        }
 4679        self.zoomed_position = None;
 4680        cx.emit(Event::ZoomChanged);
 4681        self.update_active_view_for_followers(window, cx);
 4682        pane.update(cx, |pane, _| {
 4683            pane.track_alternate_file_items();
 4684        });
 4685
 4686        cx.notify();
 4687    }
 4688
 4689    fn set_active_pane(
 4690        &mut self,
 4691        pane: &Entity<Pane>,
 4692        window: &mut Window,
 4693        cx: &mut Context<Self>,
 4694    ) {
 4695        self.active_pane = pane.clone();
 4696        self.active_item_path_changed(true, window, cx);
 4697        self.last_active_center_pane = Some(pane.downgrade());
 4698    }
 4699
 4700    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4701        self.update_active_view_for_followers(window, cx);
 4702    }
 4703
 4704    fn handle_pane_event(
 4705        &mut self,
 4706        pane: &Entity<Pane>,
 4707        event: &pane::Event,
 4708        window: &mut Window,
 4709        cx: &mut Context<Self>,
 4710    ) {
 4711        let mut serialize_workspace = true;
 4712        match event {
 4713            pane::Event::AddItem { item } => {
 4714                item.added_to_pane(self, pane.clone(), window, cx);
 4715                cx.emit(Event::ItemAdded {
 4716                    item: item.boxed_clone(),
 4717                });
 4718            }
 4719            pane::Event::Split { direction, mode } => {
 4720                match mode {
 4721                    SplitMode::ClonePane => {
 4722                        self.split_and_clone(pane.clone(), *direction, window, cx)
 4723                            .detach();
 4724                    }
 4725                    SplitMode::EmptyPane => {
 4726                        self.split_pane(pane.clone(), *direction, window, cx);
 4727                    }
 4728                    SplitMode::MovePane => {
 4729                        self.split_and_move(pane.clone(), *direction, window, cx);
 4730                    }
 4731                };
 4732            }
 4733            pane::Event::JoinIntoNext => {
 4734                self.join_pane_into_next(pane.clone(), window, cx);
 4735            }
 4736            pane::Event::JoinAll => {
 4737                self.join_all_panes(window, cx);
 4738            }
 4739            pane::Event::Remove { focus_on_pane } => {
 4740                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 4741            }
 4742            pane::Event::ActivateItem {
 4743                local,
 4744                focus_changed,
 4745            } => {
 4746                window.invalidate_character_coordinates();
 4747
 4748                pane.update(cx, |pane, _| {
 4749                    pane.track_alternate_file_items();
 4750                });
 4751                if *local {
 4752                    self.unfollow_in_pane(pane, window, cx);
 4753                }
 4754                serialize_workspace = *focus_changed || pane != self.active_pane();
 4755                if pane == self.active_pane() {
 4756                    self.active_item_path_changed(*focus_changed, window, cx);
 4757                    self.update_active_view_for_followers(window, cx);
 4758                } else if *local {
 4759                    self.set_active_pane(pane, window, cx);
 4760                }
 4761            }
 4762            pane::Event::UserSavedItem { item, save_intent } => {
 4763                cx.emit(Event::UserSavedItem {
 4764                    pane: pane.downgrade(),
 4765                    item: item.boxed_clone(),
 4766                    save_intent: *save_intent,
 4767                });
 4768                serialize_workspace = false;
 4769            }
 4770            pane::Event::ChangeItemTitle => {
 4771                if *pane == self.active_pane {
 4772                    self.active_item_path_changed(false, window, cx);
 4773                }
 4774                serialize_workspace = false;
 4775            }
 4776            pane::Event::RemovedItem { item } => {
 4777                cx.emit(Event::ActiveItemChanged);
 4778                self.update_window_edited(window, cx);
 4779                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 4780                    && entry.get().entity_id() == pane.entity_id()
 4781                {
 4782                    entry.remove();
 4783                }
 4784                cx.emit(Event::ItemRemoved {
 4785                    item_id: item.item_id(),
 4786                });
 4787            }
 4788            pane::Event::Focus => {
 4789                window.invalidate_character_coordinates();
 4790                self.handle_pane_focused(pane.clone(), window, cx);
 4791            }
 4792            pane::Event::ZoomIn => {
 4793                if *pane == self.active_pane {
 4794                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 4795                    if pane.read(cx).has_focus(window, cx) {
 4796                        self.zoomed = Some(pane.downgrade().into());
 4797                        self.zoomed_position = None;
 4798                        cx.emit(Event::ZoomChanged);
 4799                    }
 4800                    cx.notify();
 4801                }
 4802            }
 4803            pane::Event::ZoomOut => {
 4804                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4805                if self.zoomed_position.is_none() {
 4806                    self.zoomed = None;
 4807                    cx.emit(Event::ZoomChanged);
 4808                }
 4809                cx.notify();
 4810            }
 4811            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 4812        }
 4813
 4814        if serialize_workspace {
 4815            self.serialize_workspace(window, cx);
 4816        }
 4817    }
 4818
 4819    pub fn unfollow_in_pane(
 4820        &mut self,
 4821        pane: &Entity<Pane>,
 4822        window: &mut Window,
 4823        cx: &mut Context<Workspace>,
 4824    ) -> Option<CollaboratorId> {
 4825        let leader_id = self.leader_for_pane(pane)?;
 4826        self.unfollow(leader_id, window, cx);
 4827        Some(leader_id)
 4828    }
 4829
 4830    pub fn split_pane(
 4831        &mut self,
 4832        pane_to_split: Entity<Pane>,
 4833        split_direction: SplitDirection,
 4834        window: &mut Window,
 4835        cx: &mut Context<Self>,
 4836    ) -> Entity<Pane> {
 4837        let new_pane = self.add_pane(window, cx);
 4838        self.center
 4839            .split(&pane_to_split, &new_pane, split_direction, cx);
 4840        cx.notify();
 4841        new_pane
 4842    }
 4843
 4844    pub fn split_and_move(
 4845        &mut self,
 4846        pane: Entity<Pane>,
 4847        direction: SplitDirection,
 4848        window: &mut Window,
 4849        cx: &mut Context<Self>,
 4850    ) {
 4851        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 4852            return;
 4853        };
 4854        let new_pane = self.add_pane(window, cx);
 4855        new_pane.update(cx, |pane, cx| {
 4856            pane.add_item(item, true, true, None, window, cx)
 4857        });
 4858        self.center.split(&pane, &new_pane, direction, cx);
 4859        cx.notify();
 4860    }
 4861
 4862    pub fn split_and_clone(
 4863        &mut self,
 4864        pane: Entity<Pane>,
 4865        direction: SplitDirection,
 4866        window: &mut Window,
 4867        cx: &mut Context<Self>,
 4868    ) -> Task<Option<Entity<Pane>>> {
 4869        let Some(item) = pane.read(cx).active_item() else {
 4870            return Task::ready(None);
 4871        };
 4872        if !item.can_split(cx) {
 4873            return Task::ready(None);
 4874        }
 4875        let task = item.clone_on_split(self.database_id(), window, cx);
 4876        cx.spawn_in(window, async move |this, cx| {
 4877            if let Some(clone) = task.await {
 4878                this.update_in(cx, |this, window, cx| {
 4879                    let new_pane = this.add_pane(window, cx);
 4880                    let nav_history = pane.read(cx).fork_nav_history();
 4881                    new_pane.update(cx, |pane, cx| {
 4882                        pane.set_nav_history(nav_history, cx);
 4883                        pane.add_item(clone, true, true, None, window, cx)
 4884                    });
 4885                    this.center.split(&pane, &new_pane, direction, cx);
 4886                    cx.notify();
 4887                    new_pane
 4888                })
 4889                .ok()
 4890            } else {
 4891                None
 4892            }
 4893        })
 4894    }
 4895
 4896    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4897        let active_item = self.active_pane.read(cx).active_item();
 4898        for pane in &self.panes {
 4899            join_pane_into_active(&self.active_pane, pane, window, cx);
 4900        }
 4901        if let Some(active_item) = active_item {
 4902            self.activate_item(active_item.as_ref(), true, true, window, cx);
 4903        }
 4904        cx.notify();
 4905    }
 4906
 4907    pub fn join_pane_into_next(
 4908        &mut self,
 4909        pane: Entity<Pane>,
 4910        window: &mut Window,
 4911        cx: &mut Context<Self>,
 4912    ) {
 4913        let next_pane = self
 4914            .find_pane_in_direction(SplitDirection::Right, cx)
 4915            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 4916            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 4917            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 4918        let Some(next_pane) = next_pane else {
 4919            return;
 4920        };
 4921        move_all_items(&pane, &next_pane, window, cx);
 4922        cx.notify();
 4923    }
 4924
 4925    fn remove_pane(
 4926        &mut self,
 4927        pane: Entity<Pane>,
 4928        focus_on: Option<Entity<Pane>>,
 4929        window: &mut Window,
 4930        cx: &mut Context<Self>,
 4931    ) {
 4932        if self.center.remove(&pane, cx).unwrap() {
 4933            self.force_remove_pane(&pane, &focus_on, window, cx);
 4934            self.unfollow_in_pane(&pane, window, cx);
 4935            self.last_leaders_by_pane.remove(&pane.downgrade());
 4936            for removed_item in pane.read(cx).items() {
 4937                self.panes_by_item.remove(&removed_item.item_id());
 4938            }
 4939
 4940            cx.notify();
 4941        } else {
 4942            self.active_item_path_changed(true, window, cx);
 4943        }
 4944        cx.emit(Event::PaneRemoved);
 4945    }
 4946
 4947    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 4948        &mut self.panes
 4949    }
 4950
 4951    pub fn panes(&self) -> &[Entity<Pane>] {
 4952        &self.panes
 4953    }
 4954
 4955    pub fn active_pane(&self) -> &Entity<Pane> {
 4956        &self.active_pane
 4957    }
 4958
 4959    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 4960        for dock in self.all_docks() {
 4961            if dock.focus_handle(cx).contains_focused(window, cx)
 4962                && let Some(pane) = dock
 4963                    .read(cx)
 4964                    .active_panel()
 4965                    .and_then(|panel| panel.pane(cx))
 4966            {
 4967                return pane;
 4968            }
 4969        }
 4970        self.active_pane().clone()
 4971    }
 4972
 4973    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4974        self.find_pane_in_direction(SplitDirection::Right, cx)
 4975            .unwrap_or_else(|| {
 4976                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4977            })
 4978    }
 4979
 4980    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 4981        self.pane_for_item_id(handle.item_id())
 4982    }
 4983
 4984    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 4985        let weak_pane = self.panes_by_item.get(&item_id)?;
 4986        weak_pane.upgrade()
 4987    }
 4988
 4989    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 4990        self.panes
 4991            .iter()
 4992            .find(|pane| pane.entity_id() == entity_id)
 4993            .cloned()
 4994    }
 4995
 4996    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 4997        self.follower_states.retain(|leader_id, state| {
 4998            if *leader_id == CollaboratorId::PeerId(peer_id) {
 4999                for item in state.items_by_leader_view_id.values() {
 5000                    item.view.set_leader_id(None, window, cx);
 5001                }
 5002                false
 5003            } else {
 5004                true
 5005            }
 5006        });
 5007        cx.notify();
 5008    }
 5009
 5010    pub fn start_following(
 5011        &mut self,
 5012        leader_id: impl Into<CollaboratorId>,
 5013        window: &mut Window,
 5014        cx: &mut Context<Self>,
 5015    ) -> Option<Task<Result<()>>> {
 5016        let leader_id = leader_id.into();
 5017        let pane = self.active_pane().clone();
 5018
 5019        self.last_leaders_by_pane
 5020            .insert(pane.downgrade(), leader_id);
 5021        self.unfollow(leader_id, window, cx);
 5022        self.unfollow_in_pane(&pane, window, cx);
 5023        self.follower_states.insert(
 5024            leader_id,
 5025            FollowerState {
 5026                center_pane: pane.clone(),
 5027                dock_pane: None,
 5028                active_view_id: None,
 5029                items_by_leader_view_id: Default::default(),
 5030            },
 5031        );
 5032        cx.notify();
 5033
 5034        match leader_id {
 5035            CollaboratorId::PeerId(leader_peer_id) => {
 5036                let room_id = self.active_call()?.room_id(cx)?;
 5037                let project_id = self.project.read(cx).remote_id();
 5038                let request = self.app_state.client.request(proto::Follow {
 5039                    room_id,
 5040                    project_id,
 5041                    leader_id: Some(leader_peer_id),
 5042                });
 5043
 5044                Some(cx.spawn_in(window, async move |this, cx| {
 5045                    let response = request.await?;
 5046                    this.update(cx, |this, _| {
 5047                        let state = this
 5048                            .follower_states
 5049                            .get_mut(&leader_id)
 5050                            .context("following interrupted")?;
 5051                        state.active_view_id = response
 5052                            .active_view
 5053                            .as_ref()
 5054                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5055                        anyhow::Ok(())
 5056                    })??;
 5057                    if let Some(view) = response.active_view {
 5058                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5059                    }
 5060                    this.update_in(cx, |this, window, cx| {
 5061                        this.leader_updated(leader_id, window, cx)
 5062                    })?;
 5063                    Ok(())
 5064                }))
 5065            }
 5066            CollaboratorId::Agent => {
 5067                self.leader_updated(leader_id, window, cx)?;
 5068                Some(Task::ready(Ok(())))
 5069            }
 5070        }
 5071    }
 5072
 5073    pub fn follow_next_collaborator(
 5074        &mut self,
 5075        _: &FollowNextCollaborator,
 5076        window: &mut Window,
 5077        cx: &mut Context<Self>,
 5078    ) {
 5079        let collaborators = self.project.read(cx).collaborators();
 5080        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5081            let mut collaborators = collaborators.keys().copied();
 5082            for peer_id in collaborators.by_ref() {
 5083                if CollaboratorId::PeerId(peer_id) == leader_id {
 5084                    break;
 5085                }
 5086            }
 5087            collaborators.next().map(CollaboratorId::PeerId)
 5088        } else if let Some(last_leader_id) =
 5089            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5090        {
 5091            match last_leader_id {
 5092                CollaboratorId::PeerId(peer_id) => {
 5093                    if collaborators.contains_key(peer_id) {
 5094                        Some(*last_leader_id)
 5095                    } else {
 5096                        None
 5097                    }
 5098                }
 5099                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5100            }
 5101        } else {
 5102            None
 5103        };
 5104
 5105        let pane = self.active_pane.clone();
 5106        let Some(leader_id) = next_leader_id.or_else(|| {
 5107            Some(CollaboratorId::PeerId(
 5108                collaborators.keys().copied().next()?,
 5109            ))
 5110        }) else {
 5111            return;
 5112        };
 5113        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5114            return;
 5115        }
 5116        if let Some(task) = self.start_following(leader_id, window, cx) {
 5117            task.detach_and_log_err(cx)
 5118        }
 5119    }
 5120
 5121    pub fn follow(
 5122        &mut self,
 5123        leader_id: impl Into<CollaboratorId>,
 5124        window: &mut Window,
 5125        cx: &mut Context<Self>,
 5126    ) {
 5127        let leader_id = leader_id.into();
 5128
 5129        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5130            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5131                return;
 5132            };
 5133            let Some(remote_participant) =
 5134                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5135            else {
 5136                return;
 5137            };
 5138
 5139            let project = self.project.read(cx);
 5140
 5141            let other_project_id = match remote_participant.location {
 5142                ParticipantLocation::External => None,
 5143                ParticipantLocation::UnsharedProject => None,
 5144                ParticipantLocation::SharedProject { project_id } => {
 5145                    if Some(project_id) == project.remote_id() {
 5146                        None
 5147                    } else {
 5148                        Some(project_id)
 5149                    }
 5150                }
 5151            };
 5152
 5153            // if they are active in another project, follow there.
 5154            if let Some(project_id) = other_project_id {
 5155                let app_state = self.app_state.clone();
 5156                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5157                    .detach_and_log_err(cx);
 5158            }
 5159        }
 5160
 5161        // if you're already following, find the right pane and focus it.
 5162        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5163            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5164
 5165            return;
 5166        }
 5167
 5168        // Otherwise, follow.
 5169        if let Some(task) = self.start_following(leader_id, window, cx) {
 5170            task.detach_and_log_err(cx)
 5171        }
 5172    }
 5173
 5174    pub fn unfollow(
 5175        &mut self,
 5176        leader_id: impl Into<CollaboratorId>,
 5177        window: &mut Window,
 5178        cx: &mut Context<Self>,
 5179    ) -> Option<()> {
 5180        cx.notify();
 5181
 5182        let leader_id = leader_id.into();
 5183        let state = self.follower_states.remove(&leader_id)?;
 5184        for (_, item) in state.items_by_leader_view_id {
 5185            item.view.set_leader_id(None, window, cx);
 5186        }
 5187
 5188        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5189            let project_id = self.project.read(cx).remote_id();
 5190            let room_id = self.active_call()?.room_id(cx)?;
 5191            self.app_state
 5192                .client
 5193                .send(proto::Unfollow {
 5194                    room_id,
 5195                    project_id,
 5196                    leader_id: Some(leader_peer_id),
 5197                })
 5198                .log_err();
 5199        }
 5200
 5201        Some(())
 5202    }
 5203
 5204    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5205        self.follower_states.contains_key(&id.into())
 5206    }
 5207
 5208    fn active_item_path_changed(
 5209        &mut self,
 5210        focus_changed: bool,
 5211        window: &mut Window,
 5212        cx: &mut Context<Self>,
 5213    ) {
 5214        cx.emit(Event::ActiveItemChanged);
 5215        let active_entry = self.active_project_path(cx);
 5216        self.project.update(cx, |project, cx| {
 5217            project.set_active_path(active_entry.clone(), cx)
 5218        });
 5219
 5220        if focus_changed && let Some(project_path) = &active_entry {
 5221            let git_store_entity = self.project.read(cx).git_store().clone();
 5222            git_store_entity.update(cx, |git_store, cx| {
 5223                git_store.set_active_repo_for_path(project_path, cx);
 5224            });
 5225        }
 5226
 5227        self.update_window_title(window, cx);
 5228    }
 5229
 5230    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5231        let project = self.project().read(cx);
 5232        let mut title = String::new();
 5233
 5234        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5235            let name = {
 5236                let settings_location = SettingsLocation {
 5237                    worktree_id: worktree.read(cx).id(),
 5238                    path: RelPath::empty(),
 5239                };
 5240
 5241                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5242                match &settings.project_name {
 5243                    Some(name) => name.as_str(),
 5244                    None => worktree.read(cx).root_name_str(),
 5245                }
 5246            };
 5247            if i > 0 {
 5248                title.push_str(", ");
 5249            }
 5250            title.push_str(name);
 5251        }
 5252
 5253        if title.is_empty() {
 5254            title = "empty project".to_string();
 5255        }
 5256
 5257        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5258            let filename = path.path.file_name().or_else(|| {
 5259                Some(
 5260                    project
 5261                        .worktree_for_id(path.worktree_id, cx)?
 5262                        .read(cx)
 5263                        .root_name_str(),
 5264                )
 5265            });
 5266
 5267            if let Some(filename) = filename {
 5268                title.push_str("");
 5269                title.push_str(filename.as_ref());
 5270            }
 5271        }
 5272
 5273        if project.is_via_collab() {
 5274            title.push_str("");
 5275        } else if project.is_shared() {
 5276            title.push_str("");
 5277        }
 5278
 5279        if let Some(last_title) = self.last_window_title.as_ref()
 5280            && &title == last_title
 5281        {
 5282            return;
 5283        }
 5284        window.set_window_title(&title);
 5285        SystemWindowTabController::update_tab_title(
 5286            cx,
 5287            window.window_handle().window_id(),
 5288            SharedString::from(&title),
 5289        );
 5290        self.last_window_title = Some(title);
 5291    }
 5292
 5293    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5294        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5295        if is_edited != self.window_edited {
 5296            self.window_edited = is_edited;
 5297            window.set_window_edited(self.window_edited)
 5298        }
 5299    }
 5300
 5301    fn update_item_dirty_state(
 5302        &mut self,
 5303        item: &dyn ItemHandle,
 5304        window: &mut Window,
 5305        cx: &mut App,
 5306    ) {
 5307        let is_dirty = item.is_dirty(cx);
 5308        let item_id = item.item_id();
 5309        let was_dirty = self.dirty_items.contains_key(&item_id);
 5310        if is_dirty == was_dirty {
 5311            return;
 5312        }
 5313        if was_dirty {
 5314            self.dirty_items.remove(&item_id);
 5315            self.update_window_edited(window, cx);
 5316            return;
 5317        }
 5318
 5319        let workspace = self.weak_handle();
 5320        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5321            return;
 5322        };
 5323        let on_release_callback = Box::new(move |cx: &mut App| {
 5324            window_handle
 5325                .update(cx, |_, window, cx| {
 5326                    workspace
 5327                        .update(cx, |workspace, cx| {
 5328                            workspace.dirty_items.remove(&item_id);
 5329                            workspace.update_window_edited(window, cx)
 5330                        })
 5331                        .ok();
 5332                })
 5333                .ok();
 5334        });
 5335
 5336        let s = item.on_release(cx, on_release_callback);
 5337        self.dirty_items.insert(item_id, s);
 5338        self.update_window_edited(window, cx);
 5339    }
 5340
 5341    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5342        if self.notifications.is_empty() {
 5343            None
 5344        } else {
 5345            Some(
 5346                div()
 5347                    .absolute()
 5348                    .right_3()
 5349                    .bottom_3()
 5350                    .w_112()
 5351                    .h_full()
 5352                    .flex()
 5353                    .flex_col()
 5354                    .justify_end()
 5355                    .gap_2()
 5356                    .children(
 5357                        self.notifications
 5358                            .iter()
 5359                            .map(|(_, notification)| notification.clone().into_any()),
 5360                    ),
 5361            )
 5362        }
 5363    }
 5364
 5365    // RPC handlers
 5366
 5367    fn active_view_for_follower(
 5368        &self,
 5369        follower_project_id: Option<u64>,
 5370        window: &mut Window,
 5371        cx: &mut Context<Self>,
 5372    ) -> Option<proto::View> {
 5373        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5374        let item = item?;
 5375        let leader_id = self
 5376            .pane_for(&*item)
 5377            .and_then(|pane| self.leader_for_pane(&pane));
 5378        let leader_peer_id = match leader_id {
 5379            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5380            Some(CollaboratorId::Agent) | None => None,
 5381        };
 5382
 5383        let item_handle = item.to_followable_item_handle(cx)?;
 5384        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5385        let variant = item_handle.to_state_proto(window, cx)?;
 5386
 5387        if item_handle.is_project_item(window, cx)
 5388            && (follower_project_id.is_none()
 5389                || follower_project_id != self.project.read(cx).remote_id())
 5390        {
 5391            return None;
 5392        }
 5393
 5394        Some(proto::View {
 5395            id: id.to_proto(),
 5396            leader_id: leader_peer_id,
 5397            variant: Some(variant),
 5398            panel_id: panel_id.map(|id| id as i32),
 5399        })
 5400    }
 5401
 5402    fn handle_follow(
 5403        &mut self,
 5404        follower_project_id: Option<u64>,
 5405        window: &mut Window,
 5406        cx: &mut Context<Self>,
 5407    ) -> proto::FollowResponse {
 5408        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5409
 5410        cx.notify();
 5411        proto::FollowResponse {
 5412            views: active_view.iter().cloned().collect(),
 5413            active_view,
 5414        }
 5415    }
 5416
 5417    fn handle_update_followers(
 5418        &mut self,
 5419        leader_id: PeerId,
 5420        message: proto::UpdateFollowers,
 5421        _window: &mut Window,
 5422        _cx: &mut Context<Self>,
 5423    ) {
 5424        self.leader_updates_tx
 5425            .unbounded_send((leader_id, message))
 5426            .ok();
 5427    }
 5428
 5429    async fn process_leader_update(
 5430        this: &WeakEntity<Self>,
 5431        leader_id: PeerId,
 5432        update: proto::UpdateFollowers,
 5433        cx: &mut AsyncWindowContext,
 5434    ) -> Result<()> {
 5435        match update.variant.context("invalid update")? {
 5436            proto::update_followers::Variant::CreateView(view) => {
 5437                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5438                let should_add_view = this.update(cx, |this, _| {
 5439                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5440                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5441                    } else {
 5442                        anyhow::Ok(false)
 5443                    }
 5444                })??;
 5445
 5446                if should_add_view {
 5447                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5448                }
 5449            }
 5450            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5451                let should_add_view = this.update(cx, |this, _| {
 5452                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5453                        state.active_view_id = update_active_view
 5454                            .view
 5455                            .as_ref()
 5456                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5457
 5458                        if state.active_view_id.is_some_and(|view_id| {
 5459                            !state.items_by_leader_view_id.contains_key(&view_id)
 5460                        }) {
 5461                            anyhow::Ok(true)
 5462                        } else {
 5463                            anyhow::Ok(false)
 5464                        }
 5465                    } else {
 5466                        anyhow::Ok(false)
 5467                    }
 5468                })??;
 5469
 5470                if should_add_view && let Some(view) = update_active_view.view {
 5471                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5472                }
 5473            }
 5474            proto::update_followers::Variant::UpdateView(update_view) => {
 5475                let variant = update_view.variant.context("missing update view variant")?;
 5476                let id = update_view.id.context("missing update view id")?;
 5477                let mut tasks = Vec::new();
 5478                this.update_in(cx, |this, window, cx| {
 5479                    let project = this.project.clone();
 5480                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5481                        let view_id = ViewId::from_proto(id.clone())?;
 5482                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5483                            tasks.push(item.view.apply_update_proto(
 5484                                &project,
 5485                                variant.clone(),
 5486                                window,
 5487                                cx,
 5488                            ));
 5489                        }
 5490                    }
 5491                    anyhow::Ok(())
 5492                })??;
 5493                try_join_all(tasks).await.log_err();
 5494            }
 5495        }
 5496        this.update_in(cx, |this, window, cx| {
 5497            this.leader_updated(leader_id, window, cx)
 5498        })?;
 5499        Ok(())
 5500    }
 5501
 5502    async fn add_view_from_leader(
 5503        this: WeakEntity<Self>,
 5504        leader_id: PeerId,
 5505        view: &proto::View,
 5506        cx: &mut AsyncWindowContext,
 5507    ) -> Result<()> {
 5508        let this = this.upgrade().context("workspace dropped")?;
 5509
 5510        let Some(id) = view.id.clone() else {
 5511            anyhow::bail!("no id for view");
 5512        };
 5513        let id = ViewId::from_proto(id)?;
 5514        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5515
 5516        let pane = this.update(cx, |this, _cx| {
 5517            let state = this
 5518                .follower_states
 5519                .get(&leader_id.into())
 5520                .context("stopped following")?;
 5521            anyhow::Ok(state.pane().clone())
 5522        })?;
 5523        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5524            let client = this.read(cx).client().clone();
 5525            pane.items().find_map(|item| {
 5526                let item = item.to_followable_item_handle(cx)?;
 5527                if item.remote_id(&client, window, cx) == Some(id) {
 5528                    Some(item)
 5529                } else {
 5530                    None
 5531                }
 5532            })
 5533        })?;
 5534        let item = if let Some(existing_item) = existing_item {
 5535            existing_item
 5536        } else {
 5537            let variant = view.variant.clone();
 5538            anyhow::ensure!(variant.is_some(), "missing view variant");
 5539
 5540            let task = cx.update(|window, cx| {
 5541                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5542            })?;
 5543
 5544            let Some(task) = task else {
 5545                anyhow::bail!(
 5546                    "failed to construct view from leader (maybe from a different version of zed?)"
 5547                );
 5548            };
 5549
 5550            let mut new_item = task.await?;
 5551            pane.update_in(cx, |pane, window, cx| {
 5552                let mut item_to_remove = None;
 5553                for (ix, item) in pane.items().enumerate() {
 5554                    if let Some(item) = item.to_followable_item_handle(cx) {
 5555                        match new_item.dedup(item.as_ref(), window, cx) {
 5556                            Some(item::Dedup::KeepExisting) => {
 5557                                new_item =
 5558                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5559                                break;
 5560                            }
 5561                            Some(item::Dedup::ReplaceExisting) => {
 5562                                item_to_remove = Some((ix, item.item_id()));
 5563                                break;
 5564                            }
 5565                            None => {}
 5566                        }
 5567                    }
 5568                }
 5569
 5570                if let Some((ix, id)) = item_to_remove {
 5571                    pane.remove_item(id, false, false, window, cx);
 5572                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5573                }
 5574            })?;
 5575
 5576            new_item
 5577        };
 5578
 5579        this.update_in(cx, |this, window, cx| {
 5580            let state = this.follower_states.get_mut(&leader_id.into())?;
 5581            item.set_leader_id(Some(leader_id.into()), window, cx);
 5582            state.items_by_leader_view_id.insert(
 5583                id,
 5584                FollowerView {
 5585                    view: item,
 5586                    location: panel_id,
 5587                },
 5588            );
 5589
 5590            Some(())
 5591        })
 5592        .context("no follower state")?;
 5593
 5594        Ok(())
 5595    }
 5596
 5597    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5598        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5599            return;
 5600        };
 5601
 5602        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5603            let buffer_entity_id = agent_location.buffer.entity_id();
 5604            let view_id = ViewId {
 5605                creator: CollaboratorId::Agent,
 5606                id: buffer_entity_id.as_u64(),
 5607            };
 5608            follower_state.active_view_id = Some(view_id);
 5609
 5610            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5611                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5612                hash_map::Entry::Vacant(entry) => {
 5613                    let existing_view =
 5614                        follower_state
 5615                            .center_pane
 5616                            .read(cx)
 5617                            .items()
 5618                            .find_map(|item| {
 5619                                let item = item.to_followable_item_handle(cx)?;
 5620                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5621                                    && item.project_item_model_ids(cx).as_slice()
 5622                                        == [buffer_entity_id]
 5623                                {
 5624                                    Some(item)
 5625                                } else {
 5626                                    None
 5627                                }
 5628                            });
 5629                    let view = existing_view.or_else(|| {
 5630                        agent_location.buffer.upgrade().and_then(|buffer| {
 5631                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 5632                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 5633                            })?
 5634                            .to_followable_item_handle(cx)
 5635                        })
 5636                    });
 5637
 5638                    view.map(|view| {
 5639                        entry.insert(FollowerView {
 5640                            view,
 5641                            location: None,
 5642                        })
 5643                    })
 5644                }
 5645            };
 5646
 5647            if let Some(item) = item {
 5648                item.view
 5649                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 5650                item.view
 5651                    .update_agent_location(agent_location.position, window, cx);
 5652            }
 5653        } else {
 5654            follower_state.active_view_id = None;
 5655        }
 5656
 5657        self.leader_updated(CollaboratorId::Agent, window, cx);
 5658    }
 5659
 5660    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 5661        let mut is_project_item = true;
 5662        let mut update = proto::UpdateActiveView::default();
 5663        if window.is_window_active() {
 5664            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 5665
 5666            if let Some(item) = active_item
 5667                && item.item_focus_handle(cx).contains_focused(window, cx)
 5668            {
 5669                let leader_id = self
 5670                    .pane_for(&*item)
 5671                    .and_then(|pane| self.leader_for_pane(&pane));
 5672                let leader_peer_id = match leader_id {
 5673                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5674                    Some(CollaboratorId::Agent) | None => None,
 5675                };
 5676
 5677                if let Some(item) = item.to_followable_item_handle(cx) {
 5678                    let id = item
 5679                        .remote_id(&self.app_state.client, window, cx)
 5680                        .map(|id| id.to_proto());
 5681
 5682                    if let Some(id) = id
 5683                        && let Some(variant) = item.to_state_proto(window, cx)
 5684                    {
 5685                        let view = Some(proto::View {
 5686                            id,
 5687                            leader_id: leader_peer_id,
 5688                            variant: Some(variant),
 5689                            panel_id: panel_id.map(|id| id as i32),
 5690                        });
 5691
 5692                        is_project_item = item.is_project_item(window, cx);
 5693                        update = proto::UpdateActiveView { view };
 5694                    };
 5695                }
 5696            }
 5697        }
 5698
 5699        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 5700        if active_view_id != self.last_active_view_id.as_ref() {
 5701            self.last_active_view_id = active_view_id.cloned();
 5702            self.update_followers(
 5703                is_project_item,
 5704                proto::update_followers::Variant::UpdateActiveView(update),
 5705                window,
 5706                cx,
 5707            );
 5708        }
 5709    }
 5710
 5711    fn active_item_for_followers(
 5712        &self,
 5713        window: &mut Window,
 5714        cx: &mut App,
 5715    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 5716        let mut active_item = None;
 5717        let mut panel_id = None;
 5718        for dock in self.all_docks() {
 5719            if dock.focus_handle(cx).contains_focused(window, cx)
 5720                && let Some(panel) = dock.read(cx).active_panel()
 5721                && let Some(pane) = panel.pane(cx)
 5722                && let Some(item) = pane.read(cx).active_item()
 5723            {
 5724                active_item = Some(item);
 5725                panel_id = panel.remote_id();
 5726                break;
 5727            }
 5728        }
 5729
 5730        if active_item.is_none() {
 5731            active_item = self.active_pane().read(cx).active_item();
 5732        }
 5733        (active_item, panel_id)
 5734    }
 5735
 5736    fn update_followers(
 5737        &self,
 5738        project_only: bool,
 5739        update: proto::update_followers::Variant,
 5740        _: &mut Window,
 5741        cx: &mut App,
 5742    ) -> Option<()> {
 5743        // If this update only applies to for followers in the current project,
 5744        // then skip it unless this project is shared. If it applies to all
 5745        // followers, regardless of project, then set `project_id` to none,
 5746        // indicating that it goes to all followers.
 5747        let project_id = if project_only {
 5748            Some(self.project.read(cx).remote_id()?)
 5749        } else {
 5750            None
 5751        };
 5752        self.app_state().workspace_store.update(cx, |store, cx| {
 5753            store.update_followers(project_id, update, cx)
 5754        })
 5755    }
 5756
 5757    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 5758        self.follower_states.iter().find_map(|(leader_id, state)| {
 5759            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 5760                Some(*leader_id)
 5761            } else {
 5762                None
 5763            }
 5764        })
 5765    }
 5766
 5767    fn leader_updated(
 5768        &mut self,
 5769        leader_id: impl Into<CollaboratorId>,
 5770        window: &mut Window,
 5771        cx: &mut Context<Self>,
 5772    ) -> Option<Box<dyn ItemHandle>> {
 5773        cx.notify();
 5774
 5775        let leader_id = leader_id.into();
 5776        let (panel_id, item) = match leader_id {
 5777            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 5778            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 5779        };
 5780
 5781        let state = self.follower_states.get(&leader_id)?;
 5782        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 5783        let pane;
 5784        if let Some(panel_id) = panel_id {
 5785            pane = self
 5786                .activate_panel_for_proto_id(panel_id, window, cx)?
 5787                .pane(cx)?;
 5788            let state = self.follower_states.get_mut(&leader_id)?;
 5789            state.dock_pane = Some(pane.clone());
 5790        } else {
 5791            pane = state.center_pane.clone();
 5792            let state = self.follower_states.get_mut(&leader_id)?;
 5793            if let Some(dock_pane) = state.dock_pane.take() {
 5794                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 5795            }
 5796        }
 5797
 5798        pane.update(cx, |pane, cx| {
 5799            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 5800            if let Some(index) = pane.index_for_item(item.as_ref()) {
 5801                pane.activate_item(index, false, false, window, cx);
 5802            } else {
 5803                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 5804            }
 5805
 5806            if focus_active_item {
 5807                pane.focus_active_item(window, cx)
 5808            }
 5809        });
 5810
 5811        Some(item)
 5812    }
 5813
 5814    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 5815        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 5816        let active_view_id = state.active_view_id?;
 5817        Some(
 5818            state
 5819                .items_by_leader_view_id
 5820                .get(&active_view_id)?
 5821                .view
 5822                .boxed_clone(),
 5823        )
 5824    }
 5825
 5826    fn active_item_for_peer(
 5827        &self,
 5828        peer_id: PeerId,
 5829        window: &mut Window,
 5830        cx: &mut Context<Self>,
 5831    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 5832        let call = self.active_call()?;
 5833        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 5834        let leader_in_this_app;
 5835        let leader_in_this_project;
 5836        match participant.location {
 5837            ParticipantLocation::SharedProject { project_id } => {
 5838                leader_in_this_app = true;
 5839                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 5840            }
 5841            ParticipantLocation::UnsharedProject => {
 5842                leader_in_this_app = true;
 5843                leader_in_this_project = false;
 5844            }
 5845            ParticipantLocation::External => {
 5846                leader_in_this_app = false;
 5847                leader_in_this_project = false;
 5848            }
 5849        };
 5850        let state = self.follower_states.get(&peer_id.into())?;
 5851        let mut item_to_activate = None;
 5852        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 5853            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 5854                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 5855            {
 5856                item_to_activate = Some((item.location, item.view.boxed_clone()));
 5857            }
 5858        } else if let Some(shared_screen) =
 5859            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 5860        {
 5861            item_to_activate = Some((None, Box::new(shared_screen)));
 5862        }
 5863        item_to_activate
 5864    }
 5865
 5866    fn shared_screen_for_peer(
 5867        &self,
 5868        peer_id: PeerId,
 5869        pane: &Entity<Pane>,
 5870        window: &mut Window,
 5871        cx: &mut App,
 5872    ) -> Option<Entity<SharedScreen>> {
 5873        self.active_call()?
 5874            .create_shared_screen(peer_id, pane, window, cx)
 5875    }
 5876
 5877    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5878        if window.is_window_active() {
 5879            self.update_active_view_for_followers(window, cx);
 5880
 5881            if let Some(database_id) = self.database_id {
 5882                cx.background_spawn(persistence::DB.update_timestamp(database_id))
 5883                    .detach();
 5884            }
 5885        } else {
 5886            for pane in &self.panes {
 5887                pane.update(cx, |pane, cx| {
 5888                    if let Some(item) = pane.active_item() {
 5889                        item.workspace_deactivated(window, cx);
 5890                    }
 5891                    for item in pane.items() {
 5892                        if matches!(
 5893                            item.workspace_settings(cx).autosave,
 5894                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 5895                        ) {
 5896                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 5897                                .detach_and_log_err(cx);
 5898                        }
 5899                    }
 5900                });
 5901            }
 5902        }
 5903    }
 5904
 5905    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 5906        self.active_call.as_ref().map(|(call, _)| &*call.0)
 5907    }
 5908
 5909    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 5910        self.active_call.as_ref().map(|(call, _)| call.clone())
 5911    }
 5912
 5913    fn on_active_call_event(
 5914        &mut self,
 5915        event: &ActiveCallEvent,
 5916        window: &mut Window,
 5917        cx: &mut Context<Self>,
 5918    ) {
 5919        match event {
 5920            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 5921            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 5922                self.leader_updated(participant_id, window, cx);
 5923            }
 5924        }
 5925    }
 5926
 5927    pub fn database_id(&self) -> Option<WorkspaceId> {
 5928        self.database_id
 5929    }
 5930
 5931    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 5932        self.database_id = Some(id);
 5933    }
 5934
 5935    pub fn session_id(&self) -> Option<String> {
 5936        self.session_id.clone()
 5937    }
 5938
 5939    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 5940        let Some(display) = window.display(cx) else {
 5941            return Task::ready(());
 5942        };
 5943        let Ok(display_uuid) = display.uuid() else {
 5944            return Task::ready(());
 5945        };
 5946
 5947        let window_bounds = window.inner_window_bounds();
 5948        let database_id = self.database_id;
 5949        let has_paths = !self.root_paths(cx).is_empty();
 5950
 5951        cx.background_executor().spawn(async move {
 5952            if !has_paths {
 5953                persistence::write_default_window_bounds(window_bounds, display_uuid)
 5954                    .await
 5955                    .log_err();
 5956            }
 5957            if let Some(database_id) = database_id {
 5958                DB.set_window_open_status(
 5959                    database_id,
 5960                    SerializedWindowBounds(window_bounds),
 5961                    display_uuid,
 5962                )
 5963                .await
 5964                .log_err();
 5965            } else {
 5966                persistence::write_default_window_bounds(window_bounds, display_uuid)
 5967                    .await
 5968                    .log_err();
 5969            }
 5970        })
 5971    }
 5972
 5973    /// Bypass the 200ms serialization throttle and write workspace state to
 5974    /// the DB immediately. Returns a task the caller can await to ensure the
 5975    /// write completes. Used by the quit handler so the most recent state
 5976    /// isn't lost to a pending throttle timer when the process exits.
 5977    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 5978        self._schedule_serialize_workspace.take();
 5979        self._serialize_workspace_task.take();
 5980        self.bounds_save_task_queued.take();
 5981
 5982        let bounds_task = self.save_window_bounds(window, cx);
 5983        let serialize_task = self.serialize_workspace_internal(window, cx);
 5984        cx.spawn(async move |_| {
 5985            bounds_task.await;
 5986            serialize_task.await;
 5987        })
 5988    }
 5989
 5990    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 5991        let project = self.project().read(cx);
 5992        project
 5993            .visible_worktrees(cx)
 5994            .map(|worktree| worktree.read(cx).abs_path())
 5995            .collect::<Vec<_>>()
 5996    }
 5997
 5998    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 5999        match member {
 6000            Member::Axis(PaneAxis { members, .. }) => {
 6001                for child in members.iter() {
 6002                    self.remove_panes(child.clone(), window, cx)
 6003                }
 6004            }
 6005            Member::Pane(pane) => {
 6006                self.force_remove_pane(&pane, &None, window, cx);
 6007            }
 6008        }
 6009    }
 6010
 6011    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6012        self.session_id.take();
 6013        self.serialize_workspace_internal(window, cx)
 6014    }
 6015
 6016    fn force_remove_pane(
 6017        &mut self,
 6018        pane: &Entity<Pane>,
 6019        focus_on: &Option<Entity<Pane>>,
 6020        window: &mut Window,
 6021        cx: &mut Context<Workspace>,
 6022    ) {
 6023        self.panes.retain(|p| p != pane);
 6024        if let Some(focus_on) = focus_on {
 6025            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6026        } else if self.active_pane() == pane {
 6027            self.panes
 6028                .last()
 6029                .unwrap()
 6030                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6031        }
 6032        if self.last_active_center_pane == Some(pane.downgrade()) {
 6033            self.last_active_center_pane = None;
 6034        }
 6035        cx.notify();
 6036    }
 6037
 6038    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6039        if self._schedule_serialize_workspace.is_none() {
 6040            self._schedule_serialize_workspace =
 6041                Some(cx.spawn_in(window, async move |this, cx| {
 6042                    cx.background_executor()
 6043                        .timer(SERIALIZATION_THROTTLE_TIME)
 6044                        .await;
 6045                    this.update_in(cx, |this, window, cx| {
 6046                        this._serialize_workspace_task =
 6047                            Some(this.serialize_workspace_internal(window, cx));
 6048                        this._schedule_serialize_workspace.take();
 6049                    })
 6050                    .log_err();
 6051                }));
 6052        }
 6053    }
 6054
 6055    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6056        let Some(database_id) = self.database_id() else {
 6057            return Task::ready(());
 6058        };
 6059
 6060        fn serialize_pane_handle(
 6061            pane_handle: &Entity<Pane>,
 6062            window: &mut Window,
 6063            cx: &mut App,
 6064        ) -> SerializedPane {
 6065            let (items, active, pinned_count) = {
 6066                let pane = pane_handle.read(cx);
 6067                let active_item_id = pane.active_item().map(|item| item.item_id());
 6068                (
 6069                    pane.items()
 6070                        .filter_map(|handle| {
 6071                            let handle = handle.to_serializable_item_handle(cx)?;
 6072
 6073                            Some(SerializedItem {
 6074                                kind: Arc::from(handle.serialized_item_kind()),
 6075                                item_id: handle.item_id().as_u64(),
 6076                                active: Some(handle.item_id()) == active_item_id,
 6077                                preview: pane.is_active_preview_item(handle.item_id()),
 6078                            })
 6079                        })
 6080                        .collect::<Vec<_>>(),
 6081                    pane.has_focus(window, cx),
 6082                    pane.pinned_count(),
 6083                )
 6084            };
 6085
 6086            SerializedPane::new(items, active, pinned_count)
 6087        }
 6088
 6089        fn build_serialized_pane_group(
 6090            pane_group: &Member,
 6091            window: &mut Window,
 6092            cx: &mut App,
 6093        ) -> SerializedPaneGroup {
 6094            match pane_group {
 6095                Member::Axis(PaneAxis {
 6096                    axis,
 6097                    members,
 6098                    flexes,
 6099                    bounding_boxes: _,
 6100                }) => SerializedPaneGroup::Group {
 6101                    axis: SerializedAxis(*axis),
 6102                    children: members
 6103                        .iter()
 6104                        .map(|member| build_serialized_pane_group(member, window, cx))
 6105                        .collect::<Vec<_>>(),
 6106                    flexes: Some(flexes.lock().clone()),
 6107                },
 6108                Member::Pane(pane_handle) => {
 6109                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6110                }
 6111            }
 6112        }
 6113
 6114        fn build_serialized_docks(
 6115            this: &Workspace,
 6116            window: &mut Window,
 6117            cx: &mut App,
 6118        ) -> DockStructure {
 6119            this.capture_dock_state(window, cx)
 6120        }
 6121
 6122        match self.workspace_location(cx) {
 6123            WorkspaceLocation::Location(location, paths) => {
 6124                let breakpoints = self.project.update(cx, |project, cx| {
 6125                    project
 6126                        .breakpoint_store()
 6127                        .read(cx)
 6128                        .all_source_breakpoints(cx)
 6129                });
 6130                let user_toolchains = self
 6131                    .project
 6132                    .read(cx)
 6133                    .user_toolchains(cx)
 6134                    .unwrap_or_default();
 6135
 6136                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6137                let docks = build_serialized_docks(self, window, cx);
 6138                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6139
 6140                let serialized_workspace = SerializedWorkspace {
 6141                    id: database_id,
 6142                    location,
 6143                    paths,
 6144                    center_group,
 6145                    window_bounds,
 6146                    display: Default::default(),
 6147                    docks,
 6148                    centered_layout: self.centered_layout,
 6149                    session_id: self.session_id.clone(),
 6150                    breakpoints,
 6151                    window_id: Some(window.window_handle().window_id().as_u64()),
 6152                    user_toolchains,
 6153                };
 6154
 6155                window.spawn(cx, async move |_| {
 6156                    persistence::DB.save_workspace(serialized_workspace).await;
 6157                })
 6158            }
 6159            WorkspaceLocation::DetachFromSession => {
 6160                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6161                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6162                // Save dock state for empty local workspaces
 6163                let docks = build_serialized_docks(self, window, cx);
 6164                window.spawn(cx, async move |_| {
 6165                    persistence::DB
 6166                        .set_window_open_status(
 6167                            database_id,
 6168                            window_bounds,
 6169                            display.unwrap_or_default(),
 6170                        )
 6171                        .await
 6172                        .log_err();
 6173                    persistence::DB
 6174                        .set_session_id(database_id, None)
 6175                        .await
 6176                        .log_err();
 6177                    persistence::write_default_dock_state(docks).await.log_err();
 6178                })
 6179            }
 6180            WorkspaceLocation::None => {
 6181                // Save dock state for empty non-local workspaces
 6182                let docks = build_serialized_docks(self, window, cx);
 6183                window.spawn(cx, async move |_| {
 6184                    persistence::write_default_dock_state(docks).await.log_err();
 6185                })
 6186            }
 6187        }
 6188    }
 6189
 6190    fn has_any_items_open(&self, cx: &App) -> bool {
 6191        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6192    }
 6193
 6194    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6195        let paths = PathList::new(&self.root_paths(cx));
 6196        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6197            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6198        } else if self.project.read(cx).is_local() {
 6199            if !paths.is_empty() || self.has_any_items_open(cx) {
 6200                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6201            } else {
 6202                WorkspaceLocation::DetachFromSession
 6203            }
 6204        } else {
 6205            WorkspaceLocation::None
 6206        }
 6207    }
 6208
 6209    fn update_history(&self, cx: &mut App) {
 6210        let Some(id) = self.database_id() else {
 6211            return;
 6212        };
 6213        if !self.project.read(cx).is_local() {
 6214            return;
 6215        }
 6216        if let Some(manager) = HistoryManager::global(cx) {
 6217            let paths = PathList::new(&self.root_paths(cx));
 6218            manager.update(cx, |this, cx| {
 6219                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6220            });
 6221        }
 6222    }
 6223
 6224    async fn serialize_items(
 6225        this: &WeakEntity<Self>,
 6226        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6227        cx: &mut AsyncWindowContext,
 6228    ) -> Result<()> {
 6229        const CHUNK_SIZE: usize = 200;
 6230
 6231        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6232
 6233        while let Some(items_received) = serializable_items.next().await {
 6234            let unique_items =
 6235                items_received
 6236                    .into_iter()
 6237                    .fold(HashMap::default(), |mut acc, item| {
 6238                        acc.entry(item.item_id()).or_insert(item);
 6239                        acc
 6240                    });
 6241
 6242            // We use into_iter() here so that the references to the items are moved into
 6243            // the tasks and not kept alive while we're sleeping.
 6244            for (_, item) in unique_items.into_iter() {
 6245                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6246                    item.serialize(workspace, false, window, cx)
 6247                }) {
 6248                    cx.background_spawn(async move { task.await.log_err() })
 6249                        .detach();
 6250                }
 6251            }
 6252
 6253            cx.background_executor()
 6254                .timer(SERIALIZATION_THROTTLE_TIME)
 6255                .await;
 6256        }
 6257
 6258        Ok(())
 6259    }
 6260
 6261    pub(crate) fn enqueue_item_serialization(
 6262        &mut self,
 6263        item: Box<dyn SerializableItemHandle>,
 6264    ) -> Result<()> {
 6265        self.serializable_items_tx
 6266            .unbounded_send(item)
 6267            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6268    }
 6269
 6270    pub(crate) fn load_workspace(
 6271        serialized_workspace: SerializedWorkspace,
 6272        paths_to_open: Vec<Option<ProjectPath>>,
 6273        window: &mut Window,
 6274        cx: &mut Context<Workspace>,
 6275    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6276        cx.spawn_in(window, async move |workspace, cx| {
 6277            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6278
 6279            let mut center_group = None;
 6280            let mut center_items = None;
 6281
 6282            // Traverse the splits tree and add to things
 6283            if let Some((group, active_pane, items)) = serialized_workspace
 6284                .center_group
 6285                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6286                .await
 6287            {
 6288                center_items = Some(items);
 6289                center_group = Some((group, active_pane))
 6290            }
 6291
 6292            let mut items_by_project_path = HashMap::default();
 6293            let mut item_ids_by_kind = HashMap::default();
 6294            let mut all_deserialized_items = Vec::default();
 6295            cx.update(|_, cx| {
 6296                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6297                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6298                        item_ids_by_kind
 6299                            .entry(serializable_item_handle.serialized_item_kind())
 6300                            .or_insert(Vec::new())
 6301                            .push(item.item_id().as_u64() as ItemId);
 6302                    }
 6303
 6304                    if let Some(project_path) = item.project_path(cx) {
 6305                        items_by_project_path.insert(project_path, item.clone());
 6306                    }
 6307                    all_deserialized_items.push(item);
 6308                }
 6309            })?;
 6310
 6311            let opened_items = paths_to_open
 6312                .into_iter()
 6313                .map(|path_to_open| {
 6314                    path_to_open
 6315                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6316                })
 6317                .collect::<Vec<_>>();
 6318
 6319            // Remove old panes from workspace panes list
 6320            workspace.update_in(cx, |workspace, window, cx| {
 6321                if let Some((center_group, active_pane)) = center_group {
 6322                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6323
 6324                    // Swap workspace center group
 6325                    workspace.center = PaneGroup::with_root(center_group);
 6326                    workspace.center.set_is_center(true);
 6327                    workspace.center.mark_positions(cx);
 6328
 6329                    if let Some(active_pane) = active_pane {
 6330                        workspace.set_active_pane(&active_pane, window, cx);
 6331                        cx.focus_self(window);
 6332                    } else {
 6333                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6334                    }
 6335                }
 6336
 6337                let docks = serialized_workspace.docks;
 6338
 6339                for (dock, serialized_dock) in [
 6340                    (&mut workspace.right_dock, docks.right),
 6341                    (&mut workspace.left_dock, docks.left),
 6342                    (&mut workspace.bottom_dock, docks.bottom),
 6343                ]
 6344                .iter_mut()
 6345                {
 6346                    dock.update(cx, |dock, cx| {
 6347                        dock.serialized_dock = Some(serialized_dock.clone());
 6348                        dock.restore_state(window, cx);
 6349                    });
 6350                }
 6351
 6352                cx.notify();
 6353            })?;
 6354
 6355            let _ = project
 6356                .update(cx, |project, cx| {
 6357                    project
 6358                        .breakpoint_store()
 6359                        .update(cx, |breakpoint_store, cx| {
 6360                            breakpoint_store
 6361                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6362                        })
 6363                })
 6364                .await;
 6365
 6366            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6367            // after loading the items, we might have different items and in order to avoid
 6368            // the database filling up, we delete items that haven't been loaded now.
 6369            //
 6370            // The items that have been loaded, have been saved after they've been added to the workspace.
 6371            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6372                item_ids_by_kind
 6373                    .into_iter()
 6374                    .map(|(item_kind, loaded_items)| {
 6375                        SerializableItemRegistry::cleanup(
 6376                            item_kind,
 6377                            serialized_workspace.id,
 6378                            loaded_items,
 6379                            window,
 6380                            cx,
 6381                        )
 6382                        .log_err()
 6383                    })
 6384                    .collect::<Vec<_>>()
 6385            })?;
 6386
 6387            futures::future::join_all(clean_up_tasks).await;
 6388
 6389            workspace
 6390                .update_in(cx, |workspace, window, cx| {
 6391                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6392                    workspace.serialize_workspace_internal(window, cx).detach();
 6393
 6394                    // Ensure that we mark the window as edited if we did load dirty items
 6395                    workspace.update_window_edited(window, cx);
 6396                })
 6397                .ok();
 6398
 6399            Ok(opened_items)
 6400        })
 6401    }
 6402
 6403    pub fn key_context(&self, cx: &App) -> KeyContext {
 6404        let mut context = KeyContext::new_with_defaults();
 6405        context.add("Workspace");
 6406        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6407        if let Some(status) = self
 6408            .debugger_provider
 6409            .as_ref()
 6410            .and_then(|provider| provider.active_thread_state(cx))
 6411        {
 6412            match status {
 6413                ThreadStatus::Running | ThreadStatus::Stepping => {
 6414                    context.add("debugger_running");
 6415                }
 6416                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6417                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6418            }
 6419        }
 6420
 6421        if self.left_dock.read(cx).is_open() {
 6422            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6423                context.set("left_dock", active_panel.panel_key());
 6424            }
 6425        }
 6426
 6427        if self.right_dock.read(cx).is_open() {
 6428            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6429                context.set("right_dock", active_panel.panel_key());
 6430            }
 6431        }
 6432
 6433        if self.bottom_dock.read(cx).is_open() {
 6434            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6435                context.set("bottom_dock", active_panel.panel_key());
 6436            }
 6437        }
 6438
 6439        context
 6440    }
 6441
 6442    /// Multiworkspace uses this to add workspace action handling to itself
 6443    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6444        self.add_workspace_actions_listeners(div, window, cx)
 6445            .on_action(cx.listener(
 6446                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6447                    for action in &action_sequence.0 {
 6448                        window.dispatch_action(action.boxed_clone(), cx);
 6449                    }
 6450                },
 6451            ))
 6452            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6453            .on_action(cx.listener(Self::close_all_items_and_panes))
 6454            .on_action(cx.listener(Self::close_item_in_all_panes))
 6455            .on_action(cx.listener(Self::save_all))
 6456            .on_action(cx.listener(Self::send_keystrokes))
 6457            .on_action(cx.listener(Self::add_folder_to_project))
 6458            .on_action(cx.listener(Self::follow_next_collaborator))
 6459            .on_action(cx.listener(Self::activate_pane_at_index))
 6460            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6461            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6462            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6463            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6464                let pane = workspace.active_pane().clone();
 6465                workspace.unfollow_in_pane(&pane, window, cx);
 6466            }))
 6467            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6468                workspace
 6469                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6470                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6471            }))
 6472            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6473                workspace
 6474                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6475                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6476            }))
 6477            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6478                workspace
 6479                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6480                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6481            }))
 6482            .on_action(
 6483                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6484                    workspace.activate_previous_pane(window, cx)
 6485                }),
 6486            )
 6487            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6488                workspace.activate_next_pane(window, cx)
 6489            }))
 6490            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6491                workspace.activate_last_pane(window, cx)
 6492            }))
 6493            .on_action(
 6494                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6495                    workspace.activate_next_window(cx)
 6496                }),
 6497            )
 6498            .on_action(
 6499                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6500                    workspace.activate_previous_window(cx)
 6501                }),
 6502            )
 6503            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6504                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6505            }))
 6506            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6507                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6508            }))
 6509            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6510                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6511            }))
 6512            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6513                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6514            }))
 6515            .on_action(cx.listener(
 6516                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6517                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6518                },
 6519            ))
 6520            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6521                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6522            }))
 6523            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6524                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6525            }))
 6526            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6527                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6528            }))
 6529            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6530                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6531            }))
 6532            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6533                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6534                    SplitDirection::Down,
 6535                    SplitDirection::Up,
 6536                    SplitDirection::Right,
 6537                    SplitDirection::Left,
 6538                ];
 6539                for dir in DIRECTION_PRIORITY {
 6540                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6541                        workspace.swap_pane_in_direction(dir, cx);
 6542                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6543                        break;
 6544                    }
 6545                }
 6546            }))
 6547            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6548                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6549            }))
 6550            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6551                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6552            }))
 6553            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6554                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6555            }))
 6556            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6557                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6558            }))
 6559            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6560                this.toggle_dock(DockPosition::Left, window, cx);
 6561            }))
 6562            .on_action(cx.listener(
 6563                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6564                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6565                },
 6566            ))
 6567            .on_action(cx.listener(
 6568                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6569                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6570                },
 6571            ))
 6572            .on_action(cx.listener(
 6573                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6574                    if !workspace.close_active_dock(window, cx) {
 6575                        cx.propagate();
 6576                    }
 6577                },
 6578            ))
 6579            .on_action(
 6580                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6581                    workspace.close_all_docks(window, cx);
 6582                }),
 6583            )
 6584            .on_action(cx.listener(Self::toggle_all_docks))
 6585            .on_action(cx.listener(
 6586                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6587                    workspace.clear_all_notifications(cx);
 6588                },
 6589            ))
 6590            .on_action(cx.listener(
 6591                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6592                    workspace.clear_navigation_history(window, cx);
 6593                },
 6594            ))
 6595            .on_action(cx.listener(
 6596                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6597                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6598                        workspace.suppress_notification(&notification_id, cx);
 6599                    }
 6600                },
 6601            ))
 6602            .on_action(cx.listener(
 6603                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6604                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6605                },
 6606            ))
 6607            .on_action(
 6608                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6609                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6610                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6611                            trusted_worktrees.clear_trusted_paths()
 6612                        });
 6613                        let clear_task = persistence::DB.clear_trusted_worktrees();
 6614                        cx.spawn(async move |_, cx| {
 6615                            if clear_task.await.log_err().is_some() {
 6616                                cx.update(|cx| reload(cx));
 6617                            }
 6618                        })
 6619                        .detach();
 6620                    }
 6621                }),
 6622            )
 6623            .on_action(cx.listener(
 6624                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 6625                    workspace.reopen_closed_item(window, cx).detach();
 6626                },
 6627            ))
 6628            .on_action(cx.listener(
 6629                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 6630                    for dock in workspace.all_docks() {
 6631                        if dock.focus_handle(cx).contains_focused(window, cx) {
 6632                            let Some(panel) = dock.read(cx).active_panel() else {
 6633                                return;
 6634                            };
 6635
 6636                            // Set to `None`, then the size will fall back to the default.
 6637                            panel.clone().set_size(None, window, cx);
 6638
 6639                            return;
 6640                        }
 6641                    }
 6642                },
 6643            ))
 6644            .on_action(cx.listener(
 6645                |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
 6646                    for dock in workspace.all_docks() {
 6647                        if let Some(panel) = dock.read(cx).visible_panel() {
 6648                            // Set to `None`, then the size will fall back to the default.
 6649                            panel.clone().set_size(None, window, cx);
 6650                        }
 6651                    }
 6652                },
 6653            ))
 6654            .on_action(cx.listener(
 6655                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 6656                    adjust_active_dock_size_by_px(
 6657                        px_with_ui_font_fallback(act.px, cx),
 6658                        workspace,
 6659                        window,
 6660                        cx,
 6661                    );
 6662                },
 6663            ))
 6664            .on_action(cx.listener(
 6665                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 6666                    adjust_active_dock_size_by_px(
 6667                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6668                        workspace,
 6669                        window,
 6670                        cx,
 6671                    );
 6672                },
 6673            ))
 6674            .on_action(cx.listener(
 6675                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 6676                    adjust_open_docks_size_by_px(
 6677                        px_with_ui_font_fallback(act.px, cx),
 6678                        workspace,
 6679                        window,
 6680                        cx,
 6681                    );
 6682                },
 6683            ))
 6684            .on_action(cx.listener(
 6685                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 6686                    adjust_open_docks_size_by_px(
 6687                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6688                        workspace,
 6689                        window,
 6690                        cx,
 6691                    );
 6692                },
 6693            ))
 6694            .on_action(cx.listener(Workspace::toggle_centered_layout))
 6695            .on_action(cx.listener(
 6696                |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
 6697                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6698                        let dock = active_dock.read(cx);
 6699                        if let Some(active_panel) = dock.active_panel() {
 6700                            if active_panel.pane(cx).is_none() {
 6701                                let mut recent_pane: Option<Entity<Pane>> = None;
 6702                                let mut recent_timestamp = 0;
 6703                                for pane_handle in workspace.panes() {
 6704                                    let pane = pane_handle.read(cx);
 6705                                    for entry in pane.activation_history() {
 6706                                        if entry.timestamp > recent_timestamp {
 6707                                            recent_timestamp = entry.timestamp;
 6708                                            recent_pane = Some(pane_handle.clone());
 6709                                        }
 6710                                    }
 6711                                }
 6712
 6713                                if let Some(pane) = recent_pane {
 6714                                    pane.update(cx, |pane, cx| {
 6715                                        let current_index = pane.active_item_index();
 6716                                        let items_len = pane.items_len();
 6717                                        if items_len > 0 {
 6718                                            let next_index = if current_index + 1 < items_len {
 6719                                                current_index + 1
 6720                                            } else {
 6721                                                0
 6722                                            };
 6723                                            pane.activate_item(
 6724                                                next_index, false, false, window, cx,
 6725                                            );
 6726                                        }
 6727                                    });
 6728                                    return;
 6729                                }
 6730                            }
 6731                        }
 6732                    }
 6733                    cx.propagate();
 6734                },
 6735            ))
 6736            .on_action(cx.listener(
 6737                |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
 6738                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6739                        let dock = active_dock.read(cx);
 6740                        if let Some(active_panel) = dock.active_panel() {
 6741                            if active_panel.pane(cx).is_none() {
 6742                                let mut recent_pane: Option<Entity<Pane>> = None;
 6743                                let mut recent_timestamp = 0;
 6744                                for pane_handle in workspace.panes() {
 6745                                    let pane = pane_handle.read(cx);
 6746                                    for entry in pane.activation_history() {
 6747                                        if entry.timestamp > recent_timestamp {
 6748                                            recent_timestamp = entry.timestamp;
 6749                                            recent_pane = Some(pane_handle.clone());
 6750                                        }
 6751                                    }
 6752                                }
 6753
 6754                                if let Some(pane) = recent_pane {
 6755                                    pane.update(cx, |pane, cx| {
 6756                                        let current_index = pane.active_item_index();
 6757                                        let items_len = pane.items_len();
 6758                                        if items_len > 0 {
 6759                                            let prev_index = if current_index > 0 {
 6760                                                current_index - 1
 6761                                            } else {
 6762                                                items_len.saturating_sub(1)
 6763                                            };
 6764                                            pane.activate_item(
 6765                                                prev_index, false, false, window, cx,
 6766                                            );
 6767                                        }
 6768                                    });
 6769                                    return;
 6770                                }
 6771                            }
 6772                        }
 6773                    }
 6774                    cx.propagate();
 6775                },
 6776            ))
 6777            .on_action(cx.listener(
 6778                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 6779                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6780                        let dock = active_dock.read(cx);
 6781                        if let Some(active_panel) = dock.active_panel() {
 6782                            if active_panel.pane(cx).is_none() {
 6783                                let active_pane = workspace.active_pane().clone();
 6784                                active_pane.update(cx, |pane, cx| {
 6785                                    pane.close_active_item(action, window, cx)
 6786                                        .detach_and_log_err(cx);
 6787                                });
 6788                                return;
 6789                            }
 6790                        }
 6791                    }
 6792                    cx.propagate();
 6793                },
 6794            ))
 6795            .on_action(
 6796                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 6797                    let pane = workspace.active_pane().clone();
 6798                    if let Some(item) = pane.read(cx).active_item() {
 6799                        item.toggle_read_only(window, cx);
 6800                    }
 6801                }),
 6802            )
 6803            .on_action(cx.listener(Workspace::cancel))
 6804    }
 6805
 6806    #[cfg(any(test, feature = "test-support"))]
 6807    pub fn set_random_database_id(&mut self) {
 6808        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 6809    }
 6810
 6811    #[cfg(any(test, feature = "test-support"))]
 6812    pub(crate) fn test_new(
 6813        project: Entity<Project>,
 6814        window: &mut Window,
 6815        cx: &mut Context<Self>,
 6816    ) -> Self {
 6817        use node_runtime::NodeRuntime;
 6818        use session::Session;
 6819
 6820        let client = project.read(cx).client();
 6821        let user_store = project.read(cx).user_store();
 6822        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 6823        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 6824        window.activate_window();
 6825        let app_state = Arc::new(AppState {
 6826            languages: project.read(cx).languages().clone(),
 6827            workspace_store,
 6828            client,
 6829            user_store,
 6830            fs: project.read(cx).fs().clone(),
 6831            build_window_options: |_, _| Default::default(),
 6832            node_runtime: NodeRuntime::unavailable(),
 6833            session,
 6834        });
 6835        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 6836        workspace
 6837            .active_pane
 6838            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6839        workspace
 6840    }
 6841
 6842    pub fn register_action<A: Action>(
 6843        &mut self,
 6844        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 6845    ) -> &mut Self {
 6846        let callback = Arc::new(callback);
 6847
 6848        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 6849            let callback = callback.clone();
 6850            div.on_action(cx.listener(move |workspace, event, window, cx| {
 6851                (callback)(workspace, event, window, cx)
 6852            }))
 6853        }));
 6854        self
 6855    }
 6856    pub fn register_action_renderer(
 6857        &mut self,
 6858        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 6859    ) -> &mut Self {
 6860        self.workspace_actions.push(Box::new(callback));
 6861        self
 6862    }
 6863
 6864    fn add_workspace_actions_listeners(
 6865        &self,
 6866        mut div: Div,
 6867        window: &mut Window,
 6868        cx: &mut Context<Self>,
 6869    ) -> Div {
 6870        for action in self.workspace_actions.iter() {
 6871            div = (action)(div, self, window, cx)
 6872        }
 6873        div
 6874    }
 6875
 6876    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 6877        self.modal_layer.read(cx).has_active_modal()
 6878    }
 6879
 6880    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 6881        self.modal_layer.read(cx).active_modal()
 6882    }
 6883
 6884    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 6885    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 6886    /// If no modal is active, the new modal will be shown.
 6887    ///
 6888    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 6889    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 6890    /// will not be shown.
 6891    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 6892    where
 6893        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 6894    {
 6895        self.modal_layer.update(cx, |modal_layer, cx| {
 6896            modal_layer.toggle_modal(window, cx, build)
 6897        })
 6898    }
 6899
 6900    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 6901        self.modal_layer
 6902            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 6903    }
 6904
 6905    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 6906        self.toast_layer
 6907            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 6908    }
 6909
 6910    pub fn toggle_centered_layout(
 6911        &mut self,
 6912        _: &ToggleCenteredLayout,
 6913        _: &mut Window,
 6914        cx: &mut Context<Self>,
 6915    ) {
 6916        self.centered_layout = !self.centered_layout;
 6917        if let Some(database_id) = self.database_id() {
 6918            cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
 6919                .detach_and_log_err(cx);
 6920        }
 6921        cx.notify();
 6922    }
 6923
 6924    fn adjust_padding(padding: Option<f32>) -> f32 {
 6925        padding
 6926            .unwrap_or(CenteredPaddingSettings::default().0)
 6927            .clamp(
 6928                CenteredPaddingSettings::MIN_PADDING,
 6929                CenteredPaddingSettings::MAX_PADDING,
 6930            )
 6931    }
 6932
 6933    fn render_dock(
 6934        &self,
 6935        position: DockPosition,
 6936        dock: &Entity<Dock>,
 6937        window: &mut Window,
 6938        cx: &mut App,
 6939    ) -> Option<Div> {
 6940        if self.zoomed_position == Some(position) {
 6941            return None;
 6942        }
 6943
 6944        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 6945            let pane = panel.pane(cx)?;
 6946            let follower_states = &self.follower_states;
 6947            leader_border_for_pane(follower_states, &pane, window, cx)
 6948        });
 6949
 6950        Some(
 6951            div()
 6952                .flex()
 6953                .flex_none()
 6954                .overflow_hidden()
 6955                .child(dock.clone())
 6956                .children(leader_border),
 6957        )
 6958    }
 6959
 6960    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 6961        window
 6962            .root::<MultiWorkspace>()
 6963            .flatten()
 6964            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 6965    }
 6966
 6967    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 6968        self.zoomed.as_ref()
 6969    }
 6970
 6971    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 6972        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 6973            return;
 6974        };
 6975        let windows = cx.windows();
 6976        let next_window =
 6977            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 6978                || {
 6979                    windows
 6980                        .iter()
 6981                        .cycle()
 6982                        .skip_while(|window| window.window_id() != current_window_id)
 6983                        .nth(1)
 6984                },
 6985            );
 6986
 6987        if let Some(window) = next_window {
 6988            window
 6989                .update(cx, |_, window, _| window.activate_window())
 6990                .ok();
 6991        }
 6992    }
 6993
 6994    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 6995        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 6996            return;
 6997        };
 6998        let windows = cx.windows();
 6999        let prev_window =
 7000            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7001                || {
 7002                    windows
 7003                        .iter()
 7004                        .rev()
 7005                        .cycle()
 7006                        .skip_while(|window| window.window_id() != current_window_id)
 7007                        .nth(1)
 7008                },
 7009            );
 7010
 7011        if let Some(window) = prev_window {
 7012            window
 7013                .update(cx, |_, window, _| window.activate_window())
 7014                .ok();
 7015        }
 7016    }
 7017
 7018    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7019        if cx.stop_active_drag(window) {
 7020        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7021            dismiss_app_notification(&notification_id, cx);
 7022        } else {
 7023            cx.propagate();
 7024        }
 7025    }
 7026
 7027    fn adjust_dock_size_by_px(
 7028        &mut self,
 7029        panel_size: Pixels,
 7030        dock_pos: DockPosition,
 7031        px: Pixels,
 7032        window: &mut Window,
 7033        cx: &mut Context<Self>,
 7034    ) {
 7035        match dock_pos {
 7036            DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
 7037            DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
 7038            DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
 7039        }
 7040    }
 7041
 7042    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7043        let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
 7044
 7045        self.left_dock.update(cx, |left_dock, cx| {
 7046            if WorkspaceSettings::get_global(cx)
 7047                .resize_all_panels_in_dock
 7048                .contains(&DockPosition::Left)
 7049            {
 7050                left_dock.resize_all_panels(Some(size), window, cx);
 7051            } else {
 7052                left_dock.resize_active_panel(Some(size), window, cx);
 7053            }
 7054        });
 7055    }
 7056
 7057    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7058        let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
 7059        self.left_dock.read_with(cx, |left_dock, cx| {
 7060            let left_dock_size = left_dock
 7061                .active_panel_size(window, cx)
 7062                .unwrap_or(Pixels::ZERO);
 7063            if left_dock_size + size > self.bounds.right() {
 7064                size = self.bounds.right() - left_dock_size
 7065            }
 7066        });
 7067        self.right_dock.update(cx, |right_dock, cx| {
 7068            if WorkspaceSettings::get_global(cx)
 7069                .resize_all_panels_in_dock
 7070                .contains(&DockPosition::Right)
 7071            {
 7072                right_dock.resize_all_panels(Some(size), window, cx);
 7073            } else {
 7074                right_dock.resize_active_panel(Some(size), window, cx);
 7075            }
 7076        });
 7077    }
 7078
 7079    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7080        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7081        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7082            if WorkspaceSettings::get_global(cx)
 7083                .resize_all_panels_in_dock
 7084                .contains(&DockPosition::Bottom)
 7085            {
 7086                bottom_dock.resize_all_panels(Some(size), window, cx);
 7087            } else {
 7088                bottom_dock.resize_active_panel(Some(size), window, cx);
 7089            }
 7090        });
 7091    }
 7092
 7093    fn toggle_edit_predictions_all_files(
 7094        &mut self,
 7095        _: &ToggleEditPrediction,
 7096        _window: &mut Window,
 7097        cx: &mut Context<Self>,
 7098    ) {
 7099        let fs = self.project().read(cx).fs().clone();
 7100        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7101        update_settings_file(fs, cx, move |file, _| {
 7102            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7103        });
 7104    }
 7105
 7106    pub fn show_worktree_trust_security_modal(
 7107        &mut self,
 7108        toggle: bool,
 7109        window: &mut Window,
 7110        cx: &mut Context<Self>,
 7111    ) {
 7112        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7113            if toggle {
 7114                security_modal.update(cx, |security_modal, cx| {
 7115                    security_modal.dismiss(cx);
 7116                })
 7117            } else {
 7118                security_modal.update(cx, |security_modal, cx| {
 7119                    security_modal.refresh_restricted_paths(cx);
 7120                });
 7121            }
 7122        } else {
 7123            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7124                .map(|trusted_worktrees| {
 7125                    trusted_worktrees
 7126                        .read(cx)
 7127                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7128                })
 7129                .unwrap_or(false);
 7130            if has_restricted_worktrees {
 7131                let project = self.project().read(cx);
 7132                let remote_host = project
 7133                    .remote_connection_options(cx)
 7134                    .map(RemoteHostLocation::from);
 7135                let worktree_store = project.worktree_store().downgrade();
 7136                self.toggle_modal(window, cx, |_, cx| {
 7137                    SecurityModal::new(worktree_store, remote_host, cx)
 7138                });
 7139            }
 7140        }
 7141    }
 7142}
 7143
 7144pub trait AnyActiveCall {
 7145    fn entity(&self) -> AnyEntity;
 7146    fn is_in_room(&self, _: &App) -> bool;
 7147    fn room_id(&self, _: &App) -> Option<u64>;
 7148    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7149    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7150    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7151    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7152    fn is_sharing_project(&self, _: &App) -> bool;
 7153    fn has_remote_participants(&self, _: &App) -> bool;
 7154    fn local_participant_is_guest(&self, _: &App) -> bool;
 7155    fn client(&self, _: &App) -> Arc<Client>;
 7156    fn share_on_join(&self, _: &App) -> bool;
 7157    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7158    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7159    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7160    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7161    fn join_project(
 7162        &self,
 7163        _: u64,
 7164        _: Arc<LanguageRegistry>,
 7165        _: Arc<dyn Fs>,
 7166        _: &mut App,
 7167    ) -> Task<Result<Entity<Project>>>;
 7168    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7169    fn subscribe(
 7170        &self,
 7171        _: &mut Window,
 7172        _: &mut Context<Workspace>,
 7173        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7174    ) -> Subscription;
 7175    fn create_shared_screen(
 7176        &self,
 7177        _: PeerId,
 7178        _: &Entity<Pane>,
 7179        _: &mut Window,
 7180        _: &mut App,
 7181    ) -> Option<Entity<SharedScreen>>;
 7182}
 7183
 7184#[derive(Clone)]
 7185pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7186impl Global for GlobalAnyActiveCall {}
 7187
 7188impl GlobalAnyActiveCall {
 7189    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7190        cx.try_global()
 7191    }
 7192
 7193    pub(crate) fn global(cx: &App) -> &Self {
 7194        cx.global()
 7195    }
 7196}
 7197/// Workspace-local view of a remote participant's location.
 7198#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7199pub enum ParticipantLocation {
 7200    SharedProject { project_id: u64 },
 7201    UnsharedProject,
 7202    External,
 7203}
 7204
 7205impl ParticipantLocation {
 7206    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7207        match location
 7208            .and_then(|l| l.variant)
 7209            .context("participant location was not provided")?
 7210        {
 7211            proto::participant_location::Variant::SharedProject(project) => {
 7212                Ok(Self::SharedProject {
 7213                    project_id: project.id,
 7214                })
 7215            }
 7216            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7217            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7218        }
 7219    }
 7220}
 7221/// Workspace-local view of a remote collaborator's state.
 7222/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7223#[derive(Clone)]
 7224pub struct RemoteCollaborator {
 7225    pub user: Arc<User>,
 7226    pub peer_id: PeerId,
 7227    pub location: ParticipantLocation,
 7228    pub participant_index: ParticipantIndex,
 7229}
 7230
 7231pub enum ActiveCallEvent {
 7232    ParticipantLocationChanged { participant_id: PeerId },
 7233    RemoteVideoTracksChanged { participant_id: PeerId },
 7234}
 7235
 7236fn leader_border_for_pane(
 7237    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7238    pane: &Entity<Pane>,
 7239    _: &Window,
 7240    cx: &App,
 7241) -> Option<Div> {
 7242    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7243        if state.pane() == pane {
 7244            Some((*leader_id, state))
 7245        } else {
 7246            None
 7247        }
 7248    })?;
 7249
 7250    let mut leader_color = match leader_id {
 7251        CollaboratorId::PeerId(leader_peer_id) => {
 7252            let leader = GlobalAnyActiveCall::try_global(cx)?
 7253                .0
 7254                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7255
 7256            cx.theme()
 7257                .players()
 7258                .color_for_participant(leader.participant_index.0)
 7259                .cursor
 7260        }
 7261        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7262    };
 7263    leader_color.fade_out(0.3);
 7264    Some(
 7265        div()
 7266            .absolute()
 7267            .size_full()
 7268            .left_0()
 7269            .top_0()
 7270            .border_2()
 7271            .border_color(leader_color),
 7272    )
 7273}
 7274
 7275fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7276    ZED_WINDOW_POSITION
 7277        .zip(*ZED_WINDOW_SIZE)
 7278        .map(|(position, size)| Bounds {
 7279            origin: position,
 7280            size,
 7281        })
 7282}
 7283
 7284fn open_items(
 7285    serialized_workspace: Option<SerializedWorkspace>,
 7286    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7287    window: &mut Window,
 7288    cx: &mut Context<Workspace>,
 7289) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7290    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7291        Workspace::load_workspace(
 7292            serialized_workspace,
 7293            project_paths_to_open
 7294                .iter()
 7295                .map(|(_, project_path)| project_path)
 7296                .cloned()
 7297                .collect(),
 7298            window,
 7299            cx,
 7300        )
 7301    });
 7302
 7303    cx.spawn_in(window, async move |workspace, cx| {
 7304        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7305
 7306        if let Some(restored_items) = restored_items {
 7307            let restored_items = restored_items.await?;
 7308
 7309            let restored_project_paths = restored_items
 7310                .iter()
 7311                .filter_map(|item| {
 7312                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7313                        .ok()
 7314                        .flatten()
 7315                })
 7316                .collect::<HashSet<_>>();
 7317
 7318            for restored_item in restored_items {
 7319                opened_items.push(restored_item.map(Ok));
 7320            }
 7321
 7322            project_paths_to_open
 7323                .iter_mut()
 7324                .for_each(|(_, project_path)| {
 7325                    if let Some(project_path_to_open) = project_path
 7326                        && restored_project_paths.contains(project_path_to_open)
 7327                    {
 7328                        *project_path = None;
 7329                    }
 7330                });
 7331        } else {
 7332            for _ in 0..project_paths_to_open.len() {
 7333                opened_items.push(None);
 7334            }
 7335        }
 7336        assert!(opened_items.len() == project_paths_to_open.len());
 7337
 7338        let tasks =
 7339            project_paths_to_open
 7340                .into_iter()
 7341                .enumerate()
 7342                .map(|(ix, (abs_path, project_path))| {
 7343                    let workspace = workspace.clone();
 7344                    cx.spawn(async move |cx| {
 7345                        let file_project_path = project_path?;
 7346                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7347                            workspace.project().update(cx, |project, cx| {
 7348                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7349                            })
 7350                        });
 7351
 7352                        // We only want to open file paths here. If one of the items
 7353                        // here is a directory, it was already opened further above
 7354                        // with a `find_or_create_worktree`.
 7355                        if let Ok(task) = abs_path_task
 7356                            && task.await.is_none_or(|p| p.is_file())
 7357                        {
 7358                            return Some((
 7359                                ix,
 7360                                workspace
 7361                                    .update_in(cx, |workspace, window, cx| {
 7362                                        workspace.open_path(
 7363                                            file_project_path,
 7364                                            None,
 7365                                            true,
 7366                                            window,
 7367                                            cx,
 7368                                        )
 7369                                    })
 7370                                    .log_err()?
 7371                                    .await,
 7372                            ));
 7373                        }
 7374                        None
 7375                    })
 7376                });
 7377
 7378        let tasks = tasks.collect::<Vec<_>>();
 7379
 7380        let tasks = futures::future::join_all(tasks);
 7381        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7382            opened_items[ix] = Some(path_open_result);
 7383        }
 7384
 7385        Ok(opened_items)
 7386    })
 7387}
 7388
 7389enum ActivateInDirectionTarget {
 7390    Pane(Entity<Pane>),
 7391    Dock(Entity<Dock>),
 7392}
 7393
 7394fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7395    window
 7396        .update(cx, |multi_workspace, _, cx| {
 7397            let workspace = multi_workspace.workspace().clone();
 7398            workspace.update(cx, |workspace, cx| {
 7399                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7400                    struct DatabaseFailedNotification;
 7401
 7402                    workspace.show_notification(
 7403                        NotificationId::unique::<DatabaseFailedNotification>(),
 7404                        cx,
 7405                        |cx| {
 7406                            cx.new(|cx| {
 7407                                MessageNotification::new("Failed to load the database file.", cx)
 7408                                    .primary_message("File an Issue")
 7409                                    .primary_icon(IconName::Plus)
 7410                                    .primary_on_click(|window, cx| {
 7411                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7412                                    })
 7413                            })
 7414                        },
 7415                    );
 7416                }
 7417            });
 7418        })
 7419        .log_err();
 7420}
 7421
 7422fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7423    if val == 0 {
 7424        ThemeSettings::get_global(cx).ui_font_size(cx)
 7425    } else {
 7426        px(val as f32)
 7427    }
 7428}
 7429
 7430fn adjust_active_dock_size_by_px(
 7431    px: Pixels,
 7432    workspace: &mut Workspace,
 7433    window: &mut Window,
 7434    cx: &mut Context<Workspace>,
 7435) {
 7436    let Some(active_dock) = workspace
 7437        .all_docks()
 7438        .into_iter()
 7439        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7440    else {
 7441        return;
 7442    };
 7443    let dock = active_dock.read(cx);
 7444    let Some(panel_size) = dock.active_panel_size(window, cx) else {
 7445        return;
 7446    };
 7447    let dock_pos = dock.position();
 7448    workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
 7449}
 7450
 7451fn adjust_open_docks_size_by_px(
 7452    px: Pixels,
 7453    workspace: &mut Workspace,
 7454    window: &mut Window,
 7455    cx: &mut Context<Workspace>,
 7456) {
 7457    let docks = workspace
 7458        .all_docks()
 7459        .into_iter()
 7460        .filter_map(|dock| {
 7461            if dock.read(cx).is_open() {
 7462                let dock = dock.read(cx);
 7463                let panel_size = dock.active_panel_size(window, cx)?;
 7464                let dock_pos = dock.position();
 7465                Some((panel_size, dock_pos, px))
 7466            } else {
 7467                None
 7468            }
 7469        })
 7470        .collect::<Vec<_>>();
 7471
 7472    docks
 7473        .into_iter()
 7474        .for_each(|(panel_size, dock_pos, offset)| {
 7475            workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
 7476        });
 7477}
 7478
 7479impl Focusable for Workspace {
 7480    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7481        self.active_pane.focus_handle(cx)
 7482    }
 7483}
 7484
 7485#[derive(Clone)]
 7486struct DraggedDock(DockPosition);
 7487
 7488impl Render for DraggedDock {
 7489    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7490        gpui::Empty
 7491    }
 7492}
 7493
 7494impl Render for Workspace {
 7495    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 7496        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 7497        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 7498            log::info!("Rendered first frame");
 7499        }
 7500
 7501        let centered_layout = self.centered_layout
 7502            && self.center.panes().len() == 1
 7503            && self.active_item(cx).is_some();
 7504        let render_padding = |size| {
 7505            (size > 0.0).then(|| {
 7506                div()
 7507                    .h_full()
 7508                    .w(relative(size))
 7509                    .bg(cx.theme().colors().editor_background)
 7510                    .border_color(cx.theme().colors().pane_group_border)
 7511            })
 7512        };
 7513        let paddings = if centered_layout {
 7514            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 7515            (
 7516                render_padding(Self::adjust_padding(
 7517                    settings.left_padding.map(|padding| padding.0),
 7518                )),
 7519                render_padding(Self::adjust_padding(
 7520                    settings.right_padding.map(|padding| padding.0),
 7521                )),
 7522            )
 7523        } else {
 7524            (None, None)
 7525        };
 7526        let ui_font = theme::setup_ui_font(window, cx);
 7527
 7528        let theme = cx.theme().clone();
 7529        let colors = theme.colors();
 7530        let notification_entities = self
 7531            .notifications
 7532            .iter()
 7533            .map(|(_, notification)| notification.entity_id())
 7534            .collect::<Vec<_>>();
 7535        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 7536
 7537        div()
 7538            .relative()
 7539            .size_full()
 7540            .flex()
 7541            .flex_col()
 7542            .font(ui_font)
 7543            .gap_0()
 7544                .justify_start()
 7545                .items_start()
 7546                .text_color(colors.text)
 7547                .overflow_hidden()
 7548                .children(self.titlebar_item.clone())
 7549                .on_modifiers_changed(move |_, _, cx| {
 7550                    for &id in &notification_entities {
 7551                        cx.notify(id);
 7552                    }
 7553                })
 7554                .child(
 7555                    div()
 7556                        .size_full()
 7557                        .relative()
 7558                        .flex_1()
 7559                        .flex()
 7560                        .flex_col()
 7561                        .child(
 7562                            div()
 7563                                .id("workspace")
 7564                                .bg(colors.background)
 7565                                .relative()
 7566                                .flex_1()
 7567                                .w_full()
 7568                                .flex()
 7569                                .flex_col()
 7570                                .overflow_hidden()
 7571                                .border_t_1()
 7572                                .border_b_1()
 7573                                .border_color(colors.border)
 7574                                .child({
 7575                                    let this = cx.entity();
 7576                                    canvas(
 7577                                        move |bounds, window, cx| {
 7578                                            this.update(cx, |this, cx| {
 7579                                                let bounds_changed = this.bounds != bounds;
 7580                                                this.bounds = bounds;
 7581
 7582                                                if bounds_changed {
 7583                                                    this.left_dock.update(cx, |dock, cx| {
 7584                                                        dock.clamp_panel_size(
 7585                                                            bounds.size.width,
 7586                                                            window,
 7587                                                            cx,
 7588                                                        )
 7589                                                    });
 7590
 7591                                                    this.right_dock.update(cx, |dock, cx| {
 7592                                                        dock.clamp_panel_size(
 7593                                                            bounds.size.width,
 7594                                                            window,
 7595                                                            cx,
 7596                                                        )
 7597                                                    });
 7598
 7599                                                    this.bottom_dock.update(cx, |dock, cx| {
 7600                                                        dock.clamp_panel_size(
 7601                                                            bounds.size.height,
 7602                                                            window,
 7603                                                            cx,
 7604                                                        )
 7605                                                    });
 7606                                                }
 7607                                            })
 7608                                        },
 7609                                        |_, _, _, _| {},
 7610                                    )
 7611                                    .absolute()
 7612                                    .size_full()
 7613                                })
 7614                                .when(self.zoomed.is_none(), |this| {
 7615                                    this.on_drag_move(cx.listener(
 7616                                        move |workspace,
 7617                                              e: &DragMoveEvent<DraggedDock>,
 7618                                              window,
 7619                                              cx| {
 7620                                            if workspace.previous_dock_drag_coordinates
 7621                                                != Some(e.event.position)
 7622                                            {
 7623                                                workspace.previous_dock_drag_coordinates =
 7624                                                    Some(e.event.position);
 7625                                                match e.drag(cx).0 {
 7626                                                    DockPosition::Left => {
 7627                                                        workspace.resize_left_dock(
 7628                                                            e.event.position.x
 7629                                                                - workspace.bounds.left(),
 7630                                                            window,
 7631                                                            cx,
 7632                                                        );
 7633                                                    }
 7634                                                    DockPosition::Right => {
 7635                                                        workspace.resize_right_dock(
 7636                                                            workspace.bounds.right()
 7637                                                                - e.event.position.x,
 7638                                                            window,
 7639                                                            cx,
 7640                                                        );
 7641                                                    }
 7642                                                    DockPosition::Bottom => {
 7643                                                        workspace.resize_bottom_dock(
 7644                                                            workspace.bounds.bottom()
 7645                                                                - e.event.position.y,
 7646                                                            window,
 7647                                                            cx,
 7648                                                        );
 7649                                                    }
 7650                                                };
 7651                                                workspace.serialize_workspace(window, cx);
 7652                                            }
 7653                                        },
 7654                                    ))
 7655
 7656                                })
 7657                                .child({
 7658                                    match bottom_dock_layout {
 7659                                        BottomDockLayout::Full => div()
 7660                                            .flex()
 7661                                            .flex_col()
 7662                                            .h_full()
 7663                                            .child(
 7664                                                div()
 7665                                                    .flex()
 7666                                                    .flex_row()
 7667                                                    .flex_1()
 7668                                                    .overflow_hidden()
 7669                                                    .children(self.render_dock(
 7670                                                        DockPosition::Left,
 7671                                                        &self.left_dock,
 7672                                                        window,
 7673                                                        cx,
 7674                                                    ))
 7675
 7676                                                    .child(
 7677                                                        div()
 7678                                                            .flex()
 7679                                                            .flex_col()
 7680                                                            .flex_1()
 7681                                                            .overflow_hidden()
 7682                                                            .child(
 7683                                                                h_flex()
 7684                                                                    .flex_1()
 7685                                                                    .when_some(
 7686                                                                        paddings.0,
 7687                                                                        |this, p| {
 7688                                                                            this.child(
 7689                                                                                p.border_r_1(),
 7690                                                                            )
 7691                                                                        },
 7692                                                                    )
 7693                                                                    .child(self.center.render(
 7694                                                                        self.zoomed.as_ref(),
 7695                                                                        &PaneRenderContext {
 7696                                                                            follower_states:
 7697                                                                                &self.follower_states,
 7698                                                                            active_call: self.active_call(),
 7699                                                                            active_pane: &self.active_pane,
 7700                                                                            app_state: &self.app_state,
 7701                                                                            project: &self.project,
 7702                                                                            workspace: &self.weak_self,
 7703                                                                        },
 7704                                                                        window,
 7705                                                                        cx,
 7706                                                                    ))
 7707                                                                    .when_some(
 7708                                                                        paddings.1,
 7709                                                                        |this, p| {
 7710                                                                            this.child(
 7711                                                                                p.border_l_1(),
 7712                                                                            )
 7713                                                                        },
 7714                                                                    ),
 7715                                                            ),
 7716                                                    )
 7717
 7718                                                    .children(self.render_dock(
 7719                                                        DockPosition::Right,
 7720                                                        &self.right_dock,
 7721                                                        window,
 7722                                                        cx,
 7723                                                    )),
 7724                                            )
 7725                                            .child(div().w_full().children(self.render_dock(
 7726                                                DockPosition::Bottom,
 7727                                                &self.bottom_dock,
 7728                                                window,
 7729                                                cx
 7730                                            ))),
 7731
 7732                                        BottomDockLayout::LeftAligned => div()
 7733                                            .flex()
 7734                                            .flex_row()
 7735                                            .h_full()
 7736                                            .child(
 7737                                                div()
 7738                                                    .flex()
 7739                                                    .flex_col()
 7740                                                    .flex_1()
 7741                                                    .h_full()
 7742                                                    .child(
 7743                                                        div()
 7744                                                            .flex()
 7745                                                            .flex_row()
 7746                                                            .flex_1()
 7747                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 7748
 7749                                                            .child(
 7750                                                                div()
 7751                                                                    .flex()
 7752                                                                    .flex_col()
 7753                                                                    .flex_1()
 7754                                                                    .overflow_hidden()
 7755                                                                    .child(
 7756                                                                        h_flex()
 7757                                                                            .flex_1()
 7758                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7759                                                                            .child(self.center.render(
 7760                                                                                self.zoomed.as_ref(),
 7761                                                                                &PaneRenderContext {
 7762                                                                                    follower_states:
 7763                                                                                        &self.follower_states,
 7764                                                                                    active_call: self.active_call(),
 7765                                                                                    active_pane: &self.active_pane,
 7766                                                                                    app_state: &self.app_state,
 7767                                                                                    project: &self.project,
 7768                                                                                    workspace: &self.weak_self,
 7769                                                                                },
 7770                                                                                window,
 7771                                                                                cx,
 7772                                                                            ))
 7773                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7774                                                                    )
 7775                                                            )
 7776
 7777                                                    )
 7778                                                    .child(
 7779                                                        div()
 7780                                                            .w_full()
 7781                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7782                                                    ),
 7783                                            )
 7784                                            .children(self.render_dock(
 7785                                                DockPosition::Right,
 7786                                                &self.right_dock,
 7787                                                window,
 7788                                                cx,
 7789                                            )),
 7790
 7791                                        BottomDockLayout::RightAligned => div()
 7792                                            .flex()
 7793                                            .flex_row()
 7794                                            .h_full()
 7795                                            .children(self.render_dock(
 7796                                                DockPosition::Left,
 7797                                                &self.left_dock,
 7798                                                window,
 7799                                                cx,
 7800                                            ))
 7801
 7802                                            .child(
 7803                                                div()
 7804                                                    .flex()
 7805                                                    .flex_col()
 7806                                                    .flex_1()
 7807                                                    .h_full()
 7808                                                    .child(
 7809                                                        div()
 7810                                                            .flex()
 7811                                                            .flex_row()
 7812                                                            .flex_1()
 7813                                                            .child(
 7814                                                                div()
 7815                                                                    .flex()
 7816                                                                    .flex_col()
 7817                                                                    .flex_1()
 7818                                                                    .overflow_hidden()
 7819                                                                    .child(
 7820                                                                        h_flex()
 7821                                                                            .flex_1()
 7822                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7823                                                                            .child(self.center.render(
 7824                                                                                self.zoomed.as_ref(),
 7825                                                                                &PaneRenderContext {
 7826                                                                                    follower_states:
 7827                                                                                        &self.follower_states,
 7828                                                                                    active_call: self.active_call(),
 7829                                                                                    active_pane: &self.active_pane,
 7830                                                                                    app_state: &self.app_state,
 7831                                                                                    project: &self.project,
 7832                                                                                    workspace: &self.weak_self,
 7833                                                                                },
 7834                                                                                window,
 7835                                                                                cx,
 7836                                                                            ))
 7837                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7838                                                                    )
 7839                                                            )
 7840
 7841                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 7842                                                    )
 7843                                                    .child(
 7844                                                        div()
 7845                                                            .w_full()
 7846                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7847                                                    ),
 7848                                            ),
 7849
 7850                                        BottomDockLayout::Contained => div()
 7851                                            .flex()
 7852                                            .flex_row()
 7853                                            .h_full()
 7854                                            .children(self.render_dock(
 7855                                                DockPosition::Left,
 7856                                                &self.left_dock,
 7857                                                window,
 7858                                                cx,
 7859                                            ))
 7860
 7861                                            .child(
 7862                                                div()
 7863                                                    .flex()
 7864                                                    .flex_col()
 7865                                                    .flex_1()
 7866                                                    .overflow_hidden()
 7867                                                    .child(
 7868                                                        h_flex()
 7869                                                            .flex_1()
 7870                                                            .when_some(paddings.0, |this, p| {
 7871                                                                this.child(p.border_r_1())
 7872                                                            })
 7873                                                            .child(self.center.render(
 7874                                                                self.zoomed.as_ref(),
 7875                                                                &PaneRenderContext {
 7876                                                                    follower_states:
 7877                                                                        &self.follower_states,
 7878                                                                    active_call: self.active_call(),
 7879                                                                    active_pane: &self.active_pane,
 7880                                                                    app_state: &self.app_state,
 7881                                                                    project: &self.project,
 7882                                                                    workspace: &self.weak_self,
 7883                                                                },
 7884                                                                window,
 7885                                                                cx,
 7886                                                            ))
 7887                                                            .when_some(paddings.1, |this, p| {
 7888                                                                this.child(p.border_l_1())
 7889                                                            }),
 7890                                                    )
 7891                                                    .children(self.render_dock(
 7892                                                        DockPosition::Bottom,
 7893                                                        &self.bottom_dock,
 7894                                                        window,
 7895                                                        cx,
 7896                                                    )),
 7897                                            )
 7898
 7899                                            .children(self.render_dock(
 7900                                                DockPosition::Right,
 7901                                                &self.right_dock,
 7902                                                window,
 7903                                                cx,
 7904                                            )),
 7905                                    }
 7906                                })
 7907                                .children(self.zoomed.as_ref().and_then(|view| {
 7908                                    let zoomed_view = view.upgrade()?;
 7909                                    let div = div()
 7910                                        .occlude()
 7911                                        .absolute()
 7912                                        .overflow_hidden()
 7913                                        .border_color(colors.border)
 7914                                        .bg(colors.background)
 7915                                        .child(zoomed_view)
 7916                                        .inset_0()
 7917                                        .shadow_lg();
 7918
 7919                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 7920                                       return Some(div);
 7921                                    }
 7922
 7923                                    Some(match self.zoomed_position {
 7924                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 7925                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 7926                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 7927                                        None => {
 7928                                            div.top_2().bottom_2().left_2().right_2().border_1()
 7929                                        }
 7930                                    })
 7931                                }))
 7932                                .children(self.render_notifications(window, cx)),
 7933                        )
 7934                        .when(self.status_bar_visible(cx), |parent| {
 7935                            parent.child(self.status_bar.clone())
 7936                        })
 7937                        .child(self.toast_layer.clone()),
 7938                )
 7939    }
 7940}
 7941
 7942impl WorkspaceStore {
 7943    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 7944        Self {
 7945            workspaces: Default::default(),
 7946            _subscriptions: vec![
 7947                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 7948                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 7949            ],
 7950            client,
 7951        }
 7952    }
 7953
 7954    pub fn update_followers(
 7955        &self,
 7956        project_id: Option<u64>,
 7957        update: proto::update_followers::Variant,
 7958        cx: &App,
 7959    ) -> Option<()> {
 7960        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 7961        let room_id = active_call.0.room_id(cx)?;
 7962        self.client
 7963            .send(proto::UpdateFollowers {
 7964                room_id,
 7965                project_id,
 7966                variant: Some(update),
 7967            })
 7968            .log_err()
 7969    }
 7970
 7971    pub async fn handle_follow(
 7972        this: Entity<Self>,
 7973        envelope: TypedEnvelope<proto::Follow>,
 7974        mut cx: AsyncApp,
 7975    ) -> Result<proto::FollowResponse> {
 7976        this.update(&mut cx, |this, cx| {
 7977            let follower = Follower {
 7978                project_id: envelope.payload.project_id,
 7979                peer_id: envelope.original_sender_id()?,
 7980            };
 7981
 7982            let mut response = proto::FollowResponse::default();
 7983
 7984            this.workspaces.retain(|(window_handle, weak_workspace)| {
 7985                let Some(workspace) = weak_workspace.upgrade() else {
 7986                    return false;
 7987                };
 7988                window_handle
 7989                    .update(cx, |_, window, cx| {
 7990                        workspace.update(cx, |workspace, cx| {
 7991                            let handler_response =
 7992                                workspace.handle_follow(follower.project_id, window, cx);
 7993                            if let Some(active_view) = handler_response.active_view
 7994                                && workspace.project.read(cx).remote_id() == follower.project_id
 7995                            {
 7996                                response.active_view = Some(active_view)
 7997                            }
 7998                        });
 7999                    })
 8000                    .is_ok()
 8001            });
 8002
 8003            Ok(response)
 8004        })
 8005    }
 8006
 8007    async fn handle_update_followers(
 8008        this: Entity<Self>,
 8009        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8010        mut cx: AsyncApp,
 8011    ) -> Result<()> {
 8012        let leader_id = envelope.original_sender_id()?;
 8013        let update = envelope.payload;
 8014
 8015        this.update(&mut cx, |this, cx| {
 8016            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8017                let Some(workspace) = weak_workspace.upgrade() else {
 8018                    return false;
 8019                };
 8020                window_handle
 8021                    .update(cx, |_, window, cx| {
 8022                        workspace.update(cx, |workspace, cx| {
 8023                            let project_id = workspace.project.read(cx).remote_id();
 8024                            if update.project_id != project_id && update.project_id.is_some() {
 8025                                return;
 8026                            }
 8027                            workspace.handle_update_followers(
 8028                                leader_id,
 8029                                update.clone(),
 8030                                window,
 8031                                cx,
 8032                            );
 8033                        });
 8034                    })
 8035                    .is_ok()
 8036            });
 8037            Ok(())
 8038        })
 8039    }
 8040
 8041    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8042        self.workspaces.iter().map(|(_, weak)| weak)
 8043    }
 8044
 8045    pub fn workspaces_with_windows(
 8046        &self,
 8047    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8048        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8049    }
 8050}
 8051
 8052impl ViewId {
 8053    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8054        Ok(Self {
 8055            creator: message
 8056                .creator
 8057                .map(CollaboratorId::PeerId)
 8058                .context("creator is missing")?,
 8059            id: message.id,
 8060        })
 8061    }
 8062
 8063    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8064        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8065            Some(proto::ViewId {
 8066                creator: Some(peer_id),
 8067                id: self.id,
 8068            })
 8069        } else {
 8070            None
 8071        }
 8072    }
 8073}
 8074
 8075impl FollowerState {
 8076    fn pane(&self) -> &Entity<Pane> {
 8077        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8078    }
 8079}
 8080
 8081pub trait WorkspaceHandle {
 8082    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8083}
 8084
 8085impl WorkspaceHandle for Entity<Workspace> {
 8086    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8087        self.read(cx)
 8088            .worktrees(cx)
 8089            .flat_map(|worktree| {
 8090                let worktree_id = worktree.read(cx).id();
 8091                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8092                    worktree_id,
 8093                    path: f.path.clone(),
 8094                })
 8095            })
 8096            .collect::<Vec<_>>()
 8097    }
 8098}
 8099
 8100pub async fn last_opened_workspace_location(
 8101    fs: &dyn fs::Fs,
 8102) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8103    DB.last_workspace(fs)
 8104        .await
 8105        .log_err()
 8106        .flatten()
 8107        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8108}
 8109
 8110pub async fn last_session_workspace_locations(
 8111    last_session_id: &str,
 8112    last_session_window_stack: Option<Vec<WindowId>>,
 8113    fs: &dyn fs::Fs,
 8114) -> Option<Vec<SessionWorkspace>> {
 8115    DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8116        .await
 8117        .log_err()
 8118}
 8119
 8120pub struct MultiWorkspaceRestoreResult {
 8121    pub window_handle: WindowHandle<MultiWorkspace>,
 8122    pub errors: Vec<anyhow::Error>,
 8123}
 8124
 8125pub async fn restore_multiworkspace(
 8126    multi_workspace: SerializedMultiWorkspace,
 8127    app_state: Arc<AppState>,
 8128    cx: &mut AsyncApp,
 8129) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8130    let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
 8131    let mut group_iter = workspaces.into_iter();
 8132    let first = group_iter
 8133        .next()
 8134        .context("window group must not be empty")?;
 8135
 8136    let window_handle = if first.paths.is_empty() {
 8137        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8138            .await?
 8139    } else {
 8140        let (window, _items) = cx
 8141            .update(|cx| {
 8142                Workspace::new_local(
 8143                    first.paths.paths().to_vec(),
 8144                    app_state.clone(),
 8145                    None,
 8146                    None,
 8147                    None,
 8148                    true,
 8149                    cx,
 8150                )
 8151            })
 8152            .await?;
 8153        window
 8154    };
 8155
 8156    let mut errors = Vec::new();
 8157
 8158    for session_workspace in group_iter {
 8159        let error = if session_workspace.paths.is_empty() {
 8160            cx.update(|cx| {
 8161                open_workspace_by_id(
 8162                    session_workspace.workspace_id,
 8163                    app_state.clone(),
 8164                    Some(window_handle),
 8165                    cx,
 8166                )
 8167            })
 8168            .await
 8169            .err()
 8170        } else {
 8171            cx.update(|cx| {
 8172                Workspace::new_local(
 8173                    session_workspace.paths.paths().to_vec(),
 8174                    app_state.clone(),
 8175                    Some(window_handle),
 8176                    None,
 8177                    None,
 8178                    true,
 8179                    cx,
 8180                )
 8181            })
 8182            .await
 8183            .err()
 8184        };
 8185
 8186        if let Some(error) = error {
 8187            errors.push(error);
 8188        }
 8189    }
 8190
 8191    if let Some(target_id) = state.active_workspace_id {
 8192        window_handle
 8193            .update(cx, |multi_workspace, window, cx| {
 8194                let target_index = multi_workspace
 8195                    .workspaces()
 8196                    .iter()
 8197                    .position(|ws| ws.read(cx).database_id() == Some(target_id));
 8198                if let Some(index) = target_index {
 8199                    multi_workspace.activate_index(index, window, cx);
 8200                } else if !multi_workspace.workspaces().is_empty() {
 8201                    multi_workspace.activate_index(0, window, cx);
 8202                }
 8203            })
 8204            .ok();
 8205    } else {
 8206        window_handle
 8207            .update(cx, |multi_workspace, window, cx| {
 8208                if !multi_workspace.workspaces().is_empty() {
 8209                    multi_workspace.activate_index(0, window, cx);
 8210                }
 8211            })
 8212            .ok();
 8213    }
 8214
 8215    if state.sidebar_open {
 8216        window_handle
 8217            .update(cx, |multi_workspace, _, cx| {
 8218                multi_workspace.open_sidebar(cx);
 8219            })
 8220            .ok();
 8221    }
 8222
 8223    window_handle
 8224        .update(cx, |_, window, _cx| {
 8225            window.activate_window();
 8226        })
 8227        .ok();
 8228
 8229    Ok(MultiWorkspaceRestoreResult {
 8230        window_handle,
 8231        errors,
 8232    })
 8233}
 8234
 8235actions!(
 8236    collab,
 8237    [
 8238        /// Opens the channel notes for the current call.
 8239        ///
 8240        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8241        /// channel in the collab panel.
 8242        ///
 8243        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8244        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8245        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8246        OpenChannelNotes,
 8247        /// Mutes your microphone.
 8248        Mute,
 8249        /// Deafens yourself (mute both microphone and speakers).
 8250        Deafen,
 8251        /// Leaves the current call.
 8252        LeaveCall,
 8253        /// Shares the current project with collaborators.
 8254        ShareProject,
 8255        /// Shares your screen with collaborators.
 8256        ScreenShare,
 8257        /// Copies the current room name and session id for debugging purposes.
 8258        CopyRoomId,
 8259    ]
 8260);
 8261actions!(
 8262    zed,
 8263    [
 8264        /// Opens the Zed log file.
 8265        OpenLog,
 8266        /// Reveals the Zed log file in the system file manager.
 8267        RevealLogInFileManager
 8268    ]
 8269);
 8270
 8271async fn join_channel_internal(
 8272    channel_id: ChannelId,
 8273    app_state: &Arc<AppState>,
 8274    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8275    requesting_workspace: Option<WeakEntity<Workspace>>,
 8276    active_call: &dyn AnyActiveCall,
 8277    cx: &mut AsyncApp,
 8278) -> Result<bool> {
 8279    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8280        if !active_call.is_in_room(cx) {
 8281            return (false, false);
 8282        }
 8283
 8284        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8285        let should_prompt = active_call.is_sharing_project(cx)
 8286            && active_call.has_remote_participants(cx)
 8287            && !already_in_channel;
 8288        (should_prompt, already_in_channel)
 8289    });
 8290
 8291    if already_in_channel {
 8292        let task = cx.update(|cx| {
 8293            if let Some((project, host)) = active_call.most_active_project(cx) {
 8294                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8295            } else {
 8296                None
 8297            }
 8298        });
 8299        if let Some(task) = task {
 8300            task.await?;
 8301        }
 8302        return anyhow::Ok(true);
 8303    }
 8304
 8305    if should_prompt {
 8306        if let Some(multi_workspace) = requesting_window {
 8307            let answer = multi_workspace
 8308                .update(cx, |_, window, cx| {
 8309                    window.prompt(
 8310                        PromptLevel::Warning,
 8311                        "Do you want to switch channels?",
 8312                        Some("Leaving this call will unshare your current project."),
 8313                        &["Yes, Join Channel", "Cancel"],
 8314                        cx,
 8315                    )
 8316                })?
 8317                .await;
 8318
 8319            if answer == Ok(1) {
 8320                return Ok(false);
 8321            }
 8322        } else {
 8323            return Ok(false);
 8324        }
 8325    }
 8326
 8327    let client = cx.update(|cx| active_call.client(cx));
 8328
 8329    let mut client_status = client.status();
 8330
 8331    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8332    'outer: loop {
 8333        let Some(status) = client_status.recv().await else {
 8334            anyhow::bail!("error connecting");
 8335        };
 8336
 8337        match status {
 8338            Status::Connecting
 8339            | Status::Authenticating
 8340            | Status::Authenticated
 8341            | Status::Reconnecting
 8342            | Status::Reauthenticating
 8343            | Status::Reauthenticated => continue,
 8344            Status::Connected { .. } => break 'outer,
 8345            Status::SignedOut | Status::AuthenticationError => {
 8346                return Err(ErrorCode::SignedOut.into());
 8347            }
 8348            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8349            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8350                return Err(ErrorCode::Disconnected.into());
 8351            }
 8352        }
 8353    }
 8354
 8355    let joined = cx
 8356        .update(|cx| active_call.join_channel(channel_id, cx))
 8357        .await?;
 8358
 8359    if !joined {
 8360        return anyhow::Ok(true);
 8361    }
 8362
 8363    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8364
 8365    let task = cx.update(|cx| {
 8366        if let Some((project, host)) = active_call.most_active_project(cx) {
 8367            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8368        }
 8369
 8370        // If you are the first to join a channel, see if you should share your project.
 8371        if !active_call.has_remote_participants(cx)
 8372            && !active_call.local_participant_is_guest(cx)
 8373            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8374        {
 8375            let project = workspace.update(cx, |workspace, cx| {
 8376                let project = workspace.project.read(cx);
 8377
 8378                if !active_call.share_on_join(cx) {
 8379                    return None;
 8380                }
 8381
 8382                if (project.is_local() || project.is_via_remote_server())
 8383                    && project.visible_worktrees(cx).any(|tree| {
 8384                        tree.read(cx)
 8385                            .root_entry()
 8386                            .is_some_and(|entry| entry.is_dir())
 8387                    })
 8388                {
 8389                    Some(workspace.project.clone())
 8390                } else {
 8391                    None
 8392                }
 8393            });
 8394            if let Some(project) = project {
 8395                let share_task = active_call.share_project(project, cx);
 8396                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8397                    share_task.await?;
 8398                    Ok(())
 8399                }));
 8400            }
 8401        }
 8402
 8403        None
 8404    });
 8405    if let Some(task) = task {
 8406        task.await?;
 8407        return anyhow::Ok(true);
 8408    }
 8409    anyhow::Ok(false)
 8410}
 8411
 8412pub fn join_channel(
 8413    channel_id: ChannelId,
 8414    app_state: Arc<AppState>,
 8415    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8416    requesting_workspace: Option<WeakEntity<Workspace>>,
 8417    cx: &mut App,
 8418) -> Task<Result<()>> {
 8419    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8420    cx.spawn(async move |cx| {
 8421        let result = join_channel_internal(
 8422            channel_id,
 8423            &app_state,
 8424            requesting_window,
 8425            requesting_workspace,
 8426            &*active_call.0,
 8427            cx,
 8428        )
 8429        .await;
 8430
 8431        // join channel succeeded, and opened a window
 8432        if matches!(result, Ok(true)) {
 8433            return anyhow::Ok(());
 8434        }
 8435
 8436        // find an existing workspace to focus and show call controls
 8437        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8438        if active_window.is_none() {
 8439            // no open workspaces, make one to show the error in (blergh)
 8440            let (window_handle, _) = cx
 8441                .update(|cx| {
 8442                    Workspace::new_local(
 8443                        vec![],
 8444                        app_state.clone(),
 8445                        requesting_window,
 8446                        None,
 8447                        None,
 8448                        true,
 8449                        cx,
 8450                    )
 8451                })
 8452                .await?;
 8453
 8454            window_handle
 8455                .update(cx, |_, window, _cx| {
 8456                    window.activate_window();
 8457                })
 8458                .ok();
 8459
 8460            if result.is_ok() {
 8461                cx.update(|cx| {
 8462                    cx.dispatch_action(&OpenChannelNotes);
 8463                });
 8464            }
 8465
 8466            active_window = Some(window_handle);
 8467        }
 8468
 8469        if let Err(err) = result {
 8470            log::error!("failed to join channel: {}", err);
 8471            if let Some(active_window) = active_window {
 8472                active_window
 8473                    .update(cx, |_, window, cx| {
 8474                        let detail: SharedString = match err.error_code() {
 8475                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 8476                            ErrorCode::UpgradeRequired => concat!(
 8477                                "Your are running an unsupported version of Zed. ",
 8478                                "Please update to continue."
 8479                            )
 8480                            .into(),
 8481                            ErrorCode::NoSuchChannel => concat!(
 8482                                "No matching channel was found. ",
 8483                                "Please check the link and try again."
 8484                            )
 8485                            .into(),
 8486                            ErrorCode::Forbidden => concat!(
 8487                                "This channel is private, and you do not have access. ",
 8488                                "Please ask someone to add you and try again."
 8489                            )
 8490                            .into(),
 8491                            ErrorCode::Disconnected => {
 8492                                "Please check your internet connection and try again.".into()
 8493                            }
 8494                            _ => format!("{}\n\nPlease try again.", err).into(),
 8495                        };
 8496                        window.prompt(
 8497                            PromptLevel::Critical,
 8498                            "Failed to join channel",
 8499                            Some(&detail),
 8500                            &["Ok"],
 8501                            cx,
 8502                        )
 8503                    })?
 8504                    .await
 8505                    .ok();
 8506            }
 8507        }
 8508
 8509        // return ok, we showed the error to the user.
 8510        anyhow::Ok(())
 8511    })
 8512}
 8513
 8514pub async fn get_any_active_multi_workspace(
 8515    app_state: Arc<AppState>,
 8516    mut cx: AsyncApp,
 8517) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8518    // find an existing workspace to focus and show call controls
 8519    let active_window = activate_any_workspace_window(&mut cx);
 8520    if active_window.is_none() {
 8521        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
 8522            .await?;
 8523    }
 8524    activate_any_workspace_window(&mut cx).context("could not open zed")
 8525}
 8526
 8527fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 8528    cx.update(|cx| {
 8529        if let Some(workspace_window) = cx
 8530            .active_window()
 8531            .and_then(|window| window.downcast::<MultiWorkspace>())
 8532        {
 8533            return Some(workspace_window);
 8534        }
 8535
 8536        for window in cx.windows() {
 8537            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 8538                workspace_window
 8539                    .update(cx, |_, window, _| window.activate_window())
 8540                    .ok();
 8541                return Some(workspace_window);
 8542            }
 8543        }
 8544        None
 8545    })
 8546}
 8547
 8548pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 8549    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 8550}
 8551
 8552pub fn workspace_windows_for_location(
 8553    serialized_location: &SerializedWorkspaceLocation,
 8554    cx: &App,
 8555) -> Vec<WindowHandle<MultiWorkspace>> {
 8556    cx.windows()
 8557        .into_iter()
 8558        .filter_map(|window| window.downcast::<MultiWorkspace>())
 8559        .filter(|multi_workspace| {
 8560            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 8561                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 8562                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 8563                }
 8564                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 8565                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 8566                    a.distro_name == b.distro_name
 8567                }
 8568                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 8569                    a.container_id == b.container_id
 8570                }
 8571                #[cfg(any(test, feature = "test-support"))]
 8572                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 8573                    a.id == b.id
 8574                }
 8575                _ => false,
 8576            };
 8577
 8578            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 8579                multi_workspace.workspaces().iter().any(|workspace| {
 8580                    match workspace.read(cx).workspace_location(cx) {
 8581                        WorkspaceLocation::Location(location, _) => {
 8582                            match (&location, serialized_location) {
 8583                                (
 8584                                    SerializedWorkspaceLocation::Local,
 8585                                    SerializedWorkspaceLocation::Local,
 8586                                ) => true,
 8587                                (
 8588                                    SerializedWorkspaceLocation::Remote(a),
 8589                                    SerializedWorkspaceLocation::Remote(b),
 8590                                ) => same_host(a, b),
 8591                                _ => false,
 8592                            }
 8593                        }
 8594                        _ => false,
 8595                    }
 8596                })
 8597            })
 8598        })
 8599        .collect()
 8600}
 8601
 8602pub async fn find_existing_workspace(
 8603    abs_paths: &[PathBuf],
 8604    open_options: &OpenOptions,
 8605    location: &SerializedWorkspaceLocation,
 8606    cx: &mut AsyncApp,
 8607) -> (
 8608    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 8609    OpenVisible,
 8610) {
 8611    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 8612    let mut open_visible = OpenVisible::All;
 8613    let mut best_match = None;
 8614
 8615    if open_options.open_new_workspace != Some(true) {
 8616        cx.update(|cx| {
 8617            for window in workspace_windows_for_location(location, cx) {
 8618                if let Ok(multi_workspace) = window.read(cx) {
 8619                    for workspace in multi_workspace.workspaces() {
 8620                        let project = workspace.read(cx).project.read(cx);
 8621                        let m = project.visibility_for_paths(
 8622                            abs_paths,
 8623                            open_options.open_new_workspace == None,
 8624                            cx,
 8625                        );
 8626                        if m > best_match {
 8627                            existing = Some((window, workspace.clone()));
 8628                            best_match = m;
 8629                        } else if best_match.is_none()
 8630                            && open_options.open_new_workspace == Some(false)
 8631                        {
 8632                            existing = Some((window, workspace.clone()))
 8633                        }
 8634                    }
 8635                }
 8636            }
 8637        });
 8638
 8639        let all_paths_are_files = existing
 8640            .as_ref()
 8641            .and_then(|(_, target_workspace)| {
 8642                cx.update(|cx| {
 8643                    let workspace = target_workspace.read(cx);
 8644                    let project = workspace.project.read(cx);
 8645                    let path_style = workspace.path_style(cx);
 8646                    Some(!abs_paths.iter().any(|path| {
 8647                        let path = util::paths::SanitizedPath::new(path);
 8648                        project.worktrees(cx).any(|worktree| {
 8649                            let worktree = worktree.read(cx);
 8650                            let abs_path = worktree.abs_path();
 8651                            path_style
 8652                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 8653                                .and_then(|rel| worktree.entry_for_path(&rel))
 8654                                .is_some_and(|e| e.is_dir())
 8655                        })
 8656                    }))
 8657                })
 8658            })
 8659            .unwrap_or(false);
 8660
 8661        if open_options.open_new_workspace.is_none()
 8662            && existing.is_some()
 8663            && open_options.wait
 8664            && all_paths_are_files
 8665        {
 8666            cx.update(|cx| {
 8667                let windows = workspace_windows_for_location(location, cx);
 8668                let window = cx
 8669                    .active_window()
 8670                    .and_then(|window| window.downcast::<MultiWorkspace>())
 8671                    .filter(|window| windows.contains(window))
 8672                    .or_else(|| windows.into_iter().next());
 8673                if let Some(window) = window {
 8674                    if let Ok(multi_workspace) = window.read(cx) {
 8675                        let active_workspace = multi_workspace.workspace().clone();
 8676                        existing = Some((window, active_workspace));
 8677                        open_visible = OpenVisible::None;
 8678                    }
 8679                }
 8680            });
 8681        }
 8682    }
 8683    (existing, open_visible)
 8684}
 8685
 8686#[derive(Default, Clone)]
 8687pub struct OpenOptions {
 8688    pub visible: Option<OpenVisible>,
 8689    pub focus: Option<bool>,
 8690    pub open_new_workspace: Option<bool>,
 8691    pub wait: bool,
 8692    pub replace_window: Option<WindowHandle<MultiWorkspace>>,
 8693    pub env: Option<HashMap<String, String>>,
 8694}
 8695
 8696/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 8697pub fn open_workspace_by_id(
 8698    workspace_id: WorkspaceId,
 8699    app_state: Arc<AppState>,
 8700    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8701    cx: &mut App,
 8702) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 8703    let project_handle = Project::local(
 8704        app_state.client.clone(),
 8705        app_state.node_runtime.clone(),
 8706        app_state.user_store.clone(),
 8707        app_state.languages.clone(),
 8708        app_state.fs.clone(),
 8709        None,
 8710        project::LocalProjectFlags {
 8711            init_worktree_trust: true,
 8712            ..project::LocalProjectFlags::default()
 8713        },
 8714        cx,
 8715    );
 8716
 8717    cx.spawn(async move |cx| {
 8718        let serialized_workspace = persistence::DB
 8719            .workspace_for_id(workspace_id)
 8720            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 8721
 8722        let centered_layout = serialized_workspace.centered_layout;
 8723
 8724        let (window, workspace) = if let Some(window) = requesting_window {
 8725            let workspace = window.update(cx, |multi_workspace, window, cx| {
 8726                let workspace = cx.new(|cx| {
 8727                    let mut workspace = Workspace::new(
 8728                        Some(workspace_id),
 8729                        project_handle.clone(),
 8730                        app_state.clone(),
 8731                        window,
 8732                        cx,
 8733                    );
 8734                    workspace.centered_layout = centered_layout;
 8735                    workspace
 8736                });
 8737                multi_workspace.add_workspace(workspace.clone(), cx);
 8738                workspace
 8739            })?;
 8740            (window, workspace)
 8741        } else {
 8742            let window_bounds_override = window_bounds_env_override();
 8743
 8744            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 8745                (Some(WindowBounds::Windowed(bounds)), None)
 8746            } else if let Some(display) = serialized_workspace.display
 8747                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 8748            {
 8749                (Some(bounds.0), Some(display))
 8750            } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
 8751                (Some(bounds), Some(display))
 8752            } else {
 8753                (None, None)
 8754            };
 8755
 8756            let options = cx.update(|cx| {
 8757                let mut options = (app_state.build_window_options)(display, cx);
 8758                options.window_bounds = window_bounds;
 8759                options
 8760            });
 8761
 8762            let window = cx.open_window(options, {
 8763                let app_state = app_state.clone();
 8764                let project_handle = project_handle.clone();
 8765                move |window, cx| {
 8766                    let workspace = cx.new(|cx| {
 8767                        let mut workspace = Workspace::new(
 8768                            Some(workspace_id),
 8769                            project_handle,
 8770                            app_state,
 8771                            window,
 8772                            cx,
 8773                        );
 8774                        workspace.centered_layout = centered_layout;
 8775                        workspace
 8776                    });
 8777                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 8778                }
 8779            })?;
 8780
 8781            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 8782                multi_workspace.workspace().clone()
 8783            })?;
 8784
 8785            (window, workspace)
 8786        };
 8787
 8788        notify_if_database_failed(window, cx);
 8789
 8790        // Restore items from the serialized workspace
 8791        window
 8792            .update(cx, |_, window, cx| {
 8793                workspace.update(cx, |_workspace, cx| {
 8794                    open_items(Some(serialized_workspace), vec![], window, cx)
 8795                })
 8796            })?
 8797            .await?;
 8798
 8799        window.update(cx, |_, window, cx| {
 8800            workspace.update(cx, |workspace, cx| {
 8801                workspace.serialize_workspace(window, cx);
 8802            });
 8803        })?;
 8804
 8805        Ok(window)
 8806    })
 8807}
 8808
 8809#[allow(clippy::type_complexity)]
 8810pub fn open_paths(
 8811    abs_paths: &[PathBuf],
 8812    app_state: Arc<AppState>,
 8813    open_options: OpenOptions,
 8814    cx: &mut App,
 8815) -> Task<
 8816    anyhow::Result<(
 8817        WindowHandle<MultiWorkspace>,
 8818        Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 8819    )>,
 8820> {
 8821    let abs_paths = abs_paths.to_vec();
 8822    #[cfg(target_os = "windows")]
 8823    let wsl_path = abs_paths
 8824        .iter()
 8825        .find_map(|p| util::paths::WslPath::from_path(p));
 8826
 8827    cx.spawn(async move |cx| {
 8828        let (mut existing, mut open_visible) = find_existing_workspace(
 8829            &abs_paths,
 8830            &open_options,
 8831            &SerializedWorkspaceLocation::Local,
 8832            cx,
 8833        )
 8834        .await;
 8835
 8836        // Fallback: if no workspace contains the paths and all paths are files,
 8837        // prefer an existing local workspace window (active window first).
 8838        if open_options.open_new_workspace.is_none() && existing.is_none() {
 8839            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 8840            let all_metadatas = futures::future::join_all(all_paths)
 8841                .await
 8842                .into_iter()
 8843                .filter_map(|result| result.ok().flatten())
 8844                .collect::<Vec<_>>();
 8845
 8846            if all_metadatas.iter().all(|file| !file.is_dir) {
 8847                cx.update(|cx| {
 8848                    let windows = workspace_windows_for_location(
 8849                        &SerializedWorkspaceLocation::Local,
 8850                        cx,
 8851                    );
 8852                    let window = cx
 8853                        .active_window()
 8854                        .and_then(|window| window.downcast::<MultiWorkspace>())
 8855                        .filter(|window| windows.contains(window))
 8856                        .or_else(|| windows.into_iter().next());
 8857                    if let Some(window) = window {
 8858                        if let Ok(multi_workspace) = window.read(cx) {
 8859                            let active_workspace = multi_workspace.workspace().clone();
 8860                            existing = Some((window, active_workspace));
 8861                            open_visible = OpenVisible::None;
 8862                        }
 8863                    }
 8864                });
 8865            }
 8866        }
 8867
 8868        let result = if let Some((existing, target_workspace)) = existing {
 8869            let open_task = existing
 8870                .update(cx, |multi_workspace, window, cx| {
 8871                    window.activate_window();
 8872                    multi_workspace.activate(target_workspace.clone(), cx);
 8873                    target_workspace.update(cx, |workspace, cx| {
 8874                        workspace.open_paths(
 8875                            abs_paths,
 8876                            OpenOptions {
 8877                                visible: Some(open_visible),
 8878                                ..Default::default()
 8879                            },
 8880                            None,
 8881                            window,
 8882                            cx,
 8883                        )
 8884                    })
 8885                })?
 8886                .await;
 8887
 8888            _ = existing.update(cx, |multi_workspace, _, cx| {
 8889                let workspace = multi_workspace.workspace().clone();
 8890                workspace.update(cx, |workspace, cx| {
 8891                    for item in open_task.iter().flatten() {
 8892                        if let Err(e) = item {
 8893                            workspace.show_error(&e, cx);
 8894                        }
 8895                    }
 8896                });
 8897            });
 8898
 8899            Ok((existing, open_task))
 8900        } else {
 8901            let result = cx
 8902                .update(move |cx| {
 8903                    Workspace::new_local(
 8904                        abs_paths,
 8905                        app_state.clone(),
 8906                        open_options.replace_window,
 8907                        open_options.env,
 8908                        None,
 8909                        true,
 8910                        cx,
 8911                    )
 8912                })
 8913                .await;
 8914
 8915            if let Ok((ref window_handle, _)) = result {
 8916                window_handle
 8917                    .update(cx, |_, window, _cx| {
 8918                        window.activate_window();
 8919                    })
 8920                    .log_err();
 8921            }
 8922
 8923            result
 8924        };
 8925
 8926        #[cfg(target_os = "windows")]
 8927        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 8928            && let Ok((multi_workspace_window, _)) = &result
 8929        {
 8930            multi_workspace_window
 8931                .update(cx, move |multi_workspace, _window, cx| {
 8932                    struct OpenInWsl;
 8933                    let workspace = multi_workspace.workspace().clone();
 8934                    workspace.update(cx, |workspace, cx| {
 8935                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 8936                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 8937                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 8938                            cx.new(move |cx| {
 8939                                MessageNotification::new(msg, cx)
 8940                                    .primary_message("Open in WSL")
 8941                                    .primary_icon(IconName::FolderOpen)
 8942                                    .primary_on_click(move |window, cx| {
 8943                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 8944                                                distro: remote::WslConnectionOptions {
 8945                                                        distro_name: distro.clone(),
 8946                                                    user: None,
 8947                                                },
 8948                                                paths: vec![path.clone().into()],
 8949                                            }), cx)
 8950                                    })
 8951                            })
 8952                        });
 8953                    });
 8954                })
 8955                .unwrap();
 8956        };
 8957        result
 8958    })
 8959}
 8960
 8961pub fn open_new(
 8962    open_options: OpenOptions,
 8963    app_state: Arc<AppState>,
 8964    cx: &mut App,
 8965    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 8966) -> Task<anyhow::Result<()>> {
 8967    let task = Workspace::new_local(
 8968        Vec::new(),
 8969        app_state,
 8970        open_options.replace_window,
 8971        open_options.env,
 8972        Some(Box::new(init)),
 8973        true,
 8974        cx,
 8975    );
 8976    cx.spawn(async move |cx| {
 8977        let (window, _opened_paths) = task.await?;
 8978        window
 8979            .update(cx, |_, window, _cx| {
 8980                window.activate_window();
 8981            })
 8982            .ok();
 8983        Ok(())
 8984    })
 8985}
 8986
 8987pub fn create_and_open_local_file(
 8988    path: &'static Path,
 8989    window: &mut Window,
 8990    cx: &mut Context<Workspace>,
 8991    default_content: impl 'static + Send + FnOnce() -> Rope,
 8992) -> Task<Result<Box<dyn ItemHandle>>> {
 8993    cx.spawn_in(window, async move |workspace, cx| {
 8994        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 8995        if !fs.is_file(path).await {
 8996            fs.create_file(path, Default::default()).await?;
 8997            fs.save(path, &default_content(), Default::default())
 8998                .await?;
 8999        }
 9000
 9001        workspace
 9002            .update_in(cx, |workspace, window, cx| {
 9003                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9004                    let path = workspace
 9005                        .project
 9006                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9007                    cx.spawn_in(window, async move |workspace, cx| {
 9008                        let path = path.await?;
 9009                        let mut items = workspace
 9010                            .update_in(cx, |workspace, window, cx| {
 9011                                workspace.open_paths(
 9012                                    vec![path.to_path_buf()],
 9013                                    OpenOptions {
 9014                                        visible: Some(OpenVisible::None),
 9015                                        ..Default::default()
 9016                                    },
 9017                                    None,
 9018                                    window,
 9019                                    cx,
 9020                                )
 9021                            })?
 9022                            .await;
 9023                        let item = items.pop().flatten();
 9024                        item.with_context(|| format!("path {path:?} is not a file"))?
 9025                    })
 9026                })
 9027            })?
 9028            .await?
 9029            .await
 9030    })
 9031}
 9032
 9033pub fn open_remote_project_with_new_connection(
 9034    window: WindowHandle<MultiWorkspace>,
 9035    remote_connection: Arc<dyn RemoteConnection>,
 9036    cancel_rx: oneshot::Receiver<()>,
 9037    delegate: Arc<dyn RemoteClientDelegate>,
 9038    app_state: Arc<AppState>,
 9039    paths: Vec<PathBuf>,
 9040    cx: &mut App,
 9041) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9042    cx.spawn(async move |cx| {
 9043        let (workspace_id, serialized_workspace) =
 9044            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9045                .await?;
 9046
 9047        let session = match cx
 9048            .update(|cx| {
 9049                remote::RemoteClient::new(
 9050                    ConnectionIdentifier::Workspace(workspace_id.0),
 9051                    remote_connection,
 9052                    cancel_rx,
 9053                    delegate,
 9054                    cx,
 9055                )
 9056            })
 9057            .await?
 9058        {
 9059            Some(result) => result,
 9060            None => return Ok(Vec::new()),
 9061        };
 9062
 9063        let project = cx.update(|cx| {
 9064            project::Project::remote(
 9065                session,
 9066                app_state.client.clone(),
 9067                app_state.node_runtime.clone(),
 9068                app_state.user_store.clone(),
 9069                app_state.languages.clone(),
 9070                app_state.fs.clone(),
 9071                true,
 9072                cx,
 9073            )
 9074        });
 9075
 9076        open_remote_project_inner(
 9077            project,
 9078            paths,
 9079            workspace_id,
 9080            serialized_workspace,
 9081            app_state,
 9082            window,
 9083            cx,
 9084        )
 9085        .await
 9086    })
 9087}
 9088
 9089pub fn open_remote_project_with_existing_connection(
 9090    connection_options: RemoteConnectionOptions,
 9091    project: Entity<Project>,
 9092    paths: Vec<PathBuf>,
 9093    app_state: Arc<AppState>,
 9094    window: WindowHandle<MultiWorkspace>,
 9095    cx: &mut AsyncApp,
 9096) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9097    cx.spawn(async move |cx| {
 9098        let (workspace_id, serialized_workspace) =
 9099            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9100
 9101        open_remote_project_inner(
 9102            project,
 9103            paths,
 9104            workspace_id,
 9105            serialized_workspace,
 9106            app_state,
 9107            window,
 9108            cx,
 9109        )
 9110        .await
 9111    })
 9112}
 9113
 9114async fn open_remote_project_inner(
 9115    project: Entity<Project>,
 9116    paths: Vec<PathBuf>,
 9117    workspace_id: WorkspaceId,
 9118    serialized_workspace: Option<SerializedWorkspace>,
 9119    app_state: Arc<AppState>,
 9120    window: WindowHandle<MultiWorkspace>,
 9121    cx: &mut AsyncApp,
 9122) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9123    let toolchains = DB.toolchains(workspace_id).await?;
 9124    for (toolchain, worktree_path, path) in toolchains {
 9125        project
 9126            .update(cx, |this, cx| {
 9127                let Some(worktree_id) =
 9128                    this.find_worktree(&worktree_path, cx)
 9129                        .and_then(|(worktree, rel_path)| {
 9130                            if rel_path.is_empty() {
 9131                                Some(worktree.read(cx).id())
 9132                            } else {
 9133                                None
 9134                            }
 9135                        })
 9136                else {
 9137                    return Task::ready(None);
 9138                };
 9139
 9140                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9141            })
 9142            .await;
 9143    }
 9144    let mut project_paths_to_open = vec![];
 9145    let mut project_path_errors = vec![];
 9146
 9147    for path in paths {
 9148        let result = cx
 9149            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9150            .await;
 9151        match result {
 9152            Ok((_, project_path)) => {
 9153                project_paths_to_open.push((path.clone(), Some(project_path)));
 9154            }
 9155            Err(error) => {
 9156                project_path_errors.push(error);
 9157            }
 9158        };
 9159    }
 9160
 9161    if project_paths_to_open.is_empty() {
 9162        return Err(project_path_errors.pop().context("no paths given")?);
 9163    }
 9164
 9165    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9166        telemetry::event!("SSH Project Opened");
 9167
 9168        let new_workspace = cx.new(|cx| {
 9169            let mut workspace =
 9170                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9171            workspace.update_history(cx);
 9172
 9173            if let Some(ref serialized) = serialized_workspace {
 9174                workspace.centered_layout = serialized.centered_layout;
 9175            }
 9176
 9177            workspace
 9178        });
 9179
 9180        multi_workspace.activate(new_workspace.clone(), cx);
 9181        new_workspace
 9182    })?;
 9183
 9184    let items = window
 9185        .update(cx, |_, window, cx| {
 9186            window.activate_window();
 9187            workspace.update(cx, |_workspace, cx| {
 9188                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9189            })
 9190        })?
 9191        .await?;
 9192
 9193    workspace.update(cx, |workspace, cx| {
 9194        for error in project_path_errors {
 9195            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9196                if let Some(path) = error.error_tag("path") {
 9197                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9198                }
 9199            } else {
 9200                workspace.show_error(&error, cx)
 9201            }
 9202        }
 9203    });
 9204
 9205    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9206}
 9207
 9208fn deserialize_remote_project(
 9209    connection_options: RemoteConnectionOptions,
 9210    paths: Vec<PathBuf>,
 9211    cx: &AsyncApp,
 9212) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9213    cx.background_spawn(async move {
 9214        let remote_connection_id = persistence::DB
 9215            .get_or_create_remote_connection(connection_options)
 9216            .await?;
 9217
 9218        let serialized_workspace =
 9219            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 9220
 9221        let workspace_id = if let Some(workspace_id) =
 9222            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9223        {
 9224            workspace_id
 9225        } else {
 9226            persistence::DB.next_id().await?
 9227        };
 9228
 9229        Ok((workspace_id, serialized_workspace))
 9230    })
 9231}
 9232
 9233pub fn join_in_room_project(
 9234    project_id: u64,
 9235    follow_user_id: u64,
 9236    app_state: Arc<AppState>,
 9237    cx: &mut App,
 9238) -> Task<Result<()>> {
 9239    let windows = cx.windows();
 9240    cx.spawn(async move |cx| {
 9241        let existing_window_and_workspace: Option<(
 9242            WindowHandle<MultiWorkspace>,
 9243            Entity<Workspace>,
 9244        )> = windows.into_iter().find_map(|window_handle| {
 9245            window_handle
 9246                .downcast::<MultiWorkspace>()
 9247                .and_then(|window_handle| {
 9248                    window_handle
 9249                        .update(cx, |multi_workspace, _window, cx| {
 9250                            for workspace in multi_workspace.workspaces() {
 9251                                if workspace.read(cx).project().read(cx).remote_id()
 9252                                    == Some(project_id)
 9253                                {
 9254                                    return Some((window_handle, workspace.clone()));
 9255                                }
 9256                            }
 9257                            None
 9258                        })
 9259                        .unwrap_or(None)
 9260                })
 9261        });
 9262
 9263        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9264            existing_window_and_workspace
 9265        {
 9266            existing_window
 9267                .update(cx, |multi_workspace, _, cx| {
 9268                    multi_workspace.activate(target_workspace, cx);
 9269                })
 9270                .ok();
 9271            existing_window
 9272        } else {
 9273            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9274            let project = cx
 9275                .update(|cx| {
 9276                    active_call.0.join_project(
 9277                        project_id,
 9278                        app_state.languages.clone(),
 9279                        app_state.fs.clone(),
 9280                        cx,
 9281                    )
 9282                })
 9283                .await?;
 9284
 9285            let window_bounds_override = window_bounds_env_override();
 9286            cx.update(|cx| {
 9287                let mut options = (app_state.build_window_options)(None, cx);
 9288                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9289                cx.open_window(options, |window, cx| {
 9290                    let workspace = cx.new(|cx| {
 9291                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9292                    });
 9293                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9294                })
 9295            })?
 9296        };
 9297
 9298        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9299            cx.activate(true);
 9300            window.activate_window();
 9301
 9302            // We set the active workspace above, so this is the correct workspace.
 9303            let workspace = multi_workspace.workspace().clone();
 9304            workspace.update(cx, |workspace, cx| {
 9305                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9306                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9307                    .or_else(|| {
 9308                        // If we couldn't follow the given user, follow the host instead.
 9309                        let collaborator = workspace
 9310                            .project()
 9311                            .read(cx)
 9312                            .collaborators()
 9313                            .values()
 9314                            .find(|collaborator| collaborator.is_host)?;
 9315                        Some(collaborator.peer_id)
 9316                    });
 9317
 9318                if let Some(follow_peer_id) = follow_peer_id {
 9319                    workspace.follow(follow_peer_id, window, cx);
 9320                }
 9321            });
 9322        })?;
 9323
 9324        anyhow::Ok(())
 9325    })
 9326}
 9327
 9328pub fn reload(cx: &mut App) {
 9329    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9330    let mut workspace_windows = cx
 9331        .windows()
 9332        .into_iter()
 9333        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9334        .collect::<Vec<_>>();
 9335
 9336    // If multiple windows have unsaved changes, and need a save prompt,
 9337    // prompt in the active window before switching to a different window.
 9338    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9339
 9340    let mut prompt = None;
 9341    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9342        prompt = window
 9343            .update(cx, |_, window, cx| {
 9344                window.prompt(
 9345                    PromptLevel::Info,
 9346                    "Are you sure you want to restart?",
 9347                    None,
 9348                    &["Restart", "Cancel"],
 9349                    cx,
 9350                )
 9351            })
 9352            .ok();
 9353    }
 9354
 9355    cx.spawn(async move |cx| {
 9356        if let Some(prompt) = prompt {
 9357            let answer = prompt.await?;
 9358            if answer != 0 {
 9359                return anyhow::Ok(());
 9360            }
 9361        }
 9362
 9363        // If the user cancels any save prompt, then keep the app open.
 9364        for window in workspace_windows {
 9365            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9366                let workspace = multi_workspace.workspace().clone();
 9367                workspace.update(cx, |workspace, cx| {
 9368                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9369                })
 9370            }) && !should_close.await?
 9371            {
 9372                return anyhow::Ok(());
 9373            }
 9374        }
 9375        cx.update(|cx| cx.restart());
 9376        anyhow::Ok(())
 9377    })
 9378    .detach_and_log_err(cx);
 9379}
 9380
 9381fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9382    let mut parts = value.split(',');
 9383    let x: usize = parts.next()?.parse().ok()?;
 9384    let y: usize = parts.next()?.parse().ok()?;
 9385    Some(point(px(x as f32), px(y as f32)))
 9386}
 9387
 9388fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9389    let mut parts = value.split(',');
 9390    let width: usize = parts.next()?.parse().ok()?;
 9391    let height: usize = parts.next()?.parse().ok()?;
 9392    Some(size(px(width as f32), px(height as f32)))
 9393}
 9394
 9395/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9396/// appropriate.
 9397///
 9398/// The `border_radius_tiling` parameter allows overriding which corners get
 9399/// rounded, independently of the actual window tiling state. This is used
 9400/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9401/// we want square corners on the left (so the sidebar appears flush with the
 9402/// window edge) but we still need the shadow padding for proper visual
 9403/// appearance. Unlike actual window tiling, this only affects border radius -
 9404/// not padding or shadows.
 9405pub fn client_side_decorations(
 9406    element: impl IntoElement,
 9407    window: &mut Window,
 9408    cx: &mut App,
 9409    border_radius_tiling: Tiling,
 9410) -> Stateful<Div> {
 9411    const BORDER_SIZE: Pixels = px(1.0);
 9412    let decorations = window.window_decorations();
 9413    let tiling = match decorations {
 9414        Decorations::Server => Tiling::default(),
 9415        Decorations::Client { tiling } => tiling,
 9416    };
 9417
 9418    match decorations {
 9419        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9420        Decorations::Server => window.set_client_inset(px(0.0)),
 9421    }
 9422
 9423    struct GlobalResizeEdge(ResizeEdge);
 9424    impl Global for GlobalResizeEdge {}
 9425
 9426    div()
 9427        .id("window-backdrop")
 9428        .bg(transparent_black())
 9429        .map(|div| match decorations {
 9430            Decorations::Server => div,
 9431            Decorations::Client { .. } => div
 9432                .when(
 9433                    !(tiling.top
 9434                        || tiling.right
 9435                        || border_radius_tiling.top
 9436                        || border_radius_tiling.right),
 9437                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9438                )
 9439                .when(
 9440                    !(tiling.top
 9441                        || tiling.left
 9442                        || border_radius_tiling.top
 9443                        || border_radius_tiling.left),
 9444                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9445                )
 9446                .when(
 9447                    !(tiling.bottom
 9448                        || tiling.right
 9449                        || border_radius_tiling.bottom
 9450                        || border_radius_tiling.right),
 9451                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9452                )
 9453                .when(
 9454                    !(tiling.bottom
 9455                        || tiling.left
 9456                        || border_radius_tiling.bottom
 9457                        || border_radius_tiling.left),
 9458                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9459                )
 9460                .when(!tiling.top, |div| {
 9461                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9462                })
 9463                .when(!tiling.bottom, |div| {
 9464                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9465                })
 9466                .when(!tiling.left, |div| {
 9467                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9468                })
 9469                .when(!tiling.right, |div| {
 9470                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9471                })
 9472                .on_mouse_move(move |e, window, cx| {
 9473                    let size = window.window_bounds().get_bounds().size;
 9474                    let pos = e.position;
 9475
 9476                    let new_edge =
 9477                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 9478
 9479                    let edge = cx.try_global::<GlobalResizeEdge>();
 9480                    if new_edge != edge.map(|edge| edge.0) {
 9481                        window
 9482                            .window_handle()
 9483                            .update(cx, |workspace, _, cx| {
 9484                                cx.notify(workspace.entity_id());
 9485                            })
 9486                            .ok();
 9487                    }
 9488                })
 9489                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 9490                    let size = window.window_bounds().get_bounds().size;
 9491                    let pos = e.position;
 9492
 9493                    let edge = match resize_edge(
 9494                        pos,
 9495                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 9496                        size,
 9497                        tiling,
 9498                    ) {
 9499                        Some(value) => value,
 9500                        None => return,
 9501                    };
 9502
 9503                    window.start_window_resize(edge);
 9504                }),
 9505        })
 9506        .size_full()
 9507        .child(
 9508            div()
 9509                .cursor(CursorStyle::Arrow)
 9510                .map(|div| match decorations {
 9511                    Decorations::Server => div,
 9512                    Decorations::Client { .. } => div
 9513                        .border_color(cx.theme().colors().border)
 9514                        .when(
 9515                            !(tiling.top
 9516                                || tiling.right
 9517                                || border_radius_tiling.top
 9518                                || border_radius_tiling.right),
 9519                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9520                        )
 9521                        .when(
 9522                            !(tiling.top
 9523                                || tiling.left
 9524                                || border_radius_tiling.top
 9525                                || border_radius_tiling.left),
 9526                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9527                        )
 9528                        .when(
 9529                            !(tiling.bottom
 9530                                || tiling.right
 9531                                || border_radius_tiling.bottom
 9532                                || border_radius_tiling.right),
 9533                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9534                        )
 9535                        .when(
 9536                            !(tiling.bottom
 9537                                || tiling.left
 9538                                || border_radius_tiling.bottom
 9539                                || border_radius_tiling.left),
 9540                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9541                        )
 9542                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 9543                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 9544                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 9545                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 9546                        .when(!tiling.is_tiled(), |div| {
 9547                            div.shadow(vec![gpui::BoxShadow {
 9548                                color: Hsla {
 9549                                    h: 0.,
 9550                                    s: 0.,
 9551                                    l: 0.,
 9552                                    a: 0.4,
 9553                                },
 9554                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 9555                                spread_radius: px(0.),
 9556                                offset: point(px(0.0), px(0.0)),
 9557                            }])
 9558                        }),
 9559                })
 9560                .on_mouse_move(|_e, _, cx| {
 9561                    cx.stop_propagation();
 9562                })
 9563                .size_full()
 9564                .child(element),
 9565        )
 9566        .map(|div| match decorations {
 9567            Decorations::Server => div,
 9568            Decorations::Client { tiling, .. } => div.child(
 9569                canvas(
 9570                    |_bounds, window, _| {
 9571                        window.insert_hitbox(
 9572                            Bounds::new(
 9573                                point(px(0.0), px(0.0)),
 9574                                window.window_bounds().get_bounds().size,
 9575                            ),
 9576                            HitboxBehavior::Normal,
 9577                        )
 9578                    },
 9579                    move |_bounds, hitbox, window, cx| {
 9580                        let mouse = window.mouse_position();
 9581                        let size = window.window_bounds().get_bounds().size;
 9582                        let Some(edge) =
 9583                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 9584                        else {
 9585                            return;
 9586                        };
 9587                        cx.set_global(GlobalResizeEdge(edge));
 9588                        window.set_cursor_style(
 9589                            match edge {
 9590                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 9591                                ResizeEdge::Left | ResizeEdge::Right => {
 9592                                    CursorStyle::ResizeLeftRight
 9593                                }
 9594                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 9595                                    CursorStyle::ResizeUpLeftDownRight
 9596                                }
 9597                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 9598                                    CursorStyle::ResizeUpRightDownLeft
 9599                                }
 9600                            },
 9601                            &hitbox,
 9602                        );
 9603                    },
 9604                )
 9605                .size_full()
 9606                .absolute(),
 9607            ),
 9608        })
 9609}
 9610
 9611fn resize_edge(
 9612    pos: Point<Pixels>,
 9613    shadow_size: Pixels,
 9614    window_size: Size<Pixels>,
 9615    tiling: Tiling,
 9616) -> Option<ResizeEdge> {
 9617    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 9618    if bounds.contains(&pos) {
 9619        return None;
 9620    }
 9621
 9622    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 9623    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 9624    if !tiling.top && top_left_bounds.contains(&pos) {
 9625        return Some(ResizeEdge::TopLeft);
 9626    }
 9627
 9628    let top_right_bounds = Bounds::new(
 9629        Point::new(window_size.width - corner_size.width, px(0.)),
 9630        corner_size,
 9631    );
 9632    if !tiling.top && top_right_bounds.contains(&pos) {
 9633        return Some(ResizeEdge::TopRight);
 9634    }
 9635
 9636    let bottom_left_bounds = Bounds::new(
 9637        Point::new(px(0.), window_size.height - corner_size.height),
 9638        corner_size,
 9639    );
 9640    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 9641        return Some(ResizeEdge::BottomLeft);
 9642    }
 9643
 9644    let bottom_right_bounds = Bounds::new(
 9645        Point::new(
 9646            window_size.width - corner_size.width,
 9647            window_size.height - corner_size.height,
 9648        ),
 9649        corner_size,
 9650    );
 9651    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 9652        return Some(ResizeEdge::BottomRight);
 9653    }
 9654
 9655    if !tiling.top && pos.y < shadow_size {
 9656        Some(ResizeEdge::Top)
 9657    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 9658        Some(ResizeEdge::Bottom)
 9659    } else if !tiling.left && pos.x < shadow_size {
 9660        Some(ResizeEdge::Left)
 9661    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 9662        Some(ResizeEdge::Right)
 9663    } else {
 9664        None
 9665    }
 9666}
 9667
 9668fn join_pane_into_active(
 9669    active_pane: &Entity<Pane>,
 9670    pane: &Entity<Pane>,
 9671    window: &mut Window,
 9672    cx: &mut App,
 9673) {
 9674    if pane == active_pane {
 9675    } else if pane.read(cx).items_len() == 0 {
 9676        pane.update(cx, |_, cx| {
 9677            cx.emit(pane::Event::Remove {
 9678                focus_on_pane: None,
 9679            });
 9680        })
 9681    } else {
 9682        move_all_items(pane, active_pane, window, cx);
 9683    }
 9684}
 9685
 9686fn move_all_items(
 9687    from_pane: &Entity<Pane>,
 9688    to_pane: &Entity<Pane>,
 9689    window: &mut Window,
 9690    cx: &mut App,
 9691) {
 9692    let destination_is_different = from_pane != to_pane;
 9693    let mut moved_items = 0;
 9694    for (item_ix, item_handle) in from_pane
 9695        .read(cx)
 9696        .items()
 9697        .enumerate()
 9698        .map(|(ix, item)| (ix, item.clone()))
 9699        .collect::<Vec<_>>()
 9700    {
 9701        let ix = item_ix - moved_items;
 9702        if destination_is_different {
 9703            // Close item from previous pane
 9704            from_pane.update(cx, |source, cx| {
 9705                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 9706            });
 9707            moved_items += 1;
 9708        }
 9709
 9710        // This automatically removes duplicate items in the pane
 9711        to_pane.update(cx, |destination, cx| {
 9712            destination.add_item(item_handle, true, true, None, window, cx);
 9713            window.focus(&destination.focus_handle(cx), cx)
 9714        });
 9715    }
 9716}
 9717
 9718pub fn move_item(
 9719    source: &Entity<Pane>,
 9720    destination: &Entity<Pane>,
 9721    item_id_to_move: EntityId,
 9722    destination_index: usize,
 9723    activate: bool,
 9724    window: &mut Window,
 9725    cx: &mut App,
 9726) {
 9727    let Some((item_ix, item_handle)) = source
 9728        .read(cx)
 9729        .items()
 9730        .enumerate()
 9731        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 9732        .map(|(ix, item)| (ix, item.clone()))
 9733    else {
 9734        // Tab was closed during drag
 9735        return;
 9736    };
 9737
 9738    if source != destination {
 9739        // Close item from previous pane
 9740        source.update(cx, |source, cx| {
 9741            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 9742        });
 9743    }
 9744
 9745    // This automatically removes duplicate items in the pane
 9746    destination.update(cx, |destination, cx| {
 9747        destination.add_item_inner(
 9748            item_handle,
 9749            activate,
 9750            activate,
 9751            activate,
 9752            Some(destination_index),
 9753            window,
 9754            cx,
 9755        );
 9756        if activate {
 9757            window.focus(&destination.focus_handle(cx), cx)
 9758        }
 9759    });
 9760}
 9761
 9762pub fn move_active_item(
 9763    source: &Entity<Pane>,
 9764    destination: &Entity<Pane>,
 9765    focus_destination: bool,
 9766    close_if_empty: bool,
 9767    window: &mut Window,
 9768    cx: &mut App,
 9769) {
 9770    if source == destination {
 9771        return;
 9772    }
 9773    let Some(active_item) = source.read(cx).active_item() else {
 9774        return;
 9775    };
 9776    source.update(cx, |source_pane, cx| {
 9777        let item_id = active_item.item_id();
 9778        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 9779        destination.update(cx, |target_pane, cx| {
 9780            target_pane.add_item(
 9781                active_item,
 9782                focus_destination,
 9783                focus_destination,
 9784                Some(target_pane.items_len()),
 9785                window,
 9786                cx,
 9787            );
 9788        });
 9789    });
 9790}
 9791
 9792pub fn clone_active_item(
 9793    workspace_id: Option<WorkspaceId>,
 9794    source: &Entity<Pane>,
 9795    destination: &Entity<Pane>,
 9796    focus_destination: bool,
 9797    window: &mut Window,
 9798    cx: &mut App,
 9799) {
 9800    if source == destination {
 9801        return;
 9802    }
 9803    let Some(active_item) = source.read(cx).active_item() else {
 9804        return;
 9805    };
 9806    if !active_item.can_split(cx) {
 9807        return;
 9808    }
 9809    let destination = destination.downgrade();
 9810    let task = active_item.clone_on_split(workspace_id, window, cx);
 9811    window
 9812        .spawn(cx, async move |cx| {
 9813            let Some(clone) = task.await else {
 9814                return;
 9815            };
 9816            destination
 9817                .update_in(cx, |target_pane, window, cx| {
 9818                    target_pane.add_item(
 9819                        clone,
 9820                        focus_destination,
 9821                        focus_destination,
 9822                        Some(target_pane.items_len()),
 9823                        window,
 9824                        cx,
 9825                    );
 9826                })
 9827                .log_err();
 9828        })
 9829        .detach();
 9830}
 9831
 9832#[derive(Debug)]
 9833pub struct WorkspacePosition {
 9834    pub window_bounds: Option<WindowBounds>,
 9835    pub display: Option<Uuid>,
 9836    pub centered_layout: bool,
 9837}
 9838
 9839pub fn remote_workspace_position_from_db(
 9840    connection_options: RemoteConnectionOptions,
 9841    paths_to_open: &[PathBuf],
 9842    cx: &App,
 9843) -> Task<Result<WorkspacePosition>> {
 9844    let paths = paths_to_open.to_vec();
 9845
 9846    cx.background_spawn(async move {
 9847        let remote_connection_id = persistence::DB
 9848            .get_or_create_remote_connection(connection_options)
 9849            .await
 9850            .context("fetching serialized ssh project")?;
 9851        let serialized_workspace =
 9852            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 9853
 9854        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
 9855            (Some(WindowBounds::Windowed(bounds)), None)
 9856        } else {
 9857            let restorable_bounds = serialized_workspace
 9858                .as_ref()
 9859                .and_then(|workspace| {
 9860                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
 9861                })
 9862                .or_else(|| persistence::read_default_window_bounds());
 9863
 9864            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
 9865                (Some(serialized_bounds), Some(serialized_display))
 9866            } else {
 9867                (None, None)
 9868            }
 9869        };
 9870
 9871        let centered_layout = serialized_workspace
 9872            .as_ref()
 9873            .map(|w| w.centered_layout)
 9874            .unwrap_or(false);
 9875
 9876        Ok(WorkspacePosition {
 9877            window_bounds,
 9878            display,
 9879            centered_layout,
 9880        })
 9881    })
 9882}
 9883
 9884pub fn with_active_or_new_workspace(
 9885    cx: &mut App,
 9886    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
 9887) {
 9888    match cx
 9889        .active_window()
 9890        .and_then(|w| w.downcast::<MultiWorkspace>())
 9891    {
 9892        Some(multi_workspace) => {
 9893            cx.defer(move |cx| {
 9894                multi_workspace
 9895                    .update(cx, |multi_workspace, window, cx| {
 9896                        let workspace = multi_workspace.workspace().clone();
 9897                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
 9898                    })
 9899                    .log_err();
 9900            });
 9901        }
 9902        None => {
 9903            let app_state = AppState::global(cx);
 9904            if let Some(app_state) = app_state.upgrade() {
 9905                open_new(
 9906                    OpenOptions::default(),
 9907                    app_state,
 9908                    cx,
 9909                    move |workspace, window, cx| f(workspace, window, cx),
 9910                )
 9911                .detach_and_log_err(cx);
 9912            }
 9913        }
 9914    }
 9915}
 9916
 9917#[cfg(test)]
 9918mod tests {
 9919    use std::{cell::RefCell, rc::Rc};
 9920
 9921    use super::*;
 9922    use crate::{
 9923        dock::{PanelEvent, test::TestPanel},
 9924        item::{
 9925            ItemBufferKind, ItemEvent,
 9926            test::{TestItem, TestProjectItem},
 9927        },
 9928    };
 9929    use fs::FakeFs;
 9930    use gpui::{
 9931        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
 9932        UpdateGlobal, VisualTestContext, px,
 9933    };
 9934    use project::{Project, ProjectEntryId};
 9935    use serde_json::json;
 9936    use settings::SettingsStore;
 9937    use util::rel_path::rel_path;
 9938
 9939    #[gpui::test]
 9940    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
 9941        init_test(cx);
 9942
 9943        let fs = FakeFs::new(cx.executor());
 9944        let project = Project::test(fs, [], cx).await;
 9945        let (workspace, cx) =
 9946            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 9947
 9948        // Adding an item with no ambiguity renders the tab without detail.
 9949        let item1 = cx.new(|cx| {
 9950            let mut item = TestItem::new(cx);
 9951            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
 9952            item
 9953        });
 9954        workspace.update_in(cx, |workspace, window, cx| {
 9955            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 9956        });
 9957        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
 9958
 9959        // Adding an item that creates ambiguity increases the level of detail on
 9960        // both tabs.
 9961        let item2 = cx.new_window_entity(|_window, cx| {
 9962            let mut item = TestItem::new(cx);
 9963            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 9964            item
 9965        });
 9966        workspace.update_in(cx, |workspace, window, cx| {
 9967            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9968        });
 9969        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9970        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9971
 9972        // Adding an item that creates ambiguity increases the level of detail only
 9973        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
 9974        // we stop at the highest detail available.
 9975        let item3 = cx.new(|cx| {
 9976            let mut item = TestItem::new(cx);
 9977            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 9978            item
 9979        });
 9980        workspace.update_in(cx, |workspace, window, cx| {
 9981            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 9982        });
 9983        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 9984        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 9985        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 9986    }
 9987
 9988    #[gpui::test]
 9989    async fn test_tracking_active_path(cx: &mut TestAppContext) {
 9990        init_test(cx);
 9991
 9992        let fs = FakeFs::new(cx.executor());
 9993        fs.insert_tree(
 9994            "/root1",
 9995            json!({
 9996                "one.txt": "",
 9997                "two.txt": "",
 9998            }),
 9999        )
10000        .await;
10001        fs.insert_tree(
10002            "/root2",
10003            json!({
10004                "three.txt": "",
10005            }),
10006        )
10007        .await;
10008
10009        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10010        let (workspace, cx) =
10011            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10012        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10013        let worktree_id = project.update(cx, |project, cx| {
10014            project.worktrees(cx).next().unwrap().read(cx).id()
10015        });
10016
10017        let item1 = cx.new(|cx| {
10018            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10019        });
10020        let item2 = cx.new(|cx| {
10021            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10022        });
10023
10024        // Add an item to an empty pane
10025        workspace.update_in(cx, |workspace, window, cx| {
10026            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10027        });
10028        project.update(cx, |project, cx| {
10029            assert_eq!(
10030                project.active_entry(),
10031                project
10032                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10033                    .map(|e| e.id)
10034            );
10035        });
10036        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10037
10038        // Add a second item to a non-empty pane
10039        workspace.update_in(cx, |workspace, window, cx| {
10040            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10041        });
10042        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10043        project.update(cx, |project, cx| {
10044            assert_eq!(
10045                project.active_entry(),
10046                project
10047                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10048                    .map(|e| e.id)
10049            );
10050        });
10051
10052        // Close the active item
10053        pane.update_in(cx, |pane, window, cx| {
10054            pane.close_active_item(&Default::default(), window, cx)
10055        })
10056        .await
10057        .unwrap();
10058        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10059        project.update(cx, |project, cx| {
10060            assert_eq!(
10061                project.active_entry(),
10062                project
10063                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10064                    .map(|e| e.id)
10065            );
10066        });
10067
10068        // Add a project folder
10069        project
10070            .update(cx, |project, cx| {
10071                project.find_or_create_worktree("root2", true, cx)
10072            })
10073            .await
10074            .unwrap();
10075        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10076
10077        // Remove a project folder
10078        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10079        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10080    }
10081
10082    #[gpui::test]
10083    async fn test_close_window(cx: &mut TestAppContext) {
10084        init_test(cx);
10085
10086        let fs = FakeFs::new(cx.executor());
10087        fs.insert_tree("/root", json!({ "one": "" })).await;
10088
10089        let project = Project::test(fs, ["root".as_ref()], cx).await;
10090        let (workspace, cx) =
10091            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10092
10093        // When there are no dirty items, there's nothing to do.
10094        let item1 = cx.new(TestItem::new);
10095        workspace.update_in(cx, |w, window, cx| {
10096            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10097        });
10098        let task = workspace.update_in(cx, |w, window, cx| {
10099            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10100        });
10101        assert!(task.await.unwrap());
10102
10103        // When there are dirty untitled items, prompt to save each one. If the user
10104        // cancels any prompt, then abort.
10105        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10106        let item3 = cx.new(|cx| {
10107            TestItem::new(cx)
10108                .with_dirty(true)
10109                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10110        });
10111        workspace.update_in(cx, |w, window, cx| {
10112            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10113            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10114        });
10115        let task = workspace.update_in(cx, |w, window, cx| {
10116            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10117        });
10118        cx.executor().run_until_parked();
10119        cx.simulate_prompt_answer("Cancel"); // cancel save all
10120        cx.executor().run_until_parked();
10121        assert!(!cx.has_pending_prompt());
10122        assert!(!task.await.unwrap());
10123    }
10124
10125    #[gpui::test]
10126    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10127        init_test(cx);
10128
10129        let fs = FakeFs::new(cx.executor());
10130        fs.insert_tree("/root", json!({ "one": "" })).await;
10131
10132        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10133        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10134        let multi_workspace_handle =
10135            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10136        cx.run_until_parked();
10137
10138        let workspace_a = multi_workspace_handle
10139            .read_with(cx, |mw, _| mw.workspace().clone())
10140            .unwrap();
10141
10142        let workspace_b = multi_workspace_handle
10143            .update(cx, |mw, window, cx| {
10144                mw.test_add_workspace(project_b, window, cx)
10145            })
10146            .unwrap();
10147
10148        // Activate workspace A
10149        multi_workspace_handle
10150            .update(cx, |mw, window, cx| {
10151                mw.activate_index(0, window, cx);
10152            })
10153            .unwrap();
10154
10155        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10156
10157        // Workspace A has a clean item
10158        let item_a = cx.new(TestItem::new);
10159        workspace_a.update_in(cx, |w, window, cx| {
10160            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10161        });
10162
10163        // Workspace B has a dirty item
10164        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10165        workspace_b.update_in(cx, |w, window, cx| {
10166            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10167        });
10168
10169        // Verify workspace A is active
10170        multi_workspace_handle
10171            .read_with(cx, |mw, _| {
10172                assert_eq!(mw.active_workspace_index(), 0);
10173            })
10174            .unwrap();
10175
10176        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10177        multi_workspace_handle
10178            .update(cx, |mw, window, cx| {
10179                mw.close_window(&CloseWindow, window, cx);
10180            })
10181            .unwrap();
10182        cx.run_until_parked();
10183
10184        // Workspace B should now be active since it has dirty items that need attention
10185        multi_workspace_handle
10186            .read_with(cx, |mw, _| {
10187                assert_eq!(
10188                    mw.active_workspace_index(),
10189                    1,
10190                    "workspace B should be activated when it prompts"
10191                );
10192            })
10193            .unwrap();
10194
10195        // User cancels the save prompt from workspace B
10196        cx.simulate_prompt_answer("Cancel");
10197        cx.run_until_parked();
10198
10199        // Window should still exist because workspace B's close was cancelled
10200        assert!(
10201            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10202            "window should still exist after cancelling one workspace's close"
10203        );
10204    }
10205
10206    #[gpui::test]
10207    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10208        init_test(cx);
10209
10210        // Register TestItem as a serializable item
10211        cx.update(|cx| {
10212            register_serializable_item::<TestItem>(cx);
10213        });
10214
10215        let fs = FakeFs::new(cx.executor());
10216        fs.insert_tree("/root", json!({ "one": "" })).await;
10217
10218        let project = Project::test(fs, ["root".as_ref()], cx).await;
10219        let (workspace, cx) =
10220            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10221
10222        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10223        let item1 = cx.new(|cx| {
10224            TestItem::new(cx)
10225                .with_dirty(true)
10226                .with_serialize(|| Some(Task::ready(Ok(()))))
10227        });
10228        let item2 = cx.new(|cx| {
10229            TestItem::new(cx)
10230                .with_dirty(true)
10231                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10232                .with_serialize(|| Some(Task::ready(Ok(()))))
10233        });
10234        workspace.update_in(cx, |w, window, cx| {
10235            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10236            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10237        });
10238        let task = workspace.update_in(cx, |w, window, cx| {
10239            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10240        });
10241        assert!(task.await.unwrap());
10242    }
10243
10244    #[gpui::test]
10245    async fn test_close_pane_items(cx: &mut TestAppContext) {
10246        init_test(cx);
10247
10248        let fs = FakeFs::new(cx.executor());
10249
10250        let project = Project::test(fs, None, cx).await;
10251        let (workspace, cx) =
10252            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10253
10254        let item1 = cx.new(|cx| {
10255            TestItem::new(cx)
10256                .with_dirty(true)
10257                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10258        });
10259        let item2 = cx.new(|cx| {
10260            TestItem::new(cx)
10261                .with_dirty(true)
10262                .with_conflict(true)
10263                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10264        });
10265        let item3 = cx.new(|cx| {
10266            TestItem::new(cx)
10267                .with_dirty(true)
10268                .with_conflict(true)
10269                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10270        });
10271        let item4 = cx.new(|cx| {
10272            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10273                let project_item = TestProjectItem::new_untitled(cx);
10274                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10275                project_item
10276            }])
10277        });
10278        let pane = workspace.update_in(cx, |workspace, window, cx| {
10279            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10280            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10281            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10282            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10283            workspace.active_pane().clone()
10284        });
10285
10286        let close_items = pane.update_in(cx, |pane, window, cx| {
10287            pane.activate_item(1, true, true, window, cx);
10288            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10289            let item1_id = item1.item_id();
10290            let item3_id = item3.item_id();
10291            let item4_id = item4.item_id();
10292            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10293                [item1_id, item3_id, item4_id].contains(&id)
10294            })
10295        });
10296        cx.executor().run_until_parked();
10297
10298        assert!(cx.has_pending_prompt());
10299        cx.simulate_prompt_answer("Save all");
10300
10301        cx.executor().run_until_parked();
10302
10303        // Item 1 is saved. There's a prompt to save item 3.
10304        pane.update(cx, |pane, cx| {
10305            assert_eq!(item1.read(cx).save_count, 1);
10306            assert_eq!(item1.read(cx).save_as_count, 0);
10307            assert_eq!(item1.read(cx).reload_count, 0);
10308            assert_eq!(pane.items_len(), 3);
10309            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10310        });
10311        assert!(cx.has_pending_prompt());
10312
10313        // Cancel saving item 3.
10314        cx.simulate_prompt_answer("Discard");
10315        cx.executor().run_until_parked();
10316
10317        // Item 3 is reloaded. There's a prompt to save item 4.
10318        pane.update(cx, |pane, cx| {
10319            assert_eq!(item3.read(cx).save_count, 0);
10320            assert_eq!(item3.read(cx).save_as_count, 0);
10321            assert_eq!(item3.read(cx).reload_count, 1);
10322            assert_eq!(pane.items_len(), 2);
10323            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10324        });
10325
10326        // There's a prompt for a path for item 4.
10327        cx.simulate_new_path_selection(|_| Some(Default::default()));
10328        close_items.await.unwrap();
10329
10330        // The requested items are closed.
10331        pane.update(cx, |pane, cx| {
10332            assert_eq!(item4.read(cx).save_count, 0);
10333            assert_eq!(item4.read(cx).save_as_count, 1);
10334            assert_eq!(item4.read(cx).reload_count, 0);
10335            assert_eq!(pane.items_len(), 1);
10336            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10337        });
10338    }
10339
10340    #[gpui::test]
10341    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10342        init_test(cx);
10343
10344        let fs = FakeFs::new(cx.executor());
10345        let project = Project::test(fs, [], cx).await;
10346        let (workspace, cx) =
10347            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10348
10349        // Create several workspace items with single project entries, and two
10350        // workspace items with multiple project entries.
10351        let single_entry_items = (0..=4)
10352            .map(|project_entry_id| {
10353                cx.new(|cx| {
10354                    TestItem::new(cx)
10355                        .with_dirty(true)
10356                        .with_project_items(&[dirty_project_item(
10357                            project_entry_id,
10358                            &format!("{project_entry_id}.txt"),
10359                            cx,
10360                        )])
10361                })
10362            })
10363            .collect::<Vec<_>>();
10364        let item_2_3 = cx.new(|cx| {
10365            TestItem::new(cx)
10366                .with_dirty(true)
10367                .with_buffer_kind(ItemBufferKind::Multibuffer)
10368                .with_project_items(&[
10369                    single_entry_items[2].read(cx).project_items[0].clone(),
10370                    single_entry_items[3].read(cx).project_items[0].clone(),
10371                ])
10372        });
10373        let item_3_4 = cx.new(|cx| {
10374            TestItem::new(cx)
10375                .with_dirty(true)
10376                .with_buffer_kind(ItemBufferKind::Multibuffer)
10377                .with_project_items(&[
10378                    single_entry_items[3].read(cx).project_items[0].clone(),
10379                    single_entry_items[4].read(cx).project_items[0].clone(),
10380                ])
10381        });
10382
10383        // Create two panes that contain the following project entries:
10384        //   left pane:
10385        //     multi-entry items:   (2, 3)
10386        //     single-entry items:  0, 2, 3, 4
10387        //   right pane:
10388        //     single-entry items:  4, 1
10389        //     multi-entry items:   (3, 4)
10390        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10391            let left_pane = workspace.active_pane().clone();
10392            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10393            workspace.add_item_to_active_pane(
10394                single_entry_items[0].boxed_clone(),
10395                None,
10396                true,
10397                window,
10398                cx,
10399            );
10400            workspace.add_item_to_active_pane(
10401                single_entry_items[2].boxed_clone(),
10402                None,
10403                true,
10404                window,
10405                cx,
10406            );
10407            workspace.add_item_to_active_pane(
10408                single_entry_items[3].boxed_clone(),
10409                None,
10410                true,
10411                window,
10412                cx,
10413            );
10414            workspace.add_item_to_active_pane(
10415                single_entry_items[4].boxed_clone(),
10416                None,
10417                true,
10418                window,
10419                cx,
10420            );
10421
10422            let right_pane =
10423                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10424
10425            let boxed_clone = single_entry_items[1].boxed_clone();
10426            let right_pane = window.spawn(cx, async move |cx| {
10427                right_pane.await.inspect(|right_pane| {
10428                    right_pane
10429                        .update_in(cx, |pane, window, cx| {
10430                            pane.add_item(boxed_clone, true, true, None, window, cx);
10431                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10432                        })
10433                        .unwrap();
10434                })
10435            });
10436
10437            (left_pane, right_pane)
10438        });
10439        let right_pane = right_pane.await.unwrap();
10440        cx.focus(&right_pane);
10441
10442        let close = right_pane.update_in(cx, |pane, window, cx| {
10443            pane.close_all_items(&CloseAllItems::default(), window, cx)
10444                .unwrap()
10445        });
10446        cx.executor().run_until_parked();
10447
10448        let msg = cx.pending_prompt().unwrap().0;
10449        assert!(msg.contains("1.txt"));
10450        assert!(!msg.contains("2.txt"));
10451        assert!(!msg.contains("3.txt"));
10452        assert!(!msg.contains("4.txt"));
10453
10454        // With best-effort close, cancelling item 1 keeps it open but items 4
10455        // and (3,4) still close since their entries exist in left pane.
10456        cx.simulate_prompt_answer("Cancel");
10457        close.await;
10458
10459        right_pane.read_with(cx, |pane, _| {
10460            assert_eq!(pane.items_len(), 1);
10461        });
10462
10463        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10464        left_pane
10465            .update_in(cx, |left_pane, window, cx| {
10466                left_pane.close_item_by_id(
10467                    single_entry_items[3].entity_id(),
10468                    SaveIntent::Skip,
10469                    window,
10470                    cx,
10471                )
10472            })
10473            .await
10474            .unwrap();
10475
10476        let close = left_pane.update_in(cx, |pane, window, cx| {
10477            pane.close_all_items(&CloseAllItems::default(), window, cx)
10478                .unwrap()
10479        });
10480        cx.executor().run_until_parked();
10481
10482        let details = cx.pending_prompt().unwrap().1;
10483        assert!(details.contains("0.txt"));
10484        assert!(details.contains("3.txt"));
10485        assert!(details.contains("4.txt"));
10486        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10487        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10488        // assert!(!details.contains("2.txt"));
10489
10490        cx.simulate_prompt_answer("Save all");
10491        cx.executor().run_until_parked();
10492        close.await;
10493
10494        left_pane.read_with(cx, |pane, _| {
10495            assert_eq!(pane.items_len(), 0);
10496        });
10497    }
10498
10499    #[gpui::test]
10500    async fn test_autosave(cx: &mut gpui::TestAppContext) {
10501        init_test(cx);
10502
10503        let fs = FakeFs::new(cx.executor());
10504        let project = Project::test(fs, [], cx).await;
10505        let (workspace, cx) =
10506            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10507        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10508
10509        let item = cx.new(|cx| {
10510            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10511        });
10512        let item_id = item.entity_id();
10513        workspace.update_in(cx, |workspace, window, cx| {
10514            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10515        });
10516
10517        // Autosave on window change.
10518        item.update(cx, |item, cx| {
10519            SettingsStore::update_global(cx, |settings, cx| {
10520                settings.update_user_settings(cx, |settings| {
10521                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10522                })
10523            });
10524            item.is_dirty = true;
10525        });
10526
10527        // Deactivating the window saves the file.
10528        cx.deactivate_window();
10529        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10530
10531        // Re-activating the window doesn't save the file.
10532        cx.update(|window, _| window.activate_window());
10533        cx.executor().run_until_parked();
10534        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10535
10536        // Autosave on focus change.
10537        item.update_in(cx, |item, window, cx| {
10538            cx.focus_self(window);
10539            SettingsStore::update_global(cx, |settings, cx| {
10540                settings.update_user_settings(cx, |settings| {
10541                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10542                })
10543            });
10544            item.is_dirty = true;
10545        });
10546        // Blurring the item saves the file.
10547        item.update_in(cx, |_, window, _| window.blur());
10548        cx.executor().run_until_parked();
10549        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10550
10551        // Deactivating the window still saves the file.
10552        item.update_in(cx, |item, window, cx| {
10553            cx.focus_self(window);
10554            item.is_dirty = true;
10555        });
10556        cx.deactivate_window();
10557        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10558
10559        // Autosave after delay.
10560        item.update(cx, |item, cx| {
10561            SettingsStore::update_global(cx, |settings, cx| {
10562                settings.update_user_settings(cx, |settings| {
10563                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10564                        milliseconds: 500.into(),
10565                    });
10566                })
10567            });
10568            item.is_dirty = true;
10569            cx.emit(ItemEvent::Edit);
10570        });
10571
10572        // Delay hasn't fully expired, so the file is still dirty and unsaved.
10573        cx.executor().advance_clock(Duration::from_millis(250));
10574        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10575
10576        // After delay expires, the file is saved.
10577        cx.executor().advance_clock(Duration::from_millis(250));
10578        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10579
10580        // Autosave after delay, should save earlier than delay if tab is closed
10581        item.update(cx, |item, cx| {
10582            item.is_dirty = true;
10583            cx.emit(ItemEvent::Edit);
10584        });
10585        cx.executor().advance_clock(Duration::from_millis(250));
10586        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10587
10588        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10589        pane.update_in(cx, |pane, window, cx| {
10590            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10591        })
10592        .await
10593        .unwrap();
10594        assert!(!cx.has_pending_prompt());
10595        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10596
10597        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10598        workspace.update_in(cx, |workspace, window, cx| {
10599            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10600        });
10601        item.update_in(cx, |item, _window, cx| {
10602            item.is_dirty = true;
10603            for project_item in &mut item.project_items {
10604                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10605            }
10606        });
10607        cx.run_until_parked();
10608        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10609
10610        // Autosave on focus change, ensuring closing the tab counts as such.
10611        item.update(cx, |item, cx| {
10612            SettingsStore::update_global(cx, |settings, cx| {
10613                settings.update_user_settings(cx, |settings| {
10614                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10615                })
10616            });
10617            item.is_dirty = true;
10618            for project_item in &mut item.project_items {
10619                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10620            }
10621        });
10622
10623        pane.update_in(cx, |pane, window, cx| {
10624            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10625        })
10626        .await
10627        .unwrap();
10628        assert!(!cx.has_pending_prompt());
10629        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10630
10631        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10632        workspace.update_in(cx, |workspace, window, cx| {
10633            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10634        });
10635        item.update_in(cx, |item, window, cx| {
10636            item.project_items[0].update(cx, |item, _| {
10637                item.entry_id = None;
10638            });
10639            item.is_dirty = true;
10640            window.blur();
10641        });
10642        cx.run_until_parked();
10643        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10644
10645        // Ensure autosave is prevented for deleted files also when closing the buffer.
10646        let _close_items = pane.update_in(cx, |pane, window, cx| {
10647            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10648        });
10649        cx.run_until_parked();
10650        assert!(cx.has_pending_prompt());
10651        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10652    }
10653
10654    #[gpui::test]
10655    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10656        init_test(cx);
10657
10658        let fs = FakeFs::new(cx.executor());
10659
10660        let project = Project::test(fs, [], cx).await;
10661        let (workspace, cx) =
10662            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10663
10664        let item = cx.new(|cx| {
10665            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10666        });
10667        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10668        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10669        let toolbar_notify_count = Rc::new(RefCell::new(0));
10670
10671        workspace.update_in(cx, |workspace, window, cx| {
10672            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10673            let toolbar_notification_count = toolbar_notify_count.clone();
10674            cx.observe_in(&toolbar, window, move |_, _, _, _| {
10675                *toolbar_notification_count.borrow_mut() += 1
10676            })
10677            .detach();
10678        });
10679
10680        pane.read_with(cx, |pane, _| {
10681            assert!(!pane.can_navigate_backward());
10682            assert!(!pane.can_navigate_forward());
10683        });
10684
10685        item.update_in(cx, |item, _, cx| {
10686            item.set_state("one".to_string(), cx);
10687        });
10688
10689        // Toolbar must be notified to re-render the navigation buttons
10690        assert_eq!(*toolbar_notify_count.borrow(), 1);
10691
10692        pane.read_with(cx, |pane, _| {
10693            assert!(pane.can_navigate_backward());
10694            assert!(!pane.can_navigate_forward());
10695        });
10696
10697        workspace
10698            .update_in(cx, |workspace, window, cx| {
10699                workspace.go_back(pane.downgrade(), window, cx)
10700            })
10701            .await
10702            .unwrap();
10703
10704        assert_eq!(*toolbar_notify_count.borrow(), 2);
10705        pane.read_with(cx, |pane, _| {
10706            assert!(!pane.can_navigate_backward());
10707            assert!(pane.can_navigate_forward());
10708        });
10709    }
10710
10711    #[gpui::test]
10712    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
10713        init_test(cx);
10714        let fs = FakeFs::new(cx.executor());
10715        let project = Project::test(fs, [], cx).await;
10716        let (multi_workspace, cx) =
10717            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
10718        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
10719
10720        workspace.update_in(cx, |workspace, window, cx| {
10721            let first_item = cx.new(|cx| {
10722                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10723            });
10724            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
10725            workspace.split_pane(
10726                workspace.active_pane().clone(),
10727                SplitDirection::Right,
10728                window,
10729                cx,
10730            );
10731            workspace.split_pane(
10732                workspace.active_pane().clone(),
10733                SplitDirection::Right,
10734                window,
10735                cx,
10736            );
10737        });
10738
10739        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
10740            let panes = workspace.center.panes();
10741            assert!(panes.len() >= 2);
10742            (
10743                panes.first().expect("at least one pane").entity_id(),
10744                panes.last().expect("at least one pane").entity_id(),
10745            )
10746        });
10747
10748        workspace.update_in(cx, |workspace, window, cx| {
10749            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
10750        });
10751        workspace.update(cx, |workspace, _| {
10752            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
10753            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
10754        });
10755
10756        cx.dispatch_action(ActivateLastPane);
10757
10758        workspace.update(cx, |workspace, _| {
10759            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
10760        });
10761    }
10762
10763    #[gpui::test]
10764    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
10765        init_test(cx);
10766        let fs = FakeFs::new(cx.executor());
10767
10768        let project = Project::test(fs, [], cx).await;
10769        let (workspace, cx) =
10770            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10771
10772        let panel = workspace.update_in(cx, |workspace, window, cx| {
10773            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10774            workspace.add_panel(panel.clone(), window, cx);
10775
10776            workspace
10777                .right_dock()
10778                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10779
10780            panel
10781        });
10782
10783        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10784        pane.update_in(cx, |pane, window, cx| {
10785            let item = cx.new(TestItem::new);
10786            pane.add_item(Box::new(item), true, true, None, window, cx);
10787        });
10788
10789        // Transfer focus from center to panel
10790        workspace.update_in(cx, |workspace, window, cx| {
10791            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10792        });
10793
10794        workspace.update_in(cx, |workspace, window, cx| {
10795            assert!(workspace.right_dock().read(cx).is_open());
10796            assert!(!panel.is_zoomed(window, cx));
10797            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10798        });
10799
10800        // Transfer focus from panel to center
10801        workspace.update_in(cx, |workspace, window, cx| {
10802            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10803        });
10804
10805        workspace.update_in(cx, |workspace, window, cx| {
10806            assert!(workspace.right_dock().read(cx).is_open());
10807            assert!(!panel.is_zoomed(window, cx));
10808            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10809        });
10810
10811        // Close the dock
10812        workspace.update_in(cx, |workspace, window, cx| {
10813            workspace.toggle_dock(DockPosition::Right, window, cx);
10814        });
10815
10816        workspace.update_in(cx, |workspace, window, cx| {
10817            assert!(!workspace.right_dock().read(cx).is_open());
10818            assert!(!panel.is_zoomed(window, cx));
10819            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10820        });
10821
10822        // Open the dock
10823        workspace.update_in(cx, |workspace, window, cx| {
10824            workspace.toggle_dock(DockPosition::Right, window, cx);
10825        });
10826
10827        workspace.update_in(cx, |workspace, window, cx| {
10828            assert!(workspace.right_dock().read(cx).is_open());
10829            assert!(!panel.is_zoomed(window, cx));
10830            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10831        });
10832
10833        // Focus and zoom panel
10834        panel.update_in(cx, |panel, window, cx| {
10835            cx.focus_self(window);
10836            panel.set_zoomed(true, window, cx)
10837        });
10838
10839        workspace.update_in(cx, |workspace, window, cx| {
10840            assert!(workspace.right_dock().read(cx).is_open());
10841            assert!(panel.is_zoomed(window, cx));
10842            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10843        });
10844
10845        // Transfer focus to the center closes the dock
10846        workspace.update_in(cx, |workspace, window, cx| {
10847            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10848        });
10849
10850        workspace.update_in(cx, |workspace, window, cx| {
10851            assert!(!workspace.right_dock().read(cx).is_open());
10852            assert!(panel.is_zoomed(window, cx));
10853            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10854        });
10855
10856        // Transferring focus back to the panel keeps it zoomed
10857        workspace.update_in(cx, |workspace, window, cx| {
10858            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10859        });
10860
10861        workspace.update_in(cx, |workspace, window, cx| {
10862            assert!(workspace.right_dock().read(cx).is_open());
10863            assert!(panel.is_zoomed(window, cx));
10864            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10865        });
10866
10867        // Close the dock while it is zoomed
10868        workspace.update_in(cx, |workspace, window, cx| {
10869            workspace.toggle_dock(DockPosition::Right, window, cx)
10870        });
10871
10872        workspace.update_in(cx, |workspace, window, cx| {
10873            assert!(!workspace.right_dock().read(cx).is_open());
10874            assert!(panel.is_zoomed(window, cx));
10875            assert!(workspace.zoomed.is_none());
10876            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10877        });
10878
10879        // Opening the dock, when it's zoomed, retains focus
10880        workspace.update_in(cx, |workspace, window, cx| {
10881            workspace.toggle_dock(DockPosition::Right, window, cx)
10882        });
10883
10884        workspace.update_in(cx, |workspace, window, cx| {
10885            assert!(workspace.right_dock().read(cx).is_open());
10886            assert!(panel.is_zoomed(window, cx));
10887            assert!(workspace.zoomed.is_some());
10888            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10889        });
10890
10891        // Unzoom and close the panel, zoom the active pane.
10892        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
10893        workspace.update_in(cx, |workspace, window, cx| {
10894            workspace.toggle_dock(DockPosition::Right, window, cx)
10895        });
10896        pane.update_in(cx, |pane, window, cx| {
10897            pane.toggle_zoom(&Default::default(), window, cx)
10898        });
10899
10900        // Opening a dock unzooms the pane.
10901        workspace.update_in(cx, |workspace, window, cx| {
10902            workspace.toggle_dock(DockPosition::Right, window, cx)
10903        });
10904        workspace.update_in(cx, |workspace, window, cx| {
10905            let pane = pane.read(cx);
10906            assert!(!pane.is_zoomed());
10907            assert!(!pane.focus_handle(cx).is_focused(window));
10908            assert!(workspace.right_dock().read(cx).is_open());
10909            assert!(workspace.zoomed.is_none());
10910        });
10911    }
10912
10913    #[gpui::test]
10914    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
10915        init_test(cx);
10916        let fs = FakeFs::new(cx.executor());
10917
10918        let project = Project::test(fs, [], cx).await;
10919        let (workspace, cx) =
10920            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10921
10922        let panel = workspace.update_in(cx, |workspace, window, cx| {
10923            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10924            workspace.add_panel(panel.clone(), window, cx);
10925            panel
10926        });
10927
10928        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10929        pane.update_in(cx, |pane, window, cx| {
10930            let item = cx.new(TestItem::new);
10931            pane.add_item(Box::new(item), true, true, None, window, cx);
10932        });
10933
10934        // Enable close_panel_on_toggle
10935        cx.update_global(|store: &mut SettingsStore, cx| {
10936            store.update_user_settings(cx, |settings| {
10937                settings.workspace.close_panel_on_toggle = Some(true);
10938            });
10939        });
10940
10941        // Panel starts closed. Toggling should open and focus it.
10942        workspace.update_in(cx, |workspace, window, cx| {
10943            assert!(!workspace.right_dock().read(cx).is_open());
10944            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10945        });
10946
10947        workspace.update_in(cx, |workspace, window, cx| {
10948            assert!(
10949                workspace.right_dock().read(cx).is_open(),
10950                "Dock should be open after toggling from center"
10951            );
10952            assert!(
10953                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10954                "Panel should be focused after toggling from center"
10955            );
10956        });
10957
10958        // Panel is open and focused. Toggling should close the panel and
10959        // return focus to the center.
10960        workspace.update_in(cx, |workspace, window, cx| {
10961            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10962        });
10963
10964        workspace.update_in(cx, |workspace, window, cx| {
10965            assert!(
10966                !workspace.right_dock().read(cx).is_open(),
10967                "Dock should be closed after toggling from focused panel"
10968            );
10969            assert!(
10970                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10971                "Panel should not be focused after toggling from focused panel"
10972            );
10973        });
10974
10975        // Open the dock and focus something else so the panel is open but not
10976        // focused. Toggling should focus the panel (not close it).
10977        workspace.update_in(cx, |workspace, window, cx| {
10978            workspace
10979                .right_dock()
10980                .update(cx, |dock, cx| dock.set_open(true, window, cx));
10981            window.focus(&pane.read(cx).focus_handle(cx), cx);
10982        });
10983
10984        workspace.update_in(cx, |workspace, window, cx| {
10985            assert!(workspace.right_dock().read(cx).is_open());
10986            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10987            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10988        });
10989
10990        workspace.update_in(cx, |workspace, window, cx| {
10991            assert!(
10992                workspace.right_dock().read(cx).is_open(),
10993                "Dock should remain open when toggling focuses an open-but-unfocused panel"
10994            );
10995            assert!(
10996                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10997                "Panel should be focused after toggling an open-but-unfocused panel"
10998            );
10999        });
11000
11001        // Now disable the setting and verify the original behavior: toggling
11002        // from a focused panel moves focus to center but leaves the dock open.
11003        cx.update_global(|store: &mut SettingsStore, cx| {
11004            store.update_user_settings(cx, |settings| {
11005                settings.workspace.close_panel_on_toggle = Some(false);
11006            });
11007        });
11008
11009        workspace.update_in(cx, |workspace, window, cx| {
11010            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11011        });
11012
11013        workspace.update_in(cx, |workspace, window, cx| {
11014            assert!(
11015                workspace.right_dock().read(cx).is_open(),
11016                "Dock should remain open when setting is disabled"
11017            );
11018            assert!(
11019                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11020                "Panel should not be focused after toggling with setting disabled"
11021            );
11022        });
11023    }
11024
11025    #[gpui::test]
11026    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11027        init_test(cx);
11028        let fs = FakeFs::new(cx.executor());
11029
11030        let project = Project::test(fs, [], cx).await;
11031        let (workspace, cx) =
11032            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11033
11034        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11035            workspace.active_pane().clone()
11036        });
11037
11038        // Add an item to the pane so it can be zoomed
11039        workspace.update_in(cx, |workspace, window, cx| {
11040            let item = cx.new(TestItem::new);
11041            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11042        });
11043
11044        // Initially not zoomed
11045        workspace.update_in(cx, |workspace, _window, cx| {
11046            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11047            assert!(
11048                workspace.zoomed.is_none(),
11049                "Workspace should track no zoomed pane"
11050            );
11051            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11052        });
11053
11054        // Zoom In
11055        pane.update_in(cx, |pane, window, cx| {
11056            pane.zoom_in(&crate::ZoomIn, window, cx);
11057        });
11058
11059        workspace.update_in(cx, |workspace, window, cx| {
11060            assert!(
11061                pane.read(cx).is_zoomed(),
11062                "Pane should be zoomed after ZoomIn"
11063            );
11064            assert!(
11065                workspace.zoomed.is_some(),
11066                "Workspace should track the zoomed pane"
11067            );
11068            assert!(
11069                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11070                "ZoomIn should focus the pane"
11071            );
11072        });
11073
11074        // Zoom In again is a no-op
11075        pane.update_in(cx, |pane, window, cx| {
11076            pane.zoom_in(&crate::ZoomIn, window, cx);
11077        });
11078
11079        workspace.update_in(cx, |workspace, window, cx| {
11080            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11081            assert!(
11082                workspace.zoomed.is_some(),
11083                "Workspace still tracks zoomed pane"
11084            );
11085            assert!(
11086                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11087                "Pane remains focused after repeated ZoomIn"
11088            );
11089        });
11090
11091        // Zoom Out
11092        pane.update_in(cx, |pane, window, cx| {
11093            pane.zoom_out(&crate::ZoomOut, window, cx);
11094        });
11095
11096        workspace.update_in(cx, |workspace, _window, cx| {
11097            assert!(
11098                !pane.read(cx).is_zoomed(),
11099                "Pane should unzoom after ZoomOut"
11100            );
11101            assert!(
11102                workspace.zoomed.is_none(),
11103                "Workspace clears zoom tracking after ZoomOut"
11104            );
11105        });
11106
11107        // Zoom Out again is a no-op
11108        pane.update_in(cx, |pane, window, cx| {
11109            pane.zoom_out(&crate::ZoomOut, window, cx);
11110        });
11111
11112        workspace.update_in(cx, |workspace, _window, cx| {
11113            assert!(
11114                !pane.read(cx).is_zoomed(),
11115                "Second ZoomOut keeps pane unzoomed"
11116            );
11117            assert!(
11118                workspace.zoomed.is_none(),
11119                "Workspace remains without zoomed pane"
11120            );
11121        });
11122    }
11123
11124    #[gpui::test]
11125    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11126        init_test(cx);
11127        let fs = FakeFs::new(cx.executor());
11128
11129        let project = Project::test(fs, [], cx).await;
11130        let (workspace, cx) =
11131            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11132        workspace.update_in(cx, |workspace, window, cx| {
11133            // Open two docks
11134            let left_dock = workspace.dock_at_position(DockPosition::Left);
11135            let right_dock = workspace.dock_at_position(DockPosition::Right);
11136
11137            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11138            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11139
11140            assert!(left_dock.read(cx).is_open());
11141            assert!(right_dock.read(cx).is_open());
11142        });
11143
11144        workspace.update_in(cx, |workspace, window, cx| {
11145            // Toggle all docks - should close both
11146            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11147
11148            let left_dock = workspace.dock_at_position(DockPosition::Left);
11149            let right_dock = workspace.dock_at_position(DockPosition::Right);
11150            assert!(!left_dock.read(cx).is_open());
11151            assert!(!right_dock.read(cx).is_open());
11152        });
11153
11154        workspace.update_in(cx, |workspace, window, cx| {
11155            // Toggle again - should reopen both
11156            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11157
11158            let left_dock = workspace.dock_at_position(DockPosition::Left);
11159            let right_dock = workspace.dock_at_position(DockPosition::Right);
11160            assert!(left_dock.read(cx).is_open());
11161            assert!(right_dock.read(cx).is_open());
11162        });
11163    }
11164
11165    #[gpui::test]
11166    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11167        init_test(cx);
11168        let fs = FakeFs::new(cx.executor());
11169
11170        let project = Project::test(fs, [], cx).await;
11171        let (workspace, cx) =
11172            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11173        workspace.update_in(cx, |workspace, window, cx| {
11174            // Open two docks
11175            let left_dock = workspace.dock_at_position(DockPosition::Left);
11176            let right_dock = workspace.dock_at_position(DockPosition::Right);
11177
11178            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11179            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11180
11181            assert!(left_dock.read(cx).is_open());
11182            assert!(right_dock.read(cx).is_open());
11183        });
11184
11185        workspace.update_in(cx, |workspace, window, cx| {
11186            // Close them manually
11187            workspace.toggle_dock(DockPosition::Left, window, cx);
11188            workspace.toggle_dock(DockPosition::Right, window, cx);
11189
11190            let left_dock = workspace.dock_at_position(DockPosition::Left);
11191            let right_dock = workspace.dock_at_position(DockPosition::Right);
11192            assert!(!left_dock.read(cx).is_open());
11193            assert!(!right_dock.read(cx).is_open());
11194        });
11195
11196        workspace.update_in(cx, |workspace, window, cx| {
11197            // Toggle all docks - only last closed (right dock) should reopen
11198            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11199
11200            let left_dock = workspace.dock_at_position(DockPosition::Left);
11201            let right_dock = workspace.dock_at_position(DockPosition::Right);
11202            assert!(!left_dock.read(cx).is_open());
11203            assert!(right_dock.read(cx).is_open());
11204        });
11205    }
11206
11207    #[gpui::test]
11208    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11209        init_test(cx);
11210        let fs = FakeFs::new(cx.executor());
11211        let project = Project::test(fs, [], cx).await;
11212        let (multi_workspace, cx) =
11213            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11214        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11215
11216        // Open two docks (left and right) with one panel each
11217        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11218            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11219            workspace.add_panel(left_panel.clone(), window, cx);
11220
11221            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11222            workspace.add_panel(right_panel.clone(), window, cx);
11223
11224            workspace.toggle_dock(DockPosition::Left, window, cx);
11225            workspace.toggle_dock(DockPosition::Right, window, cx);
11226
11227            // Verify initial state
11228            assert!(
11229                workspace.left_dock().read(cx).is_open(),
11230                "Left dock should be open"
11231            );
11232            assert_eq!(
11233                workspace
11234                    .left_dock()
11235                    .read(cx)
11236                    .visible_panel()
11237                    .unwrap()
11238                    .panel_id(),
11239                left_panel.panel_id(),
11240                "Left panel should be visible in left dock"
11241            );
11242            assert!(
11243                workspace.right_dock().read(cx).is_open(),
11244                "Right dock should be open"
11245            );
11246            assert_eq!(
11247                workspace
11248                    .right_dock()
11249                    .read(cx)
11250                    .visible_panel()
11251                    .unwrap()
11252                    .panel_id(),
11253                right_panel.panel_id(),
11254                "Right panel should be visible in right dock"
11255            );
11256            assert!(
11257                !workspace.bottom_dock().read(cx).is_open(),
11258                "Bottom dock should be closed"
11259            );
11260
11261            (left_panel, right_panel)
11262        });
11263
11264        // Focus the left panel and move it to the next position (bottom dock)
11265        workspace.update_in(cx, |workspace, window, cx| {
11266            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11267            assert!(
11268                left_panel.read(cx).focus_handle(cx).is_focused(window),
11269                "Left panel should be focused"
11270            );
11271        });
11272
11273        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11274
11275        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11276        workspace.update(cx, |workspace, cx| {
11277            assert!(
11278                !workspace.left_dock().read(cx).is_open(),
11279                "Left dock should be closed"
11280            );
11281            assert!(
11282                workspace.bottom_dock().read(cx).is_open(),
11283                "Bottom dock should now be open"
11284            );
11285            assert_eq!(
11286                left_panel.read(cx).position,
11287                DockPosition::Bottom,
11288                "Left panel should now be in the bottom dock"
11289            );
11290            assert_eq!(
11291                workspace
11292                    .bottom_dock()
11293                    .read(cx)
11294                    .visible_panel()
11295                    .unwrap()
11296                    .panel_id(),
11297                left_panel.panel_id(),
11298                "Left panel should be the visible panel in the bottom dock"
11299            );
11300        });
11301
11302        // Toggle all docks off
11303        workspace.update_in(cx, |workspace, window, cx| {
11304            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11305            assert!(
11306                !workspace.left_dock().read(cx).is_open(),
11307                "Left dock should be closed"
11308            );
11309            assert!(
11310                !workspace.right_dock().read(cx).is_open(),
11311                "Right dock should be closed"
11312            );
11313            assert!(
11314                !workspace.bottom_dock().read(cx).is_open(),
11315                "Bottom dock should be closed"
11316            );
11317        });
11318
11319        // Toggle all docks back on and verify positions are restored
11320        workspace.update_in(cx, |workspace, window, cx| {
11321            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11322            assert!(
11323                !workspace.left_dock().read(cx).is_open(),
11324                "Left dock should remain closed"
11325            );
11326            assert!(
11327                workspace.right_dock().read(cx).is_open(),
11328                "Right dock should remain open"
11329            );
11330            assert!(
11331                workspace.bottom_dock().read(cx).is_open(),
11332                "Bottom dock should remain open"
11333            );
11334            assert_eq!(
11335                left_panel.read(cx).position,
11336                DockPosition::Bottom,
11337                "Left panel should remain in the bottom dock"
11338            );
11339            assert_eq!(
11340                right_panel.read(cx).position,
11341                DockPosition::Right,
11342                "Right panel should remain in the right dock"
11343            );
11344            assert_eq!(
11345                workspace
11346                    .bottom_dock()
11347                    .read(cx)
11348                    .visible_panel()
11349                    .unwrap()
11350                    .panel_id(),
11351                left_panel.panel_id(),
11352                "Left panel should be the visible panel in the right dock"
11353            );
11354        });
11355    }
11356
11357    #[gpui::test]
11358    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11359        init_test(cx);
11360
11361        let fs = FakeFs::new(cx.executor());
11362
11363        let project = Project::test(fs, None, cx).await;
11364        let (workspace, cx) =
11365            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11366
11367        // Let's arrange the panes like this:
11368        //
11369        // +-----------------------+
11370        // |         top           |
11371        // +------+--------+-------+
11372        // | left | center | right |
11373        // +------+--------+-------+
11374        // |        bottom         |
11375        // +-----------------------+
11376
11377        let top_item = cx.new(|cx| {
11378            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11379        });
11380        let bottom_item = cx.new(|cx| {
11381            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11382        });
11383        let left_item = cx.new(|cx| {
11384            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11385        });
11386        let right_item = cx.new(|cx| {
11387            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11388        });
11389        let center_item = cx.new(|cx| {
11390            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11391        });
11392
11393        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11394            let top_pane_id = workspace.active_pane().entity_id();
11395            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11396            workspace.split_pane(
11397                workspace.active_pane().clone(),
11398                SplitDirection::Down,
11399                window,
11400                cx,
11401            );
11402            top_pane_id
11403        });
11404        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11405            let bottom_pane_id = workspace.active_pane().entity_id();
11406            workspace.add_item_to_active_pane(
11407                Box::new(bottom_item.clone()),
11408                None,
11409                false,
11410                window,
11411                cx,
11412            );
11413            workspace.split_pane(
11414                workspace.active_pane().clone(),
11415                SplitDirection::Up,
11416                window,
11417                cx,
11418            );
11419            bottom_pane_id
11420        });
11421        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11422            let left_pane_id = workspace.active_pane().entity_id();
11423            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11424            workspace.split_pane(
11425                workspace.active_pane().clone(),
11426                SplitDirection::Right,
11427                window,
11428                cx,
11429            );
11430            left_pane_id
11431        });
11432        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11433            let right_pane_id = workspace.active_pane().entity_id();
11434            workspace.add_item_to_active_pane(
11435                Box::new(right_item.clone()),
11436                None,
11437                false,
11438                window,
11439                cx,
11440            );
11441            workspace.split_pane(
11442                workspace.active_pane().clone(),
11443                SplitDirection::Left,
11444                window,
11445                cx,
11446            );
11447            right_pane_id
11448        });
11449        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11450            let center_pane_id = workspace.active_pane().entity_id();
11451            workspace.add_item_to_active_pane(
11452                Box::new(center_item.clone()),
11453                None,
11454                false,
11455                window,
11456                cx,
11457            );
11458            center_pane_id
11459        });
11460        cx.executor().run_until_parked();
11461
11462        workspace.update_in(cx, |workspace, window, cx| {
11463            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11464
11465            // Join into next from center pane into right
11466            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11467        });
11468
11469        workspace.update_in(cx, |workspace, window, cx| {
11470            let active_pane = workspace.active_pane();
11471            assert_eq!(right_pane_id, active_pane.entity_id());
11472            assert_eq!(2, active_pane.read(cx).items_len());
11473            let item_ids_in_pane =
11474                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11475            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11476            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11477
11478            // Join into next from right pane into bottom
11479            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11480        });
11481
11482        workspace.update_in(cx, |workspace, window, cx| {
11483            let active_pane = workspace.active_pane();
11484            assert_eq!(bottom_pane_id, active_pane.entity_id());
11485            assert_eq!(3, active_pane.read(cx).items_len());
11486            let item_ids_in_pane =
11487                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11488            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11489            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11490            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11491
11492            // Join into next from bottom pane into left
11493            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11494        });
11495
11496        workspace.update_in(cx, |workspace, window, cx| {
11497            let active_pane = workspace.active_pane();
11498            assert_eq!(left_pane_id, active_pane.entity_id());
11499            assert_eq!(4, active_pane.read(cx).items_len());
11500            let item_ids_in_pane =
11501                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11502            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11503            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11504            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11505            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11506
11507            // Join into next from left pane into top
11508            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11509        });
11510
11511        workspace.update_in(cx, |workspace, window, cx| {
11512            let active_pane = workspace.active_pane();
11513            assert_eq!(top_pane_id, active_pane.entity_id());
11514            assert_eq!(5, active_pane.read(cx).items_len());
11515            let item_ids_in_pane =
11516                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11517            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11518            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11519            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11520            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11521            assert!(item_ids_in_pane.contains(&top_item.item_id()));
11522
11523            // Single pane left: no-op
11524            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11525        });
11526
11527        workspace.update(cx, |workspace, _cx| {
11528            let active_pane = workspace.active_pane();
11529            assert_eq!(top_pane_id, active_pane.entity_id());
11530        });
11531    }
11532
11533    fn add_an_item_to_active_pane(
11534        cx: &mut VisualTestContext,
11535        workspace: &Entity<Workspace>,
11536        item_id: u64,
11537    ) -> Entity<TestItem> {
11538        let item = cx.new(|cx| {
11539            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11540                item_id,
11541                "item{item_id}.txt",
11542                cx,
11543            )])
11544        });
11545        workspace.update_in(cx, |workspace, window, cx| {
11546            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11547        });
11548        item
11549    }
11550
11551    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11552        workspace.update_in(cx, |workspace, window, cx| {
11553            workspace.split_pane(
11554                workspace.active_pane().clone(),
11555                SplitDirection::Right,
11556                window,
11557                cx,
11558            )
11559        })
11560    }
11561
11562    #[gpui::test]
11563    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11564        init_test(cx);
11565        let fs = FakeFs::new(cx.executor());
11566        let project = Project::test(fs, None, cx).await;
11567        let (workspace, cx) =
11568            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11569
11570        add_an_item_to_active_pane(cx, &workspace, 1);
11571        split_pane(cx, &workspace);
11572        add_an_item_to_active_pane(cx, &workspace, 2);
11573        split_pane(cx, &workspace); // empty pane
11574        split_pane(cx, &workspace);
11575        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11576
11577        cx.executor().run_until_parked();
11578
11579        workspace.update(cx, |workspace, cx| {
11580            let num_panes = workspace.panes().len();
11581            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11582            let active_item = workspace
11583                .active_pane()
11584                .read(cx)
11585                .active_item()
11586                .expect("item is in focus");
11587
11588            assert_eq!(num_panes, 4);
11589            assert_eq!(num_items_in_current_pane, 1);
11590            assert_eq!(active_item.item_id(), last_item.item_id());
11591        });
11592
11593        workspace.update_in(cx, |workspace, window, cx| {
11594            workspace.join_all_panes(window, cx);
11595        });
11596
11597        workspace.update(cx, |workspace, cx| {
11598            let num_panes = workspace.panes().len();
11599            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11600            let active_item = workspace
11601                .active_pane()
11602                .read(cx)
11603                .active_item()
11604                .expect("item is in focus");
11605
11606            assert_eq!(num_panes, 1);
11607            assert_eq!(num_items_in_current_pane, 3);
11608            assert_eq!(active_item.item_id(), last_item.item_id());
11609        });
11610    }
11611    struct TestModal(FocusHandle);
11612
11613    impl TestModal {
11614        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11615            Self(cx.focus_handle())
11616        }
11617    }
11618
11619    impl EventEmitter<DismissEvent> for TestModal {}
11620
11621    impl Focusable for TestModal {
11622        fn focus_handle(&self, _cx: &App) -> FocusHandle {
11623            self.0.clone()
11624        }
11625    }
11626
11627    impl ModalView for TestModal {}
11628
11629    impl Render for TestModal {
11630        fn render(
11631            &mut self,
11632            _window: &mut Window,
11633            _cx: &mut Context<TestModal>,
11634        ) -> impl IntoElement {
11635            div().track_focus(&self.0)
11636        }
11637    }
11638
11639    #[gpui::test]
11640    async fn test_panels(cx: &mut gpui::TestAppContext) {
11641        init_test(cx);
11642        let fs = FakeFs::new(cx.executor());
11643
11644        let project = Project::test(fs, [], cx).await;
11645        let (multi_workspace, cx) =
11646            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11647        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11648
11649        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11650            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11651            workspace.add_panel(panel_1.clone(), window, cx);
11652            workspace.toggle_dock(DockPosition::Left, window, cx);
11653            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11654            workspace.add_panel(panel_2.clone(), window, cx);
11655            workspace.toggle_dock(DockPosition::Right, window, cx);
11656
11657            let left_dock = workspace.left_dock();
11658            assert_eq!(
11659                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11660                panel_1.panel_id()
11661            );
11662            assert_eq!(
11663                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11664                panel_1.size(window, cx)
11665            );
11666
11667            left_dock.update(cx, |left_dock, cx| {
11668                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11669            });
11670            assert_eq!(
11671                workspace
11672                    .right_dock()
11673                    .read(cx)
11674                    .visible_panel()
11675                    .unwrap()
11676                    .panel_id(),
11677                panel_2.panel_id(),
11678            );
11679
11680            (panel_1, panel_2)
11681        });
11682
11683        // Move panel_1 to the right
11684        panel_1.update_in(cx, |panel_1, window, cx| {
11685            panel_1.set_position(DockPosition::Right, window, cx)
11686        });
11687
11688        workspace.update_in(cx, |workspace, window, cx| {
11689            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11690            // Since it was the only panel on the left, the left dock should now be closed.
11691            assert!(!workspace.left_dock().read(cx).is_open());
11692            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11693            let right_dock = workspace.right_dock();
11694            assert_eq!(
11695                right_dock.read(cx).visible_panel().unwrap().panel_id(),
11696                panel_1.panel_id()
11697            );
11698            assert_eq!(
11699                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11700                px(1337.)
11701            );
11702
11703            // Now we move panel_2 to the left
11704            panel_2.set_position(DockPosition::Left, window, cx);
11705        });
11706
11707        workspace.update(cx, |workspace, cx| {
11708            // Since panel_2 was not visible on the right, we don't open the left dock.
11709            assert!(!workspace.left_dock().read(cx).is_open());
11710            // And the right dock is unaffected in its displaying of panel_1
11711            assert!(workspace.right_dock().read(cx).is_open());
11712            assert_eq!(
11713                workspace
11714                    .right_dock()
11715                    .read(cx)
11716                    .visible_panel()
11717                    .unwrap()
11718                    .panel_id(),
11719                panel_1.panel_id(),
11720            );
11721        });
11722
11723        // Move panel_1 back to the left
11724        panel_1.update_in(cx, |panel_1, window, cx| {
11725            panel_1.set_position(DockPosition::Left, window, cx)
11726        });
11727
11728        workspace.update_in(cx, |workspace, window, cx| {
11729            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11730            let left_dock = workspace.left_dock();
11731            assert!(left_dock.read(cx).is_open());
11732            assert_eq!(
11733                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11734                panel_1.panel_id()
11735            );
11736            assert_eq!(
11737                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11738                px(1337.)
11739            );
11740            // And the right dock should be closed as it no longer has any panels.
11741            assert!(!workspace.right_dock().read(cx).is_open());
11742
11743            // Now we move panel_1 to the bottom
11744            panel_1.set_position(DockPosition::Bottom, window, cx);
11745        });
11746
11747        workspace.update_in(cx, |workspace, window, cx| {
11748            // Since panel_1 was visible on the left, we close the left dock.
11749            assert!(!workspace.left_dock().read(cx).is_open());
11750            // The bottom dock is sized based on the panel's default size,
11751            // since the panel orientation changed from vertical to horizontal.
11752            let bottom_dock = workspace.bottom_dock();
11753            assert_eq!(
11754                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
11755                panel_1.size(window, cx),
11756            );
11757            // Close bottom dock and move panel_1 back to the left.
11758            bottom_dock.update(cx, |bottom_dock, cx| {
11759                bottom_dock.set_open(false, window, cx)
11760            });
11761            panel_1.set_position(DockPosition::Left, window, cx);
11762        });
11763
11764        // Emit activated event on panel 1
11765        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
11766
11767        // Now the left dock is open and panel_1 is active and focused.
11768        workspace.update_in(cx, |workspace, window, cx| {
11769            let left_dock = workspace.left_dock();
11770            assert!(left_dock.read(cx).is_open());
11771            assert_eq!(
11772                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11773                panel_1.panel_id(),
11774            );
11775            assert!(panel_1.focus_handle(cx).is_focused(window));
11776        });
11777
11778        // Emit closed event on panel 2, which is not active
11779        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11780
11781        // Wo don't close the left dock, because panel_2 wasn't the active panel
11782        workspace.update(cx, |workspace, cx| {
11783            let left_dock = workspace.left_dock();
11784            assert!(left_dock.read(cx).is_open());
11785            assert_eq!(
11786                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11787                panel_1.panel_id(),
11788            );
11789        });
11790
11791        // Emitting a ZoomIn event shows the panel as zoomed.
11792        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
11793        workspace.read_with(cx, |workspace, _| {
11794            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11795            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
11796        });
11797
11798        // Move panel to another dock while it is zoomed
11799        panel_1.update_in(cx, |panel, window, cx| {
11800            panel.set_position(DockPosition::Right, window, cx)
11801        });
11802        workspace.read_with(cx, |workspace, _| {
11803            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11804
11805            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11806        });
11807
11808        // This is a helper for getting a:
11809        // - valid focus on an element,
11810        // - that isn't a part of the panes and panels system of the Workspace,
11811        // - and doesn't trigger the 'on_focus_lost' API.
11812        let focus_other_view = {
11813            let workspace = workspace.clone();
11814            move |cx: &mut VisualTestContext| {
11815                workspace.update_in(cx, |workspace, window, cx| {
11816                    if workspace.active_modal::<TestModal>(cx).is_some() {
11817                        workspace.toggle_modal(window, cx, TestModal::new);
11818                        workspace.toggle_modal(window, cx, TestModal::new);
11819                    } else {
11820                        workspace.toggle_modal(window, cx, TestModal::new);
11821                    }
11822                })
11823            }
11824        };
11825
11826        // If focus is transferred to another view that's not a panel or another pane, we still show
11827        // the panel as zoomed.
11828        focus_other_view(cx);
11829        workspace.read_with(cx, |workspace, _| {
11830            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11831            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11832        });
11833
11834        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
11835        workspace.update_in(cx, |_workspace, window, cx| {
11836            cx.focus_self(window);
11837        });
11838        workspace.read_with(cx, |workspace, _| {
11839            assert_eq!(workspace.zoomed, None);
11840            assert_eq!(workspace.zoomed_position, None);
11841        });
11842
11843        // If focus is transferred again to another view that's not a panel or a pane, we won't
11844        // show the panel as zoomed because it wasn't zoomed before.
11845        focus_other_view(cx);
11846        workspace.read_with(cx, |workspace, _| {
11847            assert_eq!(workspace.zoomed, None);
11848            assert_eq!(workspace.zoomed_position, None);
11849        });
11850
11851        // When the panel is activated, it is zoomed again.
11852        cx.dispatch_action(ToggleRightDock);
11853        workspace.read_with(cx, |workspace, _| {
11854            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11855            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11856        });
11857
11858        // Emitting a ZoomOut event unzooms the panel.
11859        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
11860        workspace.read_with(cx, |workspace, _| {
11861            assert_eq!(workspace.zoomed, None);
11862            assert_eq!(workspace.zoomed_position, None);
11863        });
11864
11865        // Emit closed event on panel 1, which is active
11866        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11867
11868        // Now the left dock is closed, because panel_1 was the active panel
11869        workspace.update(cx, |workspace, cx| {
11870            let right_dock = workspace.right_dock();
11871            assert!(!right_dock.read(cx).is_open());
11872        });
11873    }
11874
11875    #[gpui::test]
11876    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
11877        init_test(cx);
11878
11879        let fs = FakeFs::new(cx.background_executor.clone());
11880        let project = Project::test(fs, [], cx).await;
11881        let (workspace, cx) =
11882            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11883        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11884
11885        let dirty_regular_buffer = cx.new(|cx| {
11886            TestItem::new(cx)
11887                .with_dirty(true)
11888                .with_label("1.txt")
11889                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11890        });
11891        let dirty_regular_buffer_2 = cx.new(|cx| {
11892            TestItem::new(cx)
11893                .with_dirty(true)
11894                .with_label("2.txt")
11895                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11896        });
11897        let dirty_multi_buffer_with_both = cx.new(|cx| {
11898            TestItem::new(cx)
11899                .with_dirty(true)
11900                .with_buffer_kind(ItemBufferKind::Multibuffer)
11901                .with_label("Fake Project Search")
11902                .with_project_items(&[
11903                    dirty_regular_buffer.read(cx).project_items[0].clone(),
11904                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11905                ])
11906        });
11907        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11908        workspace.update_in(cx, |workspace, window, cx| {
11909            workspace.add_item(
11910                pane.clone(),
11911                Box::new(dirty_regular_buffer.clone()),
11912                None,
11913                false,
11914                false,
11915                window,
11916                cx,
11917            );
11918            workspace.add_item(
11919                pane.clone(),
11920                Box::new(dirty_regular_buffer_2.clone()),
11921                None,
11922                false,
11923                false,
11924                window,
11925                cx,
11926            );
11927            workspace.add_item(
11928                pane.clone(),
11929                Box::new(dirty_multi_buffer_with_both.clone()),
11930                None,
11931                false,
11932                false,
11933                window,
11934                cx,
11935            );
11936        });
11937
11938        pane.update_in(cx, |pane, window, cx| {
11939            pane.activate_item(2, true, true, window, cx);
11940            assert_eq!(
11941                pane.active_item().unwrap().item_id(),
11942                multi_buffer_with_both_files_id,
11943                "Should select the multi buffer in the pane"
11944            );
11945        });
11946        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11947            pane.close_other_items(
11948                &CloseOtherItems {
11949                    save_intent: Some(SaveIntent::Save),
11950                    close_pinned: true,
11951                },
11952                None,
11953                window,
11954                cx,
11955            )
11956        });
11957        cx.background_executor.run_until_parked();
11958        assert!(!cx.has_pending_prompt());
11959        close_all_but_multi_buffer_task
11960            .await
11961            .expect("Closing all buffers but the multi buffer failed");
11962        pane.update(cx, |pane, cx| {
11963            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
11964            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
11965            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
11966            assert_eq!(pane.items_len(), 1);
11967            assert_eq!(
11968                pane.active_item().unwrap().item_id(),
11969                multi_buffer_with_both_files_id,
11970                "Should have only the multi buffer left in the pane"
11971            );
11972            assert!(
11973                dirty_multi_buffer_with_both.read(cx).is_dirty,
11974                "The multi buffer containing the unsaved buffer should still be dirty"
11975            );
11976        });
11977
11978        dirty_regular_buffer.update(cx, |buffer, cx| {
11979            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
11980        });
11981
11982        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11983            pane.close_active_item(
11984                &CloseActiveItem {
11985                    save_intent: Some(SaveIntent::Close),
11986                    close_pinned: false,
11987                },
11988                window,
11989                cx,
11990            )
11991        });
11992        cx.background_executor.run_until_parked();
11993        assert!(
11994            cx.has_pending_prompt(),
11995            "Dirty multi buffer should prompt a save dialog"
11996        );
11997        cx.simulate_prompt_answer("Save");
11998        cx.background_executor.run_until_parked();
11999        close_multi_buffer_task
12000            .await
12001            .expect("Closing the multi buffer failed");
12002        pane.update(cx, |pane, cx| {
12003            assert_eq!(
12004                dirty_multi_buffer_with_both.read(cx).save_count,
12005                1,
12006                "Multi buffer item should get be saved"
12007            );
12008            // Test impl does not save inner items, so we do not assert them
12009            assert_eq!(
12010                pane.items_len(),
12011                0,
12012                "No more items should be left in the pane"
12013            );
12014            assert!(pane.active_item().is_none());
12015        });
12016    }
12017
12018    #[gpui::test]
12019    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12020        cx: &mut TestAppContext,
12021    ) {
12022        init_test(cx);
12023
12024        let fs = FakeFs::new(cx.background_executor.clone());
12025        let project = Project::test(fs, [], cx).await;
12026        let (workspace, cx) =
12027            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12028        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12029
12030        let dirty_regular_buffer = cx.new(|cx| {
12031            TestItem::new(cx)
12032                .with_dirty(true)
12033                .with_label("1.txt")
12034                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12035        });
12036        let dirty_regular_buffer_2 = cx.new(|cx| {
12037            TestItem::new(cx)
12038                .with_dirty(true)
12039                .with_label("2.txt")
12040                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12041        });
12042        let clear_regular_buffer = cx.new(|cx| {
12043            TestItem::new(cx)
12044                .with_label("3.txt")
12045                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12046        });
12047
12048        let dirty_multi_buffer_with_both = cx.new(|cx| {
12049            TestItem::new(cx)
12050                .with_dirty(true)
12051                .with_buffer_kind(ItemBufferKind::Multibuffer)
12052                .with_label("Fake Project Search")
12053                .with_project_items(&[
12054                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12055                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12056                    clear_regular_buffer.read(cx).project_items[0].clone(),
12057                ])
12058        });
12059        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12060        workspace.update_in(cx, |workspace, window, cx| {
12061            workspace.add_item(
12062                pane.clone(),
12063                Box::new(dirty_regular_buffer.clone()),
12064                None,
12065                false,
12066                false,
12067                window,
12068                cx,
12069            );
12070            workspace.add_item(
12071                pane.clone(),
12072                Box::new(dirty_multi_buffer_with_both.clone()),
12073                None,
12074                false,
12075                false,
12076                window,
12077                cx,
12078            );
12079        });
12080
12081        pane.update_in(cx, |pane, window, cx| {
12082            pane.activate_item(1, true, true, window, cx);
12083            assert_eq!(
12084                pane.active_item().unwrap().item_id(),
12085                multi_buffer_with_both_files_id,
12086                "Should select the multi buffer in the pane"
12087            );
12088        });
12089        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12090            pane.close_active_item(
12091                &CloseActiveItem {
12092                    save_intent: None,
12093                    close_pinned: false,
12094                },
12095                window,
12096                cx,
12097            )
12098        });
12099        cx.background_executor.run_until_parked();
12100        assert!(
12101            cx.has_pending_prompt(),
12102            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12103        );
12104    }
12105
12106    /// Tests that when `close_on_file_delete` is enabled, files are automatically
12107    /// closed when they are deleted from disk.
12108    #[gpui::test]
12109    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12110        init_test(cx);
12111
12112        // Enable the close_on_disk_deletion setting
12113        cx.update_global(|store: &mut SettingsStore, cx| {
12114            store.update_user_settings(cx, |settings| {
12115                settings.workspace.close_on_file_delete = Some(true);
12116            });
12117        });
12118
12119        let fs = FakeFs::new(cx.background_executor.clone());
12120        let project = Project::test(fs, [], cx).await;
12121        let (workspace, cx) =
12122            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12123        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12124
12125        // Create a test item that simulates a file
12126        let item = cx.new(|cx| {
12127            TestItem::new(cx)
12128                .with_label("test.txt")
12129                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12130        });
12131
12132        // Add item to workspace
12133        workspace.update_in(cx, |workspace, window, cx| {
12134            workspace.add_item(
12135                pane.clone(),
12136                Box::new(item.clone()),
12137                None,
12138                false,
12139                false,
12140                window,
12141                cx,
12142            );
12143        });
12144
12145        // Verify the item is in the pane
12146        pane.read_with(cx, |pane, _| {
12147            assert_eq!(pane.items().count(), 1);
12148        });
12149
12150        // Simulate file deletion by setting the item's deleted state
12151        item.update(cx, |item, _| {
12152            item.set_has_deleted_file(true);
12153        });
12154
12155        // Emit UpdateTab event to trigger the close behavior
12156        cx.run_until_parked();
12157        item.update(cx, |_, cx| {
12158            cx.emit(ItemEvent::UpdateTab);
12159        });
12160
12161        // Allow the close operation to complete
12162        cx.run_until_parked();
12163
12164        // Verify the item was automatically closed
12165        pane.read_with(cx, |pane, _| {
12166            assert_eq!(
12167                pane.items().count(),
12168                0,
12169                "Item should be automatically closed when file is deleted"
12170            );
12171        });
12172    }
12173
12174    /// Tests that when `close_on_file_delete` is disabled (default), files remain
12175    /// open with a strikethrough when they are deleted from disk.
12176    #[gpui::test]
12177    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12178        init_test(cx);
12179
12180        // Ensure close_on_disk_deletion is disabled (default)
12181        cx.update_global(|store: &mut SettingsStore, cx| {
12182            store.update_user_settings(cx, |settings| {
12183                settings.workspace.close_on_file_delete = Some(false);
12184            });
12185        });
12186
12187        let fs = FakeFs::new(cx.background_executor.clone());
12188        let project = Project::test(fs, [], cx).await;
12189        let (workspace, cx) =
12190            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12191        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12192
12193        // Create a test item that simulates a file
12194        let item = cx.new(|cx| {
12195            TestItem::new(cx)
12196                .with_label("test.txt")
12197                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12198        });
12199
12200        // Add item to workspace
12201        workspace.update_in(cx, |workspace, window, cx| {
12202            workspace.add_item(
12203                pane.clone(),
12204                Box::new(item.clone()),
12205                None,
12206                false,
12207                false,
12208                window,
12209                cx,
12210            );
12211        });
12212
12213        // Verify the item is in the pane
12214        pane.read_with(cx, |pane, _| {
12215            assert_eq!(pane.items().count(), 1);
12216        });
12217
12218        // Simulate file deletion
12219        item.update(cx, |item, _| {
12220            item.set_has_deleted_file(true);
12221        });
12222
12223        // Emit UpdateTab event
12224        cx.run_until_parked();
12225        item.update(cx, |_, cx| {
12226            cx.emit(ItemEvent::UpdateTab);
12227        });
12228
12229        // Allow any potential close operation to complete
12230        cx.run_until_parked();
12231
12232        // Verify the item remains open (with strikethrough)
12233        pane.read_with(cx, |pane, _| {
12234            assert_eq!(
12235                pane.items().count(),
12236                1,
12237                "Item should remain open when close_on_disk_deletion is disabled"
12238            );
12239        });
12240
12241        // Verify the item shows as deleted
12242        item.read_with(cx, |item, _| {
12243            assert!(
12244                item.has_deleted_file,
12245                "Item should be marked as having deleted file"
12246            );
12247        });
12248    }
12249
12250    /// Tests that dirty files are not automatically closed when deleted from disk,
12251    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12252    /// unsaved changes without being prompted.
12253    #[gpui::test]
12254    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12255        init_test(cx);
12256
12257        // Enable the close_on_file_delete setting
12258        cx.update_global(|store: &mut SettingsStore, cx| {
12259            store.update_user_settings(cx, |settings| {
12260                settings.workspace.close_on_file_delete = Some(true);
12261            });
12262        });
12263
12264        let fs = FakeFs::new(cx.background_executor.clone());
12265        let project = Project::test(fs, [], cx).await;
12266        let (workspace, cx) =
12267            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12268        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12269
12270        // Create a dirty test item
12271        let item = cx.new(|cx| {
12272            TestItem::new(cx)
12273                .with_dirty(true)
12274                .with_label("test.txt")
12275                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12276        });
12277
12278        // Add item to workspace
12279        workspace.update_in(cx, |workspace, window, cx| {
12280            workspace.add_item(
12281                pane.clone(),
12282                Box::new(item.clone()),
12283                None,
12284                false,
12285                false,
12286                window,
12287                cx,
12288            );
12289        });
12290
12291        // Simulate file deletion
12292        item.update(cx, |item, _| {
12293            item.set_has_deleted_file(true);
12294        });
12295
12296        // Emit UpdateTab event to trigger the close behavior
12297        cx.run_until_parked();
12298        item.update(cx, |_, cx| {
12299            cx.emit(ItemEvent::UpdateTab);
12300        });
12301
12302        // Allow any potential close operation to complete
12303        cx.run_until_parked();
12304
12305        // Verify the item remains open (dirty files are not auto-closed)
12306        pane.read_with(cx, |pane, _| {
12307            assert_eq!(
12308                pane.items().count(),
12309                1,
12310                "Dirty items should not be automatically closed even when file is deleted"
12311            );
12312        });
12313
12314        // Verify the item is marked as deleted and still dirty
12315        item.read_with(cx, |item, _| {
12316            assert!(
12317                item.has_deleted_file,
12318                "Item should be marked as having deleted file"
12319            );
12320            assert!(item.is_dirty, "Item should still be dirty");
12321        });
12322    }
12323
12324    /// Tests that navigation history is cleaned up when files are auto-closed
12325    /// due to deletion from disk.
12326    #[gpui::test]
12327    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12328        init_test(cx);
12329
12330        // Enable the close_on_file_delete setting
12331        cx.update_global(|store: &mut SettingsStore, cx| {
12332            store.update_user_settings(cx, |settings| {
12333                settings.workspace.close_on_file_delete = Some(true);
12334            });
12335        });
12336
12337        let fs = FakeFs::new(cx.background_executor.clone());
12338        let project = Project::test(fs, [], cx).await;
12339        let (workspace, cx) =
12340            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12341        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12342
12343        // Create test items
12344        let item1 = cx.new(|cx| {
12345            TestItem::new(cx)
12346                .with_label("test1.txt")
12347                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12348        });
12349        let item1_id = item1.item_id();
12350
12351        let item2 = cx.new(|cx| {
12352            TestItem::new(cx)
12353                .with_label("test2.txt")
12354                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12355        });
12356
12357        // Add items to workspace
12358        workspace.update_in(cx, |workspace, window, cx| {
12359            workspace.add_item(
12360                pane.clone(),
12361                Box::new(item1.clone()),
12362                None,
12363                false,
12364                false,
12365                window,
12366                cx,
12367            );
12368            workspace.add_item(
12369                pane.clone(),
12370                Box::new(item2.clone()),
12371                None,
12372                false,
12373                false,
12374                window,
12375                cx,
12376            );
12377        });
12378
12379        // Activate item1 to ensure it gets navigation entries
12380        pane.update_in(cx, |pane, window, cx| {
12381            pane.activate_item(0, true, true, window, cx);
12382        });
12383
12384        // Switch to item2 and back to create navigation history
12385        pane.update_in(cx, |pane, window, cx| {
12386            pane.activate_item(1, true, true, window, cx);
12387        });
12388        cx.run_until_parked();
12389
12390        pane.update_in(cx, |pane, window, cx| {
12391            pane.activate_item(0, true, true, window, cx);
12392        });
12393        cx.run_until_parked();
12394
12395        // Simulate file deletion for item1
12396        item1.update(cx, |item, _| {
12397            item.set_has_deleted_file(true);
12398        });
12399
12400        // Emit UpdateTab event to trigger the close behavior
12401        item1.update(cx, |_, cx| {
12402            cx.emit(ItemEvent::UpdateTab);
12403        });
12404        cx.run_until_parked();
12405
12406        // Verify item1 was closed
12407        pane.read_with(cx, |pane, _| {
12408            assert_eq!(
12409                pane.items().count(),
12410                1,
12411                "Should have 1 item remaining after auto-close"
12412            );
12413        });
12414
12415        // Check navigation history after close
12416        let has_item = pane.read_with(cx, |pane, cx| {
12417            let mut has_item = false;
12418            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12419                if entry.item.id() == item1_id {
12420                    has_item = true;
12421                }
12422            });
12423            has_item
12424        });
12425
12426        assert!(
12427            !has_item,
12428            "Navigation history should not contain closed item entries"
12429        );
12430    }
12431
12432    #[gpui::test]
12433    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12434        cx: &mut TestAppContext,
12435    ) {
12436        init_test(cx);
12437
12438        let fs = FakeFs::new(cx.background_executor.clone());
12439        let project = Project::test(fs, [], cx).await;
12440        let (workspace, cx) =
12441            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12442        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12443
12444        let dirty_regular_buffer = cx.new(|cx| {
12445            TestItem::new(cx)
12446                .with_dirty(true)
12447                .with_label("1.txt")
12448                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12449        });
12450        let dirty_regular_buffer_2 = cx.new(|cx| {
12451            TestItem::new(cx)
12452                .with_dirty(true)
12453                .with_label("2.txt")
12454                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12455        });
12456        let clear_regular_buffer = cx.new(|cx| {
12457            TestItem::new(cx)
12458                .with_label("3.txt")
12459                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12460        });
12461
12462        let dirty_multi_buffer = cx.new(|cx| {
12463            TestItem::new(cx)
12464                .with_dirty(true)
12465                .with_buffer_kind(ItemBufferKind::Multibuffer)
12466                .with_label("Fake Project Search")
12467                .with_project_items(&[
12468                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12469                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12470                    clear_regular_buffer.read(cx).project_items[0].clone(),
12471                ])
12472        });
12473        workspace.update_in(cx, |workspace, window, cx| {
12474            workspace.add_item(
12475                pane.clone(),
12476                Box::new(dirty_regular_buffer.clone()),
12477                None,
12478                false,
12479                false,
12480                window,
12481                cx,
12482            );
12483            workspace.add_item(
12484                pane.clone(),
12485                Box::new(dirty_regular_buffer_2.clone()),
12486                None,
12487                false,
12488                false,
12489                window,
12490                cx,
12491            );
12492            workspace.add_item(
12493                pane.clone(),
12494                Box::new(dirty_multi_buffer.clone()),
12495                None,
12496                false,
12497                false,
12498                window,
12499                cx,
12500            );
12501        });
12502
12503        pane.update_in(cx, |pane, window, cx| {
12504            pane.activate_item(2, true, true, window, cx);
12505            assert_eq!(
12506                pane.active_item().unwrap().item_id(),
12507                dirty_multi_buffer.item_id(),
12508                "Should select the multi buffer in the pane"
12509            );
12510        });
12511        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12512            pane.close_active_item(
12513                &CloseActiveItem {
12514                    save_intent: None,
12515                    close_pinned: false,
12516                },
12517                window,
12518                cx,
12519            )
12520        });
12521        cx.background_executor.run_until_parked();
12522        assert!(
12523            !cx.has_pending_prompt(),
12524            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12525        );
12526        close_multi_buffer_task
12527            .await
12528            .expect("Closing multi buffer failed");
12529        pane.update(cx, |pane, cx| {
12530            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12531            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12532            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12533            assert_eq!(
12534                pane.items()
12535                    .map(|item| item.item_id())
12536                    .sorted()
12537                    .collect::<Vec<_>>(),
12538                vec![
12539                    dirty_regular_buffer.item_id(),
12540                    dirty_regular_buffer_2.item_id(),
12541                ],
12542                "Should have no multi buffer left in the pane"
12543            );
12544            assert!(dirty_regular_buffer.read(cx).is_dirty);
12545            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12546        });
12547    }
12548
12549    #[gpui::test]
12550    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12551        init_test(cx);
12552        let fs = FakeFs::new(cx.executor());
12553        let project = Project::test(fs, [], cx).await;
12554        let (multi_workspace, cx) =
12555            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12556        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12557
12558        // Add a new panel to the right dock, opening the dock and setting the
12559        // focus to the new panel.
12560        let panel = workspace.update_in(cx, |workspace, window, cx| {
12561            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12562            workspace.add_panel(panel.clone(), window, cx);
12563
12564            workspace
12565                .right_dock()
12566                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12567
12568            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12569
12570            panel
12571        });
12572
12573        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12574        // panel to the next valid position which, in this case, is the left
12575        // dock.
12576        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12577        workspace.update(cx, |workspace, cx| {
12578            assert!(workspace.left_dock().read(cx).is_open());
12579            assert_eq!(panel.read(cx).position, DockPosition::Left);
12580        });
12581
12582        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12583        // panel to the next valid position which, in this case, is the bottom
12584        // dock.
12585        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12586        workspace.update(cx, |workspace, cx| {
12587            assert!(workspace.bottom_dock().read(cx).is_open());
12588            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12589        });
12590
12591        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12592        // around moving the panel to its initial position, the right dock.
12593        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12594        workspace.update(cx, |workspace, cx| {
12595            assert!(workspace.right_dock().read(cx).is_open());
12596            assert_eq!(panel.read(cx).position, DockPosition::Right);
12597        });
12598
12599        // Remove focus from the panel, ensuring that, if the panel is not
12600        // focused, the `MoveFocusedPanelToNextPosition` action does not update
12601        // the panel's position, so the panel is still in the right dock.
12602        workspace.update_in(cx, |workspace, window, cx| {
12603            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12604        });
12605
12606        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12607        workspace.update(cx, |workspace, cx| {
12608            assert!(workspace.right_dock().read(cx).is_open());
12609            assert_eq!(panel.read(cx).position, DockPosition::Right);
12610        });
12611    }
12612
12613    #[gpui::test]
12614    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12615        init_test(cx);
12616
12617        let fs = FakeFs::new(cx.executor());
12618        let project = Project::test(fs, [], cx).await;
12619        let (workspace, cx) =
12620            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12621
12622        let item_1 = cx.new(|cx| {
12623            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12624        });
12625        workspace.update_in(cx, |workspace, window, cx| {
12626            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12627            workspace.move_item_to_pane_in_direction(
12628                &MoveItemToPaneInDirection {
12629                    direction: SplitDirection::Right,
12630                    focus: true,
12631                    clone: false,
12632                },
12633                window,
12634                cx,
12635            );
12636            workspace.move_item_to_pane_at_index(
12637                &MoveItemToPane {
12638                    destination: 3,
12639                    focus: true,
12640                    clone: false,
12641                },
12642                window,
12643                cx,
12644            );
12645
12646            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12647            assert_eq!(
12648                pane_items_paths(&workspace.active_pane, cx),
12649                vec!["first.txt".to_string()],
12650                "Single item was not moved anywhere"
12651            );
12652        });
12653
12654        let item_2 = cx.new(|cx| {
12655            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12656        });
12657        workspace.update_in(cx, |workspace, window, cx| {
12658            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12659            assert_eq!(
12660                pane_items_paths(&workspace.panes[0], cx),
12661                vec!["first.txt".to_string(), "second.txt".to_string()],
12662            );
12663            workspace.move_item_to_pane_in_direction(
12664                &MoveItemToPaneInDirection {
12665                    direction: SplitDirection::Right,
12666                    focus: true,
12667                    clone: false,
12668                },
12669                window,
12670                cx,
12671            );
12672
12673            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12674            assert_eq!(
12675                pane_items_paths(&workspace.panes[0], cx),
12676                vec!["first.txt".to_string()],
12677                "After moving, one item should be left in the original pane"
12678            );
12679            assert_eq!(
12680                pane_items_paths(&workspace.panes[1], cx),
12681                vec!["second.txt".to_string()],
12682                "New item should have been moved to the new pane"
12683            );
12684        });
12685
12686        let item_3 = cx.new(|cx| {
12687            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12688        });
12689        workspace.update_in(cx, |workspace, window, cx| {
12690            let original_pane = workspace.panes[0].clone();
12691            workspace.set_active_pane(&original_pane, window, cx);
12692            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12693            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12694            assert_eq!(
12695                pane_items_paths(&workspace.active_pane, cx),
12696                vec!["first.txt".to_string(), "third.txt".to_string()],
12697                "New pane should be ready to move one item out"
12698            );
12699
12700            workspace.move_item_to_pane_at_index(
12701                &MoveItemToPane {
12702                    destination: 3,
12703                    focus: true,
12704                    clone: false,
12705                },
12706                window,
12707                cx,
12708            );
12709            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12710            assert_eq!(
12711                pane_items_paths(&workspace.active_pane, cx),
12712                vec!["first.txt".to_string()],
12713                "After moving, one item should be left in the original pane"
12714            );
12715            assert_eq!(
12716                pane_items_paths(&workspace.panes[1], cx),
12717                vec!["second.txt".to_string()],
12718                "Previously created pane should be unchanged"
12719            );
12720            assert_eq!(
12721                pane_items_paths(&workspace.panes[2], cx),
12722                vec!["third.txt".to_string()],
12723                "New item should have been moved to the new pane"
12724            );
12725        });
12726    }
12727
12728    #[gpui::test]
12729    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12730        init_test(cx);
12731
12732        let fs = FakeFs::new(cx.executor());
12733        let project = Project::test(fs, [], cx).await;
12734        let (workspace, cx) =
12735            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12736
12737        let item_1 = cx.new(|cx| {
12738            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12739        });
12740        workspace.update_in(cx, |workspace, window, cx| {
12741            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12742            workspace.move_item_to_pane_in_direction(
12743                &MoveItemToPaneInDirection {
12744                    direction: SplitDirection::Right,
12745                    focus: true,
12746                    clone: true,
12747                },
12748                window,
12749                cx,
12750            );
12751        });
12752        cx.run_until_parked();
12753        workspace.update_in(cx, |workspace, window, cx| {
12754            workspace.move_item_to_pane_at_index(
12755                &MoveItemToPane {
12756                    destination: 3,
12757                    focus: true,
12758                    clone: true,
12759                },
12760                window,
12761                cx,
12762            );
12763        });
12764        cx.run_until_parked();
12765
12766        workspace.update(cx, |workspace, cx| {
12767            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
12768            for pane in workspace.panes() {
12769                assert_eq!(
12770                    pane_items_paths(pane, cx),
12771                    vec!["first.txt".to_string()],
12772                    "Single item exists in all panes"
12773                );
12774            }
12775        });
12776
12777        // verify that the active pane has been updated after waiting for the
12778        // pane focus event to fire and resolve
12779        workspace.read_with(cx, |workspace, _app| {
12780            assert_eq!(
12781                workspace.active_pane(),
12782                &workspace.panes[2],
12783                "The third pane should be the active one: {:?}",
12784                workspace.panes
12785            );
12786        })
12787    }
12788
12789    #[gpui::test]
12790    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
12791        init_test(cx);
12792
12793        let fs = FakeFs::new(cx.executor());
12794        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
12795
12796        let project = Project::test(fs, ["root".as_ref()], cx).await;
12797        let (workspace, cx) =
12798            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12799
12800        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12801        // Add item to pane A with project path
12802        let item_a = cx.new(|cx| {
12803            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12804        });
12805        workspace.update_in(cx, |workspace, window, cx| {
12806            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
12807        });
12808
12809        // Split to create pane B
12810        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
12811            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
12812        });
12813
12814        // Add item with SAME project path to pane B, and pin it
12815        let item_b = cx.new(|cx| {
12816            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12817        });
12818        pane_b.update_in(cx, |pane, window, cx| {
12819            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12820            pane.set_pinned_count(1);
12821        });
12822
12823        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
12824        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
12825
12826        // close_pinned: false should only close the unpinned copy
12827        workspace.update_in(cx, |workspace, window, cx| {
12828            workspace.close_item_in_all_panes(
12829                &CloseItemInAllPanes {
12830                    save_intent: Some(SaveIntent::Close),
12831                    close_pinned: false,
12832                },
12833                window,
12834                cx,
12835            )
12836        });
12837        cx.executor().run_until_parked();
12838
12839        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
12840        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12841        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
12842        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
12843
12844        // Split again, seeing as closing the previous item also closed its
12845        // pane, so only pane remains, which does not allow us to properly test
12846        // that both items close when `close_pinned: true`.
12847        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
12848            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
12849        });
12850
12851        // Add an item with the same project path to pane C so that
12852        // close_item_in_all_panes can determine what to close across all panes
12853        // (it reads the active item from the active pane, and split_pane
12854        // creates an empty pane).
12855        let item_c = cx.new(|cx| {
12856            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12857        });
12858        pane_c.update_in(cx, |pane, window, cx| {
12859            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
12860        });
12861
12862        // close_pinned: true should close the pinned copy too
12863        workspace.update_in(cx, |workspace, window, cx| {
12864            let panes_count = workspace.panes().len();
12865            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
12866
12867            workspace.close_item_in_all_panes(
12868                &CloseItemInAllPanes {
12869                    save_intent: Some(SaveIntent::Close),
12870                    close_pinned: true,
12871                },
12872                window,
12873                cx,
12874            )
12875        });
12876        cx.executor().run_until_parked();
12877
12878        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12879        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
12880        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
12881        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
12882    }
12883
12884    mod register_project_item_tests {
12885
12886        use super::*;
12887
12888        // View
12889        struct TestPngItemView {
12890            focus_handle: FocusHandle,
12891        }
12892        // Model
12893        struct TestPngItem {}
12894
12895        impl project::ProjectItem for TestPngItem {
12896            fn try_open(
12897                _project: &Entity<Project>,
12898                path: &ProjectPath,
12899                cx: &mut App,
12900            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12901                if path.path.extension().unwrap() == "png" {
12902                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
12903                } else {
12904                    None
12905                }
12906            }
12907
12908            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12909                None
12910            }
12911
12912            fn project_path(&self, _: &App) -> Option<ProjectPath> {
12913                None
12914            }
12915
12916            fn is_dirty(&self) -> bool {
12917                false
12918            }
12919        }
12920
12921        impl Item for TestPngItemView {
12922            type Event = ();
12923            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12924                "".into()
12925            }
12926        }
12927        impl EventEmitter<()> for TestPngItemView {}
12928        impl Focusable for TestPngItemView {
12929            fn focus_handle(&self, _cx: &App) -> FocusHandle {
12930                self.focus_handle.clone()
12931            }
12932        }
12933
12934        impl Render for TestPngItemView {
12935            fn render(
12936                &mut self,
12937                _window: &mut Window,
12938                _cx: &mut Context<Self>,
12939            ) -> impl IntoElement {
12940                Empty
12941            }
12942        }
12943
12944        impl ProjectItem for TestPngItemView {
12945            type Item = TestPngItem;
12946
12947            fn for_project_item(
12948                _project: Entity<Project>,
12949                _pane: Option<&Pane>,
12950                _item: Entity<Self::Item>,
12951                _: &mut Window,
12952                cx: &mut Context<Self>,
12953            ) -> Self
12954            where
12955                Self: Sized,
12956            {
12957                Self {
12958                    focus_handle: cx.focus_handle(),
12959                }
12960            }
12961        }
12962
12963        // View
12964        struct TestIpynbItemView {
12965            focus_handle: FocusHandle,
12966        }
12967        // Model
12968        struct TestIpynbItem {}
12969
12970        impl project::ProjectItem for TestIpynbItem {
12971            fn try_open(
12972                _project: &Entity<Project>,
12973                path: &ProjectPath,
12974                cx: &mut App,
12975            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12976                if path.path.extension().unwrap() == "ipynb" {
12977                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
12978                } else {
12979                    None
12980                }
12981            }
12982
12983            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12984                None
12985            }
12986
12987            fn project_path(&self, _: &App) -> Option<ProjectPath> {
12988                None
12989            }
12990
12991            fn is_dirty(&self) -> bool {
12992                false
12993            }
12994        }
12995
12996        impl Item for TestIpynbItemView {
12997            type Event = ();
12998            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12999                "".into()
13000            }
13001        }
13002        impl EventEmitter<()> for TestIpynbItemView {}
13003        impl Focusable for TestIpynbItemView {
13004            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13005                self.focus_handle.clone()
13006            }
13007        }
13008
13009        impl Render for TestIpynbItemView {
13010            fn render(
13011                &mut self,
13012                _window: &mut Window,
13013                _cx: &mut Context<Self>,
13014            ) -> impl IntoElement {
13015                Empty
13016            }
13017        }
13018
13019        impl ProjectItem for TestIpynbItemView {
13020            type Item = TestIpynbItem;
13021
13022            fn for_project_item(
13023                _project: Entity<Project>,
13024                _pane: Option<&Pane>,
13025                _item: Entity<Self::Item>,
13026                _: &mut Window,
13027                cx: &mut Context<Self>,
13028            ) -> Self
13029            where
13030                Self: Sized,
13031            {
13032                Self {
13033                    focus_handle: cx.focus_handle(),
13034                }
13035            }
13036        }
13037
13038        struct TestAlternatePngItemView {
13039            focus_handle: FocusHandle,
13040        }
13041
13042        impl Item for TestAlternatePngItemView {
13043            type Event = ();
13044            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13045                "".into()
13046            }
13047        }
13048
13049        impl EventEmitter<()> for TestAlternatePngItemView {}
13050        impl Focusable for TestAlternatePngItemView {
13051            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13052                self.focus_handle.clone()
13053            }
13054        }
13055
13056        impl Render for TestAlternatePngItemView {
13057            fn render(
13058                &mut self,
13059                _window: &mut Window,
13060                _cx: &mut Context<Self>,
13061            ) -> impl IntoElement {
13062                Empty
13063            }
13064        }
13065
13066        impl ProjectItem for TestAlternatePngItemView {
13067            type Item = TestPngItem;
13068
13069            fn for_project_item(
13070                _project: Entity<Project>,
13071                _pane: Option<&Pane>,
13072                _item: Entity<Self::Item>,
13073                _: &mut Window,
13074                cx: &mut Context<Self>,
13075            ) -> Self
13076            where
13077                Self: Sized,
13078            {
13079                Self {
13080                    focus_handle: cx.focus_handle(),
13081                }
13082            }
13083        }
13084
13085        #[gpui::test]
13086        async fn test_register_project_item(cx: &mut TestAppContext) {
13087            init_test(cx);
13088
13089            cx.update(|cx| {
13090                register_project_item::<TestPngItemView>(cx);
13091                register_project_item::<TestIpynbItemView>(cx);
13092            });
13093
13094            let fs = FakeFs::new(cx.executor());
13095            fs.insert_tree(
13096                "/root1",
13097                json!({
13098                    "one.png": "BINARYDATAHERE",
13099                    "two.ipynb": "{ totally a notebook }",
13100                    "three.txt": "editing text, sure why not?"
13101                }),
13102            )
13103            .await;
13104
13105            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13106            let (workspace, cx) =
13107                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13108
13109            let worktree_id = project.update(cx, |project, cx| {
13110                project.worktrees(cx).next().unwrap().read(cx).id()
13111            });
13112
13113            let handle = workspace
13114                .update_in(cx, |workspace, window, cx| {
13115                    let project_path = (worktree_id, rel_path("one.png"));
13116                    workspace.open_path(project_path, None, true, window, cx)
13117                })
13118                .await
13119                .unwrap();
13120
13121            // Now we can check if the handle we got back errored or not
13122            assert_eq!(
13123                handle.to_any_view().entity_type(),
13124                TypeId::of::<TestPngItemView>()
13125            );
13126
13127            let handle = workspace
13128                .update_in(cx, |workspace, window, cx| {
13129                    let project_path = (worktree_id, rel_path("two.ipynb"));
13130                    workspace.open_path(project_path, None, true, window, cx)
13131                })
13132                .await
13133                .unwrap();
13134
13135            assert_eq!(
13136                handle.to_any_view().entity_type(),
13137                TypeId::of::<TestIpynbItemView>()
13138            );
13139
13140            let handle = workspace
13141                .update_in(cx, |workspace, window, cx| {
13142                    let project_path = (worktree_id, rel_path("three.txt"));
13143                    workspace.open_path(project_path, None, true, window, cx)
13144                })
13145                .await;
13146            assert!(handle.is_err());
13147        }
13148
13149        #[gpui::test]
13150        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13151            init_test(cx);
13152
13153            cx.update(|cx| {
13154                register_project_item::<TestPngItemView>(cx);
13155                register_project_item::<TestAlternatePngItemView>(cx);
13156            });
13157
13158            let fs = FakeFs::new(cx.executor());
13159            fs.insert_tree(
13160                "/root1",
13161                json!({
13162                    "one.png": "BINARYDATAHERE",
13163                    "two.ipynb": "{ totally a notebook }",
13164                    "three.txt": "editing text, sure why not?"
13165                }),
13166            )
13167            .await;
13168            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13169            let (workspace, cx) =
13170                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13171            let worktree_id = project.update(cx, |project, cx| {
13172                project.worktrees(cx).next().unwrap().read(cx).id()
13173            });
13174
13175            let handle = workspace
13176                .update_in(cx, |workspace, window, cx| {
13177                    let project_path = (worktree_id, rel_path("one.png"));
13178                    workspace.open_path(project_path, None, true, window, cx)
13179                })
13180                .await
13181                .unwrap();
13182
13183            // This _must_ be the second item registered
13184            assert_eq!(
13185                handle.to_any_view().entity_type(),
13186                TypeId::of::<TestAlternatePngItemView>()
13187            );
13188
13189            let handle = workspace
13190                .update_in(cx, |workspace, window, cx| {
13191                    let project_path = (worktree_id, rel_path("three.txt"));
13192                    workspace.open_path(project_path, None, true, window, cx)
13193                })
13194                .await;
13195            assert!(handle.is_err());
13196        }
13197    }
13198
13199    #[gpui::test]
13200    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13201        init_test(cx);
13202
13203        let fs = FakeFs::new(cx.executor());
13204        let project = Project::test(fs, [], cx).await;
13205        let (workspace, _cx) =
13206            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13207
13208        // Test with status bar shown (default)
13209        workspace.read_with(cx, |workspace, cx| {
13210            let visible = workspace.status_bar_visible(cx);
13211            assert!(visible, "Status bar should be visible by default");
13212        });
13213
13214        // Test with status bar hidden
13215        cx.update_global(|store: &mut SettingsStore, cx| {
13216            store.update_user_settings(cx, |settings| {
13217                settings.status_bar.get_or_insert_default().show = Some(false);
13218            });
13219        });
13220
13221        workspace.read_with(cx, |workspace, cx| {
13222            let visible = workspace.status_bar_visible(cx);
13223            assert!(!visible, "Status bar should be hidden when show is false");
13224        });
13225
13226        // Test with status bar shown explicitly
13227        cx.update_global(|store: &mut SettingsStore, cx| {
13228            store.update_user_settings(cx, |settings| {
13229                settings.status_bar.get_or_insert_default().show = Some(true);
13230            });
13231        });
13232
13233        workspace.read_with(cx, |workspace, cx| {
13234            let visible = workspace.status_bar_visible(cx);
13235            assert!(visible, "Status bar should be visible when show is true");
13236        });
13237    }
13238
13239    #[gpui::test]
13240    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13241        init_test(cx);
13242
13243        let fs = FakeFs::new(cx.executor());
13244        let project = Project::test(fs, [], cx).await;
13245        let (multi_workspace, cx) =
13246            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13247        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13248        let panel = workspace.update_in(cx, |workspace, window, cx| {
13249            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13250            workspace.add_panel(panel.clone(), window, cx);
13251
13252            workspace
13253                .right_dock()
13254                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13255
13256            panel
13257        });
13258
13259        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13260        let item_a = cx.new(TestItem::new);
13261        let item_b = cx.new(TestItem::new);
13262        let item_a_id = item_a.entity_id();
13263        let item_b_id = item_b.entity_id();
13264
13265        pane.update_in(cx, |pane, window, cx| {
13266            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13267            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13268        });
13269
13270        pane.read_with(cx, |pane, _| {
13271            assert_eq!(pane.items_len(), 2);
13272            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13273        });
13274
13275        workspace.update_in(cx, |workspace, window, cx| {
13276            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13277        });
13278
13279        workspace.update_in(cx, |_, window, cx| {
13280            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13281        });
13282
13283        // Assert that the `pane::CloseActiveItem` action is handled at the
13284        // workspace level when one of the dock panels is focused and, in that
13285        // case, the center pane's active item is closed but the focus is not
13286        // moved.
13287        cx.dispatch_action(pane::CloseActiveItem::default());
13288        cx.run_until_parked();
13289
13290        pane.read_with(cx, |pane, _| {
13291            assert_eq!(pane.items_len(), 1);
13292            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13293        });
13294
13295        workspace.update_in(cx, |workspace, window, cx| {
13296            assert!(workspace.right_dock().read(cx).is_open());
13297            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13298        });
13299    }
13300
13301    #[gpui::test]
13302    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13303        init_test(cx);
13304        let fs = FakeFs::new(cx.executor());
13305
13306        let project_a = Project::test(fs.clone(), [], cx).await;
13307        let project_b = Project::test(fs, [], cx).await;
13308
13309        let multi_workspace_handle =
13310            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13311        cx.run_until_parked();
13312
13313        let workspace_a = multi_workspace_handle
13314            .read_with(cx, |mw, _| mw.workspace().clone())
13315            .unwrap();
13316
13317        let _workspace_b = multi_workspace_handle
13318            .update(cx, |mw, window, cx| {
13319                mw.test_add_workspace(project_b, window, cx)
13320            })
13321            .unwrap();
13322
13323        // Switch to workspace A
13324        multi_workspace_handle
13325            .update(cx, |mw, window, cx| {
13326                mw.activate_index(0, window, cx);
13327            })
13328            .unwrap();
13329
13330        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13331
13332        // Add a panel to workspace A's right dock and open the dock
13333        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13334            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13335            workspace.add_panel(panel.clone(), window, cx);
13336            workspace
13337                .right_dock()
13338                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13339            panel
13340        });
13341
13342        // Focus the panel through the workspace (matching existing test pattern)
13343        workspace_a.update_in(cx, |workspace, window, cx| {
13344            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13345        });
13346
13347        // Zoom the panel
13348        panel.update_in(cx, |panel, window, cx| {
13349            panel.set_zoomed(true, window, cx);
13350        });
13351
13352        // Verify the panel is zoomed and the dock is open
13353        workspace_a.update_in(cx, |workspace, window, cx| {
13354            assert!(
13355                workspace.right_dock().read(cx).is_open(),
13356                "dock should be open before switch"
13357            );
13358            assert!(
13359                panel.is_zoomed(window, cx),
13360                "panel should be zoomed before switch"
13361            );
13362            assert!(
13363                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13364                "panel should be focused before switch"
13365            );
13366        });
13367
13368        // Switch to workspace B
13369        multi_workspace_handle
13370            .update(cx, |mw, window, cx| {
13371                mw.activate_index(1, window, cx);
13372            })
13373            .unwrap();
13374        cx.run_until_parked();
13375
13376        // Switch back to workspace A
13377        multi_workspace_handle
13378            .update(cx, |mw, window, cx| {
13379                mw.activate_index(0, window, cx);
13380            })
13381            .unwrap();
13382        cx.run_until_parked();
13383
13384        // Verify the panel is still zoomed and the dock is still open
13385        workspace_a.update_in(cx, |workspace, window, cx| {
13386            assert!(
13387                workspace.right_dock().read(cx).is_open(),
13388                "dock should still be open after switching back"
13389            );
13390            assert!(
13391                panel.is_zoomed(window, cx),
13392                "panel should still be zoomed after switching back"
13393            );
13394        });
13395    }
13396
13397    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13398        pane.read(cx)
13399            .items()
13400            .flat_map(|item| {
13401                item.project_paths(cx)
13402                    .into_iter()
13403                    .map(|path| path.path.display(PathStyle::local()).into_owned())
13404            })
13405            .collect()
13406    }
13407
13408    pub fn init_test(cx: &mut TestAppContext) {
13409        cx.update(|cx| {
13410            let settings_store = SettingsStore::test(cx);
13411            cx.set_global(settings_store);
13412            theme::init(theme::LoadThemes::JustBase, cx);
13413        });
13414    }
13415
13416    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13417        let item = TestProjectItem::new(id, path, cx);
13418        item.update(cx, |item, _| {
13419            item.is_dirty = true;
13420        });
13421        item
13422    }
13423
13424    #[gpui::test]
13425    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13426        cx: &mut gpui::TestAppContext,
13427    ) {
13428        init_test(cx);
13429        let fs = FakeFs::new(cx.executor());
13430
13431        let project = Project::test(fs, [], cx).await;
13432        let (workspace, cx) =
13433            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13434
13435        let panel = workspace.update_in(cx, |workspace, window, cx| {
13436            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13437            workspace.add_panel(panel.clone(), window, cx);
13438            workspace
13439                .right_dock()
13440                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13441            panel
13442        });
13443
13444        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13445        pane.update_in(cx, |pane, window, cx| {
13446            let item = cx.new(TestItem::new);
13447            pane.add_item(Box::new(item), true, true, None, window, cx);
13448        });
13449
13450        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13451        // mirrors the real-world flow and avoids side effects from directly
13452        // focusing the panel while the center pane is active.
13453        workspace.update_in(cx, |workspace, window, cx| {
13454            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13455        });
13456
13457        panel.update_in(cx, |panel, window, cx| {
13458            panel.set_zoomed(true, window, cx);
13459        });
13460
13461        workspace.update_in(cx, |workspace, window, cx| {
13462            assert!(workspace.right_dock().read(cx).is_open());
13463            assert!(panel.is_zoomed(window, cx));
13464            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13465        });
13466
13467        // Simulate a spurious pane::Event::Focus on the center pane while the
13468        // panel still has focus. This mirrors what happens during macOS window
13469        // activation: the center pane fires a focus event even though actual
13470        // focus remains on the dock panel.
13471        pane.update_in(cx, |_, _, cx| {
13472            cx.emit(pane::Event::Focus);
13473        });
13474
13475        // The dock must remain open because the panel had focus at the time the
13476        // event was processed. Before the fix, dock_to_preserve was None for
13477        // panels that don't implement pane(), causing the dock to close.
13478        workspace.update_in(cx, |workspace, window, cx| {
13479            assert!(
13480                workspace.right_dock().read(cx).is_open(),
13481                "Dock should stay open when its zoomed panel (without pane()) still has focus"
13482            );
13483            assert!(panel.is_zoomed(window, cx));
13484        });
13485    }
13486}