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, MultiWorkspaceEvent, Sidebar,
   31    SidebarHandle, ToggleWorkspaceSidebar,
   32};
   33pub use path_list::{PathList, SerializedPathList};
   34pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   35
   36use anyhow::{Context as _, Result, anyhow};
   37use client::{
   38    ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
   39    proto::{self, ErrorCode, PanelId, PeerId},
   40};
   41use collections::{HashMap, HashSet, hash_map};
   42use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   43use fs::Fs;
   44use futures::{
   45    Future, FutureExt, StreamExt,
   46    channel::{
   47        mpsc::{self, UnboundedReceiver, UnboundedSender},
   48        oneshot,
   49    },
   50    future::{Shared, try_join_all},
   51};
   52use gpui::{
   53    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
   54    CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   55    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   56    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   57    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   58    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   59};
   60pub use history_manager::*;
   61pub use item::{
   62    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   63    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   64};
   65use itertools::Itertools;
   66use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   67pub use modal_layer::*;
   68use node_runtime::NodeRuntime;
   69use notifications::{
   70    DetachAndPromptErr, Notifications, dismiss_app_notification,
   71    simple_message_notification::MessageNotification,
   72};
   73pub use pane::*;
   74pub use pane_group::{
   75    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   76    SplitDirection,
   77};
   78use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
   79pub use persistence::{
   80    WorkspaceDb, delete_unloaded_items,
   81    model::{
   82        DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
   83        SessionWorkspace,
   84    },
   85    read_serialized_multi_workspaces, resolve_worktree_workspaces,
   86};
   87use postage::stream::Stream;
   88use project::{
   89    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
   90    WorktreeSettings,
   91    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   92    project_settings::ProjectSettings,
   93    toolchain_store::ToolchainStoreEvent,
   94    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
   95};
   96use remote::{
   97    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
   98    remote_client::ConnectionIdentifier,
   99};
  100use schemars::JsonSchema;
  101use serde::Deserialize;
  102use session::AppSession;
  103use settings::{
  104    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  105};
  106
  107use sqlez::{
  108    bindable::{Bind, Column, StaticColumnCount},
  109    statement::Statement,
  110};
  111use status_bar::StatusBar;
  112pub use status_bar::StatusItemView;
  113use std::{
  114    any::TypeId,
  115    borrow::Cow,
  116    cell::RefCell,
  117    cmp,
  118    collections::VecDeque,
  119    env,
  120    hash::Hash,
  121    path::{Path, PathBuf},
  122    process::ExitStatus,
  123    rc::Rc,
  124    sync::{
  125        Arc, LazyLock, Weak,
  126        atomic::{AtomicBool, AtomicUsize},
  127    },
  128    time::Duration,
  129};
  130use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  131use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
  132pub use toolbar::{
  133    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  134};
  135pub use ui;
  136use ui::{Window, prelude::*};
  137use util::{
  138    ResultExt, TryFutureExt,
  139    paths::{PathStyle, SanitizedPath},
  140    rel_path::RelPath,
  141    serde::default_true,
  142};
  143use uuid::Uuid;
  144pub use workspace_settings::{
  145    AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
  146    WorkspaceSettings,
  147};
  148use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
  149
  150use crate::{item::ItemBufferKind, notifications::NotificationId};
  151use crate::{
  152    persistence::{
  153        SerializedAxis,
  154        model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
  155    },
  156    security_modal::SecurityModal,
  157};
  158
  159pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  160
  161static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  162    env::var("ZED_WINDOW_SIZE")
  163        .ok()
  164        .as_deref()
  165        .and_then(parse_pixel_size_env_var)
  166});
  167
  168static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  169    env::var("ZED_WINDOW_POSITION")
  170        .ok()
  171        .as_deref()
  172        .and_then(parse_pixel_position_env_var)
  173});
  174
  175pub trait TerminalProvider {
  176    fn spawn(
  177        &self,
  178        task: SpawnInTerminal,
  179        window: &mut Window,
  180        cx: &mut App,
  181    ) -> Task<Option<Result<ExitStatus>>>;
  182}
  183
  184pub trait DebuggerProvider {
  185    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  186    fn start_session(
  187        &self,
  188        definition: DebugScenario,
  189        task_context: SharedTaskContext,
  190        active_buffer: Option<Entity<Buffer>>,
  191        worktree_id: Option<WorktreeId>,
  192        window: &mut Window,
  193        cx: &mut App,
  194    );
  195
  196    fn spawn_task_or_modal(
  197        &self,
  198        workspace: &mut Workspace,
  199        action: &Spawn,
  200        window: &mut Window,
  201        cx: &mut Context<Workspace>,
  202    );
  203
  204    fn task_scheduled(&self, cx: &mut App);
  205    fn debug_scenario_scheduled(&self, cx: &mut App);
  206    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  207
  208    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  209}
  210
  211/// Opens a file or directory.
  212#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  213#[action(namespace = workspace)]
  214pub struct Open {
  215    /// When true, opens in a new window. When false, adds to the current
  216    /// window as a new workspace (multi-workspace).
  217    #[serde(default = "Open::default_create_new_window")]
  218    pub create_new_window: bool,
  219}
  220
  221impl Open {
  222    pub const DEFAULT: Self = Self {
  223        create_new_window: true,
  224    };
  225
  226    /// Used by `#[serde(default)]` on the `create_new_window` field so that
  227    /// the serde default and `Open::DEFAULT` stay in sync.
  228    fn default_create_new_window() -> bool {
  229        Self::DEFAULT.create_new_window
  230    }
  231}
  232
  233impl Default for Open {
  234    fn default() -> Self {
  235        Self::DEFAULT
  236    }
  237}
  238
  239actions!(
  240    workspace,
  241    [
  242        /// Activates the next pane in the workspace.
  243        ActivateNextPane,
  244        /// Activates the previous pane in the workspace.
  245        ActivatePreviousPane,
  246        /// Activates the last pane in the workspace.
  247        ActivateLastPane,
  248        /// Switches to the next window.
  249        ActivateNextWindow,
  250        /// Switches to the previous window.
  251        ActivatePreviousWindow,
  252        /// Adds a folder to the current project.
  253        AddFolderToProject,
  254        /// Clears all notifications.
  255        ClearAllNotifications,
  256        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  257        ClearNavigationHistory,
  258        /// Closes the active dock.
  259        CloseActiveDock,
  260        /// Closes all docks.
  261        CloseAllDocks,
  262        /// Toggles all docks.
  263        ToggleAllDocks,
  264        /// Closes the current window.
  265        CloseWindow,
  266        /// Closes the current project.
  267        CloseProject,
  268        /// Opens the feedback dialog.
  269        Feedback,
  270        /// Follows the next collaborator in the session.
  271        FollowNextCollaborator,
  272        /// Moves the focused panel to the next position.
  273        MoveFocusedPanelToNextPosition,
  274        /// Creates a new file.
  275        NewFile,
  276        /// Creates a new file in a vertical split.
  277        NewFileSplitVertical,
  278        /// Creates a new file in a horizontal split.
  279        NewFileSplitHorizontal,
  280        /// Opens a new search.
  281        NewSearch,
  282        /// Opens a new window.
  283        NewWindow,
  284        /// Opens multiple files.
  285        OpenFiles,
  286        /// Opens the current location in terminal.
  287        OpenInTerminal,
  288        /// Opens the component preview.
  289        OpenComponentPreview,
  290        /// Reloads the active item.
  291        ReloadActiveItem,
  292        /// Resets the active dock to its default size.
  293        ResetActiveDockSize,
  294        /// Resets all open docks to their default sizes.
  295        ResetOpenDocksSize,
  296        /// Reloads the application
  297        Reload,
  298        /// Saves the current file with a new name.
  299        SaveAs,
  300        /// Saves without formatting.
  301        SaveWithoutFormat,
  302        /// Shuts down all debug adapters.
  303        ShutdownDebugAdapters,
  304        /// Suppresses the current notification.
  305        SuppressNotification,
  306        /// Toggles the bottom dock.
  307        ToggleBottomDock,
  308        /// Toggles centered layout mode.
  309        ToggleCenteredLayout,
  310        /// Toggles edit prediction feature globally for all files.
  311        ToggleEditPrediction,
  312        /// Toggles the left dock.
  313        ToggleLeftDock,
  314        /// Toggles the right dock.
  315        ToggleRightDock,
  316        /// Toggles zoom on the active pane.
  317        ToggleZoom,
  318        /// Toggles read-only mode for the active item (if supported by that item).
  319        ToggleReadOnlyFile,
  320        /// Zooms in on the active pane.
  321        ZoomIn,
  322        /// Zooms out of the active pane.
  323        ZoomOut,
  324        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  325        /// If the modal is shown already, closes it without trusting any worktree.
  326        ToggleWorktreeSecurity,
  327        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  328        /// Requires restart to take effect on already opened projects.
  329        ClearTrustedWorktrees,
  330        /// Stops following a collaborator.
  331        Unfollow,
  332        /// Restores the banner.
  333        RestoreBanner,
  334        /// Toggles expansion of the selected item.
  335        ToggleExpandItem,
  336    ]
  337);
  338
  339/// Activates a specific pane by its index.
  340#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  341#[action(namespace = workspace)]
  342pub struct ActivatePane(pub usize);
  343
  344/// Moves an item to a specific pane by index.
  345#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  346#[action(namespace = workspace)]
  347#[serde(deny_unknown_fields)]
  348pub struct MoveItemToPane {
  349    #[serde(default = "default_1")]
  350    pub destination: usize,
  351    #[serde(default = "default_true")]
  352    pub focus: bool,
  353    #[serde(default)]
  354    pub clone: bool,
  355}
  356
  357fn default_1() -> usize {
  358    1
  359}
  360
  361/// Moves an item to a pane in the specified direction.
  362#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  363#[action(namespace = workspace)]
  364#[serde(deny_unknown_fields)]
  365pub struct MoveItemToPaneInDirection {
  366    #[serde(default = "default_right")]
  367    pub direction: SplitDirection,
  368    #[serde(default = "default_true")]
  369    pub focus: bool,
  370    #[serde(default)]
  371    pub clone: bool,
  372}
  373
  374/// Creates a new file in a split of the desired direction.
  375#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  376#[action(namespace = workspace)]
  377#[serde(deny_unknown_fields)]
  378pub struct NewFileSplit(pub SplitDirection);
  379
  380fn default_right() -> SplitDirection {
  381    SplitDirection::Right
  382}
  383
  384/// Saves all open files in the workspace.
  385#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  386#[action(namespace = workspace)]
  387#[serde(deny_unknown_fields)]
  388pub struct SaveAll {
  389    #[serde(default)]
  390    pub save_intent: Option<SaveIntent>,
  391}
  392
  393/// Saves the current file with the specified options.
  394#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  395#[action(namespace = workspace)]
  396#[serde(deny_unknown_fields)]
  397pub struct Save {
  398    #[serde(default)]
  399    pub save_intent: Option<SaveIntent>,
  400}
  401
  402/// Moves Focus to the central panes in the workspace.
  403#[derive(Clone, Debug, PartialEq, Eq, Action)]
  404#[action(namespace = workspace)]
  405pub struct FocusCenterPane;
  406
  407///  Closes all items and panes in the workspace.
  408#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  409#[action(namespace = workspace)]
  410#[serde(deny_unknown_fields)]
  411pub struct CloseAllItemsAndPanes {
  412    #[serde(default)]
  413    pub save_intent: Option<SaveIntent>,
  414}
  415
  416/// Closes all inactive tabs and panes in the workspace.
  417#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  418#[action(namespace = workspace)]
  419#[serde(deny_unknown_fields)]
  420pub struct CloseInactiveTabsAndPanes {
  421    #[serde(default)]
  422    pub save_intent: Option<SaveIntent>,
  423}
  424
  425/// Closes the active item across all panes.
  426#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  427#[action(namespace = workspace)]
  428#[serde(deny_unknown_fields)]
  429pub struct CloseItemInAllPanes {
  430    #[serde(default)]
  431    pub save_intent: Option<SaveIntent>,
  432    #[serde(default)]
  433    pub close_pinned: bool,
  434}
  435
  436/// Sends a sequence of keystrokes to the active element.
  437#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  438#[action(namespace = workspace)]
  439pub struct SendKeystrokes(pub String);
  440
  441actions!(
  442    project_symbols,
  443    [
  444        /// Toggles the project symbols search.
  445        #[action(name = "Toggle")]
  446        ToggleProjectSymbols
  447    ]
  448);
  449
  450/// Toggles the file finder interface.
  451#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  452#[action(namespace = file_finder, name = "Toggle")]
  453#[serde(deny_unknown_fields)]
  454pub struct ToggleFileFinder {
  455    #[serde(default)]
  456    pub separate_history: bool,
  457}
  458
  459/// Opens a new terminal in the center.
  460#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  461#[action(namespace = workspace)]
  462#[serde(deny_unknown_fields)]
  463pub struct NewCenterTerminal {
  464    /// If true, creates a local terminal even in remote projects.
  465    #[serde(default)]
  466    pub local: bool,
  467}
  468
  469/// Opens a new terminal.
  470#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  471#[action(namespace = workspace)]
  472#[serde(deny_unknown_fields)]
  473pub struct NewTerminal {
  474    /// If true, creates a local terminal even in remote projects.
  475    #[serde(default)]
  476    pub local: bool,
  477}
  478
  479/// Increases size of a currently focused dock by a given amount of pixels.
  480#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  481#[action(namespace = workspace)]
  482#[serde(deny_unknown_fields)]
  483pub struct IncreaseActiveDockSize {
  484    /// For 0px parameter, uses UI font size value.
  485    #[serde(default)]
  486    pub px: u32,
  487}
  488
  489/// Decreases size of a currently focused dock by a given amount of pixels.
  490#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  491#[action(namespace = workspace)]
  492#[serde(deny_unknown_fields)]
  493pub struct DecreaseActiveDockSize {
  494    /// For 0px parameter, uses UI font size value.
  495    #[serde(default)]
  496    pub px: u32,
  497}
  498
  499/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  500#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  501#[action(namespace = workspace)]
  502#[serde(deny_unknown_fields)]
  503pub struct IncreaseOpenDocksSize {
  504    /// For 0px parameter, uses UI font size value.
  505    #[serde(default)]
  506    pub px: u32,
  507}
  508
  509/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  510#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  511#[action(namespace = workspace)]
  512#[serde(deny_unknown_fields)]
  513pub struct DecreaseOpenDocksSize {
  514    /// For 0px parameter, uses UI font size value.
  515    #[serde(default)]
  516    pub px: u32,
  517}
  518
  519actions!(
  520    workspace,
  521    [
  522        /// Activates the pane to the left.
  523        ActivatePaneLeft,
  524        /// Activates the pane to the right.
  525        ActivatePaneRight,
  526        /// Activates the pane above.
  527        ActivatePaneUp,
  528        /// Activates the pane below.
  529        ActivatePaneDown,
  530        /// Swaps the current pane with the one to the left.
  531        SwapPaneLeft,
  532        /// Swaps the current pane with the one to the right.
  533        SwapPaneRight,
  534        /// Swaps the current pane with the one above.
  535        SwapPaneUp,
  536        /// Swaps the current pane with the one below.
  537        SwapPaneDown,
  538        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  539        SwapPaneAdjacent,
  540        /// Move the current pane to be at the far left.
  541        MovePaneLeft,
  542        /// Move the current pane to be at the far right.
  543        MovePaneRight,
  544        /// Move the current pane to be at the very top.
  545        MovePaneUp,
  546        /// Move the current pane to be at the very bottom.
  547        MovePaneDown,
  548    ]
  549);
  550
  551#[derive(PartialEq, Eq, Debug)]
  552pub enum CloseIntent {
  553    /// Quit the program entirely.
  554    Quit,
  555    /// Close a window.
  556    CloseWindow,
  557    /// Replace the workspace in an existing window.
  558    ReplaceWindow,
  559}
  560
  561#[derive(Clone)]
  562pub struct Toast {
  563    id: NotificationId,
  564    msg: Cow<'static, str>,
  565    autohide: bool,
  566    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  567}
  568
  569impl Toast {
  570    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  571        Toast {
  572            id,
  573            msg: msg.into(),
  574            on_click: None,
  575            autohide: false,
  576        }
  577    }
  578
  579    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  580    where
  581        M: Into<Cow<'static, str>>,
  582        F: Fn(&mut Window, &mut App) + 'static,
  583    {
  584        self.on_click = Some((message.into(), Arc::new(on_click)));
  585        self
  586    }
  587
  588    pub fn autohide(mut self) -> Self {
  589        self.autohide = true;
  590        self
  591    }
  592}
  593
  594impl PartialEq for Toast {
  595    fn eq(&self, other: &Self) -> bool {
  596        self.id == other.id
  597            && self.msg == other.msg
  598            && self.on_click.is_some() == other.on_click.is_some()
  599    }
  600}
  601
  602/// Opens a new terminal with the specified working directory.
  603#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  604#[action(namespace = workspace)]
  605#[serde(deny_unknown_fields)]
  606pub struct OpenTerminal {
  607    pub working_directory: PathBuf,
  608    /// If true, creates a local terminal even in remote projects.
  609    #[serde(default)]
  610    pub local: bool,
  611}
  612
  613#[derive(
  614    Clone,
  615    Copy,
  616    Debug,
  617    Default,
  618    Hash,
  619    PartialEq,
  620    Eq,
  621    PartialOrd,
  622    Ord,
  623    serde::Serialize,
  624    serde::Deserialize,
  625)]
  626pub struct WorkspaceId(i64);
  627
  628impl WorkspaceId {
  629    pub fn from_i64(value: i64) -> Self {
  630        Self(value)
  631    }
  632}
  633
  634impl StaticColumnCount for WorkspaceId {}
  635impl Bind for WorkspaceId {
  636    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  637        self.0.bind(statement, start_index)
  638    }
  639}
  640impl Column for WorkspaceId {
  641    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  642        i64::column(statement, start_index)
  643            .map(|(i, next_index)| (Self(i), next_index))
  644            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  645    }
  646}
  647impl From<WorkspaceId> for i64 {
  648    fn from(val: WorkspaceId) -> Self {
  649        val.0
  650    }
  651}
  652
  653fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
  654    if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
  655        workspace_window
  656            .update(cx, |multi_workspace, window, cx| {
  657                let workspace = multi_workspace.workspace().clone();
  658                workspace.update(cx, |workspace, cx| {
  659                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  660                });
  661            })
  662            .ok();
  663    } else {
  664        let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, true, cx);
  665        cx.spawn(async move |cx| {
  666            let OpenResult { window, .. } = task.await?;
  667            window.update(cx, |multi_workspace, window, cx| {
  668                window.activate_window();
  669                let workspace = multi_workspace.workspace().clone();
  670                workspace.update(cx, |workspace, cx| {
  671                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  672                });
  673            })?;
  674            anyhow::Ok(())
  675        })
  676        .detach_and_log_err(cx);
  677    }
  678}
  679
  680pub fn prompt_for_open_path_and_open(
  681    workspace: &mut Workspace,
  682    app_state: Arc<AppState>,
  683    options: PathPromptOptions,
  684    create_new_window: bool,
  685    window: &mut Window,
  686    cx: &mut Context<Workspace>,
  687) {
  688    let paths = workspace.prompt_for_open_path(
  689        options,
  690        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  691        window,
  692        cx,
  693    );
  694    let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
  695    cx.spawn_in(window, async move |this, cx| {
  696        let Some(paths) = paths.await.log_err().flatten() else {
  697            return;
  698        };
  699        if !create_new_window {
  700            if let Some(handle) = multi_workspace_handle {
  701                if let Some(task) = handle
  702                    .update(cx, |multi_workspace, window, cx| {
  703                        multi_workspace.open_project(paths, window, cx)
  704                    })
  705                    .log_err()
  706                {
  707                    task.await.log_err();
  708                }
  709                return;
  710            }
  711        }
  712        if let Some(task) = this
  713            .update_in(cx, |this, window, cx| {
  714                this.open_workspace_for_paths(false, paths, window, cx)
  715            })
  716            .log_err()
  717        {
  718            task.await.log_err();
  719        }
  720    })
  721    .detach();
  722}
  723
  724pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  725    component::init();
  726    theme_preview::init(cx);
  727    toast_layer::init(cx);
  728    history_manager::init(app_state.fs.clone(), cx);
  729
  730    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  731        .on_action(|_: &Reload, cx| reload(cx))
  732        .on_action({
  733            let app_state = Arc::downgrade(&app_state);
  734            move |_: &Open, cx: &mut App| {
  735                if let Some(app_state) = app_state.upgrade() {
  736                    prompt_and_open_paths(
  737                        app_state,
  738                        PathPromptOptions {
  739                            files: true,
  740                            directories: true,
  741                            multiple: true,
  742                            prompt: None,
  743                        },
  744                        cx,
  745                    );
  746                }
  747            }
  748        })
  749        .on_action({
  750            let app_state = Arc::downgrade(&app_state);
  751            move |_: &OpenFiles, cx: &mut App| {
  752                let directories = cx.can_select_mixed_files_and_dirs();
  753                if let Some(app_state) = app_state.upgrade() {
  754                    prompt_and_open_paths(
  755                        app_state,
  756                        PathPromptOptions {
  757                            files: true,
  758                            directories,
  759                            multiple: true,
  760                            prompt: None,
  761                        },
  762                        cx,
  763                    );
  764                }
  765            }
  766        });
  767}
  768
  769type BuildProjectItemFn =
  770    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  771
  772type BuildProjectItemForPathFn =
  773    fn(
  774        &Entity<Project>,
  775        &ProjectPath,
  776        &mut Window,
  777        &mut App,
  778    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  779
  780#[derive(Clone, Default)]
  781struct ProjectItemRegistry {
  782    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  783    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  784}
  785
  786impl ProjectItemRegistry {
  787    fn register<T: ProjectItem>(&mut self) {
  788        self.build_project_item_fns_by_type.insert(
  789            TypeId::of::<T::Item>(),
  790            |item, project, pane, window, cx| {
  791                let item = item.downcast().unwrap();
  792                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  793                    as Box<dyn ItemHandle>
  794            },
  795        );
  796        self.build_project_item_for_path_fns
  797            .push(|project, project_path, window, cx| {
  798                let project_path = project_path.clone();
  799                let is_file = project
  800                    .read(cx)
  801                    .entry_for_path(&project_path, cx)
  802                    .is_some_and(|entry| entry.is_file());
  803                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  804                let is_local = project.read(cx).is_local();
  805                let project_item =
  806                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  807                let project = project.clone();
  808                Some(window.spawn(cx, async move |cx| {
  809                    match project_item.await.with_context(|| {
  810                        format!(
  811                            "opening project path {:?}",
  812                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  813                        )
  814                    }) {
  815                        Ok(project_item) => {
  816                            let project_item = project_item;
  817                            let project_entry_id: Option<ProjectEntryId> =
  818                                project_item.read_with(cx, project::ProjectItem::entry_id);
  819                            let build_workspace_item = Box::new(
  820                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  821                                    Box::new(cx.new(|cx| {
  822                                        T::for_project_item(
  823                                            project,
  824                                            Some(pane),
  825                                            project_item,
  826                                            window,
  827                                            cx,
  828                                        )
  829                                    })) as Box<dyn ItemHandle>
  830                                },
  831                            ) as Box<_>;
  832                            Ok((project_entry_id, build_workspace_item))
  833                        }
  834                        Err(e) => {
  835                            log::warn!("Failed to open a project item: {e:#}");
  836                            if e.error_code() == ErrorCode::Internal {
  837                                if let Some(abs_path) =
  838                                    entry_abs_path.as_deref().filter(|_| is_file)
  839                                {
  840                                    if let Some(broken_project_item_view) =
  841                                        cx.update(|window, cx| {
  842                                            T::for_broken_project_item(
  843                                                abs_path, is_local, &e, window, cx,
  844                                            )
  845                                        })?
  846                                    {
  847                                        let build_workspace_item = Box::new(
  848                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  849                                                cx.new(|_| broken_project_item_view).boxed_clone()
  850                                            },
  851                                        )
  852                                        as Box<_>;
  853                                        return Ok((None, build_workspace_item));
  854                                    }
  855                                }
  856                            }
  857                            Err(e)
  858                        }
  859                    }
  860                }))
  861            });
  862    }
  863
  864    fn open_path(
  865        &self,
  866        project: &Entity<Project>,
  867        path: &ProjectPath,
  868        window: &mut Window,
  869        cx: &mut App,
  870    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  871        let Some(open_project_item) = self
  872            .build_project_item_for_path_fns
  873            .iter()
  874            .rev()
  875            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  876        else {
  877            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  878        };
  879        open_project_item
  880    }
  881
  882    fn build_item<T: project::ProjectItem>(
  883        &self,
  884        item: Entity<T>,
  885        project: Entity<Project>,
  886        pane: Option<&Pane>,
  887        window: &mut Window,
  888        cx: &mut App,
  889    ) -> Option<Box<dyn ItemHandle>> {
  890        let build = self
  891            .build_project_item_fns_by_type
  892            .get(&TypeId::of::<T>())?;
  893        Some(build(item.into_any(), project, pane, window, cx))
  894    }
  895}
  896
  897type WorkspaceItemBuilder =
  898    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  899
  900impl Global for ProjectItemRegistry {}
  901
  902/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  903/// items will get a chance to open the file, starting from the project item that
  904/// was added last.
  905pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  906    cx.default_global::<ProjectItemRegistry>().register::<I>();
  907}
  908
  909#[derive(Default)]
  910pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  911
  912struct FollowableViewDescriptor {
  913    from_state_proto: fn(
  914        Entity<Workspace>,
  915        ViewId,
  916        &mut Option<proto::view::Variant>,
  917        &mut Window,
  918        &mut App,
  919    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  920    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  921}
  922
  923impl Global for FollowableViewRegistry {}
  924
  925impl FollowableViewRegistry {
  926    pub fn register<I: FollowableItem>(cx: &mut App) {
  927        cx.default_global::<Self>().0.insert(
  928            TypeId::of::<I>(),
  929            FollowableViewDescriptor {
  930                from_state_proto: |workspace, id, state, window, cx| {
  931                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  932                        cx.foreground_executor()
  933                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  934                    })
  935                },
  936                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  937            },
  938        );
  939    }
  940
  941    pub fn from_state_proto(
  942        workspace: Entity<Workspace>,
  943        view_id: ViewId,
  944        mut state: Option<proto::view::Variant>,
  945        window: &mut Window,
  946        cx: &mut App,
  947    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  948        cx.update_default_global(|this: &mut Self, cx| {
  949            this.0.values().find_map(|descriptor| {
  950                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  951            })
  952        })
  953    }
  954
  955    pub fn to_followable_view(
  956        view: impl Into<AnyView>,
  957        cx: &App,
  958    ) -> Option<Box<dyn FollowableItemHandle>> {
  959        let this = cx.try_global::<Self>()?;
  960        let view = view.into();
  961        let descriptor = this.0.get(&view.entity_type())?;
  962        Some((descriptor.to_followable_view)(&view))
  963    }
  964}
  965
  966#[derive(Copy, Clone)]
  967struct SerializableItemDescriptor {
  968    deserialize: fn(
  969        Entity<Project>,
  970        WeakEntity<Workspace>,
  971        WorkspaceId,
  972        ItemId,
  973        &mut Window,
  974        &mut Context<Pane>,
  975    ) -> Task<Result<Box<dyn ItemHandle>>>,
  976    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  977    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  978}
  979
  980#[derive(Default)]
  981struct SerializableItemRegistry {
  982    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  983    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  984}
  985
  986impl Global for SerializableItemRegistry {}
  987
  988impl SerializableItemRegistry {
  989    fn deserialize(
  990        item_kind: &str,
  991        project: Entity<Project>,
  992        workspace: WeakEntity<Workspace>,
  993        workspace_id: WorkspaceId,
  994        item_item: ItemId,
  995        window: &mut Window,
  996        cx: &mut Context<Pane>,
  997    ) -> Task<Result<Box<dyn ItemHandle>>> {
  998        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  999            return Task::ready(Err(anyhow!(
 1000                "cannot deserialize {}, descriptor not found",
 1001                item_kind
 1002            )));
 1003        };
 1004
 1005        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
 1006    }
 1007
 1008    fn cleanup(
 1009        item_kind: &str,
 1010        workspace_id: WorkspaceId,
 1011        loaded_items: Vec<ItemId>,
 1012        window: &mut Window,
 1013        cx: &mut App,
 1014    ) -> Task<Result<()>> {
 1015        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1016            return Task::ready(Err(anyhow!(
 1017                "cannot cleanup {}, descriptor not found",
 1018                item_kind
 1019            )));
 1020        };
 1021
 1022        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
 1023    }
 1024
 1025    fn view_to_serializable_item_handle(
 1026        view: AnyView,
 1027        cx: &App,
 1028    ) -> Option<Box<dyn SerializableItemHandle>> {
 1029        let this = cx.try_global::<Self>()?;
 1030        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
 1031        Some((descriptor.view_to_serializable_item)(view))
 1032    }
 1033
 1034    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
 1035        let this = cx.try_global::<Self>()?;
 1036        this.descriptors_by_kind.get(item_kind).copied()
 1037    }
 1038}
 1039
 1040pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
 1041    let serialized_item_kind = I::serialized_item_kind();
 1042
 1043    let registry = cx.default_global::<SerializableItemRegistry>();
 1044    let descriptor = SerializableItemDescriptor {
 1045        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
 1046            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
 1047            cx.foreground_executor()
 1048                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 1049        },
 1050        cleanup: |workspace_id, loaded_items, window, cx| {
 1051            I::cleanup(workspace_id, loaded_items, window, cx)
 1052        },
 1053        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1054    };
 1055    registry
 1056        .descriptors_by_kind
 1057        .insert(Arc::from(serialized_item_kind), descriptor);
 1058    registry
 1059        .descriptors_by_type
 1060        .insert(TypeId::of::<I>(), descriptor);
 1061}
 1062
 1063pub struct AppState {
 1064    pub languages: Arc<LanguageRegistry>,
 1065    pub client: Arc<Client>,
 1066    pub user_store: Entity<UserStore>,
 1067    pub workspace_store: Entity<WorkspaceStore>,
 1068    pub fs: Arc<dyn fs::Fs>,
 1069    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1070    pub node_runtime: NodeRuntime,
 1071    pub session: Entity<AppSession>,
 1072}
 1073
 1074struct GlobalAppState(Weak<AppState>);
 1075
 1076impl Global for GlobalAppState {}
 1077
 1078pub struct WorkspaceStore {
 1079    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1080    client: Arc<Client>,
 1081    _subscriptions: Vec<client::Subscription>,
 1082}
 1083
 1084#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1085pub enum CollaboratorId {
 1086    PeerId(PeerId),
 1087    Agent,
 1088}
 1089
 1090impl From<PeerId> for CollaboratorId {
 1091    fn from(peer_id: PeerId) -> Self {
 1092        CollaboratorId::PeerId(peer_id)
 1093    }
 1094}
 1095
 1096impl From<&PeerId> for CollaboratorId {
 1097    fn from(peer_id: &PeerId) -> Self {
 1098        CollaboratorId::PeerId(*peer_id)
 1099    }
 1100}
 1101
 1102#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1103struct Follower {
 1104    project_id: Option<u64>,
 1105    peer_id: PeerId,
 1106}
 1107
 1108impl AppState {
 1109    #[track_caller]
 1110    pub fn global(cx: &App) -> Weak<Self> {
 1111        cx.global::<GlobalAppState>().0.clone()
 1112    }
 1113    pub fn try_global(cx: &App) -> Option<Weak<Self>> {
 1114        cx.try_global::<GlobalAppState>()
 1115            .map(|state| state.0.clone())
 1116    }
 1117    pub fn set_global(state: Weak<AppState>, cx: &mut App) {
 1118        cx.set_global(GlobalAppState(state));
 1119    }
 1120
 1121    #[cfg(any(test, feature = "test-support"))]
 1122    pub fn test(cx: &mut App) -> Arc<Self> {
 1123        use fs::Fs;
 1124        use node_runtime::NodeRuntime;
 1125        use session::Session;
 1126        use settings::SettingsStore;
 1127
 1128        if !cx.has_global::<SettingsStore>() {
 1129            let settings_store = SettingsStore::test(cx);
 1130            cx.set_global(settings_store);
 1131        }
 1132
 1133        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1134        <dyn Fs>::set_global(fs.clone(), cx);
 1135        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1136        let clock = Arc::new(clock::FakeSystemClock::new());
 1137        let http_client = http_client::FakeHttpClient::with_404_response();
 1138        let client = Client::new(clock, http_client, cx);
 1139        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1140        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1141        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1142
 1143        theme::init(theme::LoadThemes::JustBase, cx);
 1144        client::init(&client, cx);
 1145
 1146        Arc::new(Self {
 1147            client,
 1148            fs,
 1149            languages,
 1150            user_store,
 1151            workspace_store,
 1152            node_runtime: NodeRuntime::unavailable(),
 1153            build_window_options: |_, _| Default::default(),
 1154            session,
 1155        })
 1156    }
 1157}
 1158
 1159struct DelayedDebouncedEditAction {
 1160    task: Option<Task<()>>,
 1161    cancel_channel: Option<oneshot::Sender<()>>,
 1162}
 1163
 1164impl DelayedDebouncedEditAction {
 1165    fn new() -> DelayedDebouncedEditAction {
 1166        DelayedDebouncedEditAction {
 1167            task: None,
 1168            cancel_channel: None,
 1169        }
 1170    }
 1171
 1172    fn fire_new<F>(
 1173        &mut self,
 1174        delay: Duration,
 1175        window: &mut Window,
 1176        cx: &mut Context<Workspace>,
 1177        func: F,
 1178    ) where
 1179        F: 'static
 1180            + Send
 1181            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1182    {
 1183        if let Some(channel) = self.cancel_channel.take() {
 1184            _ = channel.send(());
 1185        }
 1186
 1187        let (sender, mut receiver) = oneshot::channel::<()>();
 1188        self.cancel_channel = Some(sender);
 1189
 1190        let previous_task = self.task.take();
 1191        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1192            let mut timer = cx.background_executor().timer(delay).fuse();
 1193            if let Some(previous_task) = previous_task {
 1194                previous_task.await;
 1195            }
 1196
 1197            futures::select_biased! {
 1198                _ = receiver => return,
 1199                    _ = timer => {}
 1200            }
 1201
 1202            if let Some(result) = workspace
 1203                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1204                .log_err()
 1205            {
 1206                result.await.log_err();
 1207            }
 1208        }));
 1209    }
 1210}
 1211
 1212pub enum Event {
 1213    PaneAdded(Entity<Pane>),
 1214    PaneRemoved,
 1215    ItemAdded {
 1216        item: Box<dyn ItemHandle>,
 1217    },
 1218    ActiveItemChanged,
 1219    ItemRemoved {
 1220        item_id: EntityId,
 1221    },
 1222    UserSavedItem {
 1223        pane: WeakEntity<Pane>,
 1224        item: Box<dyn WeakItemHandle>,
 1225        save_intent: SaveIntent,
 1226    },
 1227    ContactRequestedJoin(u64),
 1228    WorkspaceCreated(WeakEntity<Workspace>),
 1229    OpenBundledFile {
 1230        text: Cow<'static, str>,
 1231        title: &'static str,
 1232        language: &'static str,
 1233    },
 1234    ZoomChanged,
 1235    ModalOpened,
 1236    Activate,
 1237    PanelAdded(AnyView),
 1238}
 1239
 1240#[derive(Debug, Clone)]
 1241pub enum OpenVisible {
 1242    All,
 1243    None,
 1244    OnlyFiles,
 1245    OnlyDirectories,
 1246}
 1247
 1248enum WorkspaceLocation {
 1249    // Valid local paths or SSH project to serialize
 1250    Location(SerializedWorkspaceLocation, PathList),
 1251    // No valid location found hence clear session id
 1252    DetachFromSession,
 1253    // No valid location found to serialize
 1254    None,
 1255}
 1256
 1257type PromptForNewPath = Box<
 1258    dyn Fn(
 1259        &mut Workspace,
 1260        DirectoryLister,
 1261        Option<String>,
 1262        &mut Window,
 1263        &mut Context<Workspace>,
 1264    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1265>;
 1266
 1267type PromptForOpenPath = Box<
 1268    dyn Fn(
 1269        &mut Workspace,
 1270        DirectoryLister,
 1271        &mut Window,
 1272        &mut Context<Workspace>,
 1273    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1274>;
 1275
 1276#[derive(Default)]
 1277struct DispatchingKeystrokes {
 1278    dispatched: HashSet<Vec<Keystroke>>,
 1279    queue: VecDeque<Keystroke>,
 1280    task: Option<Shared<Task<()>>>,
 1281}
 1282
 1283/// Collects everything project-related for a certain window opened.
 1284/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1285///
 1286/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1287/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1288/// that can be used to register a global action to be triggered from any place in the window.
 1289pub struct Workspace {
 1290    weak_self: WeakEntity<Self>,
 1291    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1292    zoomed: Option<AnyWeakView>,
 1293    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1294    zoomed_position: Option<DockPosition>,
 1295    center: PaneGroup,
 1296    left_dock: Entity<Dock>,
 1297    bottom_dock: Entity<Dock>,
 1298    right_dock: Entity<Dock>,
 1299    panes: Vec<Entity<Pane>>,
 1300    active_worktree_override: Option<WorktreeId>,
 1301    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1302    active_pane: Entity<Pane>,
 1303    last_active_center_pane: Option<WeakEntity<Pane>>,
 1304    last_active_view_id: Option<proto::ViewId>,
 1305    status_bar: Entity<StatusBar>,
 1306    pub(crate) modal_layer: Entity<ModalLayer>,
 1307    toast_layer: Entity<ToastLayer>,
 1308    titlebar_item: Option<AnyView>,
 1309    notifications: Notifications,
 1310    suppressed_notifications: HashSet<NotificationId>,
 1311    project: Entity<Project>,
 1312    follower_states: HashMap<CollaboratorId, FollowerState>,
 1313    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1314    window_edited: bool,
 1315    last_window_title: Option<String>,
 1316    dirty_items: HashMap<EntityId, Subscription>,
 1317    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1318    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1319    database_id: Option<WorkspaceId>,
 1320    app_state: Arc<AppState>,
 1321    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1322    _subscriptions: Vec<Subscription>,
 1323    _apply_leader_updates: Task<Result<()>>,
 1324    _observe_current_user: Task<Result<()>>,
 1325    _schedule_serialize_workspace: Option<Task<()>>,
 1326    _serialize_workspace_task: Option<Task<()>>,
 1327    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1328    pane_history_timestamp: Arc<AtomicUsize>,
 1329    bounds: Bounds<Pixels>,
 1330    pub centered_layout: bool,
 1331    bounds_save_task_queued: Option<Task<()>>,
 1332    on_prompt_for_new_path: Option<PromptForNewPath>,
 1333    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1334    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1335    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1336    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1337    _items_serializer: Task<Result<()>>,
 1338    session_id: Option<String>,
 1339    scheduled_tasks: Vec<Task<()>>,
 1340    last_open_dock_positions: Vec<DockPosition>,
 1341    removing: bool,
 1342    _panels_task: Option<Task<Result<()>>>,
 1343    sidebar_focus_handle: Option<FocusHandle>,
 1344}
 1345
 1346impl EventEmitter<Event> for Workspace {}
 1347
 1348#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1349pub struct ViewId {
 1350    pub creator: CollaboratorId,
 1351    pub id: u64,
 1352}
 1353
 1354pub struct FollowerState {
 1355    center_pane: Entity<Pane>,
 1356    dock_pane: Option<Entity<Pane>>,
 1357    active_view_id: Option<ViewId>,
 1358    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1359}
 1360
 1361struct FollowerView {
 1362    view: Box<dyn FollowableItemHandle>,
 1363    location: Option<proto::PanelId>,
 1364}
 1365
 1366impl Workspace {
 1367    pub fn new(
 1368        workspace_id: Option<WorkspaceId>,
 1369        project: Entity<Project>,
 1370        app_state: Arc<AppState>,
 1371        window: &mut Window,
 1372        cx: &mut Context<Self>,
 1373    ) -> Self {
 1374        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1375            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1376                if let TrustedWorktreesEvent::Trusted(..) = e {
 1377                    // Do not persist auto trusted worktrees
 1378                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1379                        worktrees_store.update(cx, |worktrees_store, cx| {
 1380                            worktrees_store.schedule_serialization(
 1381                                cx,
 1382                                |new_trusted_worktrees, cx| {
 1383                                    let timeout =
 1384                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1385                                    let db = WorkspaceDb::global(cx);
 1386                                    cx.background_spawn(async move {
 1387                                        timeout.await;
 1388                                        db.save_trusted_worktrees(new_trusted_worktrees)
 1389                                            .await
 1390                                            .log_err();
 1391                                    })
 1392                                },
 1393                            )
 1394                        });
 1395                    }
 1396                }
 1397            })
 1398            .detach();
 1399
 1400            cx.observe_global::<SettingsStore>(|_, cx| {
 1401                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1402                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1403                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1404                            trusted_worktrees.auto_trust_all(cx);
 1405                        })
 1406                    }
 1407                }
 1408            })
 1409            .detach();
 1410        }
 1411
 1412        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1413            match event {
 1414                project::Event::RemoteIdChanged(_) => {
 1415                    this.update_window_title(window, cx);
 1416                }
 1417
 1418                project::Event::CollaboratorLeft(peer_id) => {
 1419                    this.collaborator_left(*peer_id, window, cx);
 1420                }
 1421
 1422                &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
 1423                    this.update_window_title(window, cx);
 1424                    if this
 1425                        .project()
 1426                        .read(cx)
 1427                        .worktree_for_id(id, cx)
 1428                        .is_some_and(|wt| wt.read(cx).is_visible())
 1429                    {
 1430                        this.serialize_workspace(window, cx);
 1431                        this.update_history(cx);
 1432                    }
 1433                }
 1434                project::Event::WorktreeUpdatedEntries(..) => {
 1435                    this.update_window_title(window, cx);
 1436                    this.serialize_workspace(window, cx);
 1437                }
 1438
 1439                project::Event::DisconnectedFromHost => {
 1440                    this.update_window_edited(window, cx);
 1441                    let leaders_to_unfollow =
 1442                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1443                    for leader_id in leaders_to_unfollow {
 1444                        this.unfollow(leader_id, window, cx);
 1445                    }
 1446                }
 1447
 1448                project::Event::DisconnectedFromRemote {
 1449                    server_not_running: _,
 1450                } => {
 1451                    this.update_window_edited(window, cx);
 1452                }
 1453
 1454                project::Event::Closed => {
 1455                    window.remove_window();
 1456                }
 1457
 1458                project::Event::DeletedEntry(_, entry_id) => {
 1459                    for pane in this.panes.iter() {
 1460                        pane.update(cx, |pane, cx| {
 1461                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1462                        });
 1463                    }
 1464                }
 1465
 1466                project::Event::Toast {
 1467                    notification_id,
 1468                    message,
 1469                    link,
 1470                } => this.show_notification(
 1471                    NotificationId::named(notification_id.clone()),
 1472                    cx,
 1473                    |cx| {
 1474                        let mut notification = MessageNotification::new(message.clone(), cx);
 1475                        if let Some(link) = link {
 1476                            notification = notification
 1477                                .more_info_message(link.label)
 1478                                .more_info_url(link.url);
 1479                        }
 1480
 1481                        cx.new(|_| notification)
 1482                    },
 1483                ),
 1484
 1485                project::Event::HideToast { notification_id } => {
 1486                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1487                }
 1488
 1489                project::Event::LanguageServerPrompt(request) => {
 1490                    struct LanguageServerPrompt;
 1491
 1492                    this.show_notification(
 1493                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1494                        cx,
 1495                        |cx| {
 1496                            cx.new(|cx| {
 1497                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1498                            })
 1499                        },
 1500                    );
 1501                }
 1502
 1503                project::Event::AgentLocationChanged => {
 1504                    this.handle_agent_location_changed(window, cx)
 1505                }
 1506
 1507                _ => {}
 1508            }
 1509            cx.notify()
 1510        })
 1511        .detach();
 1512
 1513        cx.subscribe_in(
 1514            &project.read(cx).breakpoint_store(),
 1515            window,
 1516            |workspace, _, event, window, cx| match event {
 1517                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1518                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1519                    workspace.serialize_workspace(window, cx);
 1520                }
 1521                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1522            },
 1523        )
 1524        .detach();
 1525        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1526            cx.subscribe_in(
 1527                &toolchain_store,
 1528                window,
 1529                |workspace, _, event, window, cx| match event {
 1530                    ToolchainStoreEvent::CustomToolchainsModified => {
 1531                        workspace.serialize_workspace(window, cx);
 1532                    }
 1533                    _ => {}
 1534                },
 1535            )
 1536            .detach();
 1537        }
 1538
 1539        cx.on_focus_lost(window, |this, window, cx| {
 1540            let focus_handle = this.focus_handle(cx);
 1541            window.focus(&focus_handle, cx);
 1542        })
 1543        .detach();
 1544
 1545        let weak_handle = cx.entity().downgrade();
 1546        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1547
 1548        let center_pane = cx.new(|cx| {
 1549            let mut center_pane = Pane::new(
 1550                weak_handle.clone(),
 1551                project.clone(),
 1552                pane_history_timestamp.clone(),
 1553                None,
 1554                NewFile.boxed_clone(),
 1555                true,
 1556                window,
 1557                cx,
 1558            );
 1559            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1560            center_pane.set_should_display_welcome_page(true);
 1561            center_pane
 1562        });
 1563        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1564            .detach();
 1565
 1566        window.focus(&center_pane.focus_handle(cx), cx);
 1567
 1568        cx.emit(Event::PaneAdded(center_pane.clone()));
 1569
 1570        let any_window_handle = window.window_handle();
 1571        app_state.workspace_store.update(cx, |store, _| {
 1572            store
 1573                .workspaces
 1574                .insert((any_window_handle, weak_handle.clone()));
 1575        });
 1576
 1577        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1578        let mut connection_status = app_state.client.status();
 1579        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1580            current_user.next().await;
 1581            connection_status.next().await;
 1582            let mut stream =
 1583                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1584
 1585            while stream.recv().await.is_some() {
 1586                this.update(cx, |_, cx| cx.notify())?;
 1587            }
 1588            anyhow::Ok(())
 1589        });
 1590
 1591        // All leader updates are enqueued and then processed in a single task, so
 1592        // that each asynchronous operation can be run in order.
 1593        let (leader_updates_tx, mut leader_updates_rx) =
 1594            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1595        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1596            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1597                Self::process_leader_update(&this, leader_id, update, cx)
 1598                    .await
 1599                    .log_err();
 1600            }
 1601
 1602            Ok(())
 1603        });
 1604
 1605        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1606        let modal_layer = cx.new(|_| ModalLayer::new());
 1607        let toast_layer = cx.new(|_| ToastLayer::new());
 1608        cx.subscribe(
 1609            &modal_layer,
 1610            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1611                cx.emit(Event::ModalOpened);
 1612            },
 1613        )
 1614        .detach();
 1615
 1616        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1617        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1618        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1619        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1620        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1621        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1622        let status_bar = cx.new(|cx| {
 1623            let mut status_bar = StatusBar::new(&center_pane.clone(), window, cx);
 1624            status_bar.add_left_item(left_dock_buttons, window, cx);
 1625            status_bar.add_right_item(right_dock_buttons, window, cx);
 1626            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1627            status_bar
 1628        });
 1629
 1630        let session_id = app_state.session.read(cx).id().to_owned();
 1631
 1632        let mut active_call = None;
 1633        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1634            let subscriptions =
 1635                vec![
 1636                    call.0
 1637                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1638                ];
 1639            active_call = Some((call, subscriptions));
 1640        }
 1641
 1642        let (serializable_items_tx, serializable_items_rx) =
 1643            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1644        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1645            Self::serialize_items(&this, serializable_items_rx, cx).await
 1646        });
 1647
 1648        let subscriptions = vec![
 1649            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1650            cx.observe_window_bounds(window, move |this, window, cx| {
 1651                if this.bounds_save_task_queued.is_some() {
 1652                    return;
 1653                }
 1654                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1655                    cx.background_executor()
 1656                        .timer(Duration::from_millis(100))
 1657                        .await;
 1658                    this.update_in(cx, |this, window, cx| {
 1659                        this.save_window_bounds(window, cx).detach();
 1660                        this.bounds_save_task_queued.take();
 1661                    })
 1662                    .ok();
 1663                }));
 1664                cx.notify();
 1665            }),
 1666            cx.observe_window_appearance(window, |_, window, cx| {
 1667                let window_appearance = window.appearance();
 1668
 1669                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1670
 1671                GlobalTheme::reload_theme(cx);
 1672                GlobalTheme::reload_icon_theme(cx);
 1673            }),
 1674            cx.on_release({
 1675                let weak_handle = weak_handle.clone();
 1676                move |this, cx| {
 1677                    this.app_state.workspace_store.update(cx, move |store, _| {
 1678                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1679                    })
 1680                }
 1681            }),
 1682        ];
 1683
 1684        cx.defer_in(window, move |this, window, cx| {
 1685            this.update_window_title(window, cx);
 1686            this.show_initial_notifications(cx);
 1687        });
 1688
 1689        let mut center = PaneGroup::new(center_pane.clone());
 1690        center.set_is_center(true);
 1691        center.mark_positions(cx);
 1692
 1693        Workspace {
 1694            weak_self: weak_handle.clone(),
 1695            zoomed: None,
 1696            zoomed_position: None,
 1697            previous_dock_drag_coordinates: None,
 1698            center,
 1699            panes: vec![center_pane.clone()],
 1700            panes_by_item: Default::default(),
 1701            active_pane: center_pane.clone(),
 1702            last_active_center_pane: Some(center_pane.downgrade()),
 1703            last_active_view_id: None,
 1704            status_bar,
 1705            modal_layer,
 1706            toast_layer,
 1707            titlebar_item: None,
 1708            active_worktree_override: None,
 1709            notifications: Notifications::default(),
 1710            suppressed_notifications: HashSet::default(),
 1711            left_dock,
 1712            bottom_dock,
 1713            right_dock,
 1714            _panels_task: None,
 1715            project: project.clone(),
 1716            follower_states: Default::default(),
 1717            last_leaders_by_pane: Default::default(),
 1718            dispatching_keystrokes: Default::default(),
 1719            window_edited: false,
 1720            last_window_title: None,
 1721            dirty_items: Default::default(),
 1722            active_call,
 1723            database_id: workspace_id,
 1724            app_state,
 1725            _observe_current_user,
 1726            _apply_leader_updates,
 1727            _schedule_serialize_workspace: None,
 1728            _serialize_workspace_task: None,
 1729            _schedule_serialize_ssh_paths: None,
 1730            leader_updates_tx,
 1731            _subscriptions: subscriptions,
 1732            pane_history_timestamp,
 1733            workspace_actions: Default::default(),
 1734            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1735            bounds: Default::default(),
 1736            centered_layout: false,
 1737            bounds_save_task_queued: None,
 1738            on_prompt_for_new_path: None,
 1739            on_prompt_for_open_path: None,
 1740            terminal_provider: None,
 1741            debugger_provider: None,
 1742            serializable_items_tx,
 1743            _items_serializer,
 1744            session_id: Some(session_id),
 1745
 1746            scheduled_tasks: Vec::new(),
 1747            last_open_dock_positions: Vec::new(),
 1748            removing: false,
 1749            sidebar_focus_handle: None,
 1750        }
 1751    }
 1752
 1753    pub fn new_local(
 1754        abs_paths: Vec<PathBuf>,
 1755        app_state: Arc<AppState>,
 1756        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1757        env: Option<HashMap<String, String>>,
 1758        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1759        activate: bool,
 1760        cx: &mut App,
 1761    ) -> Task<anyhow::Result<OpenResult>> {
 1762        let project_handle = Project::local(
 1763            app_state.client.clone(),
 1764            app_state.node_runtime.clone(),
 1765            app_state.user_store.clone(),
 1766            app_state.languages.clone(),
 1767            app_state.fs.clone(),
 1768            env,
 1769            Default::default(),
 1770            cx,
 1771        );
 1772
 1773        let db = WorkspaceDb::global(cx);
 1774        let kvp = db::kvp::KeyValueStore::global(cx);
 1775        cx.spawn(async move |cx| {
 1776            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1777            for path in abs_paths.into_iter() {
 1778                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1779                    paths_to_open.push(canonical)
 1780                } else {
 1781                    paths_to_open.push(path)
 1782                }
 1783            }
 1784
 1785            let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
 1786
 1787            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1788                paths_to_open = paths.ordered_paths().cloned().collect();
 1789                if !paths.is_lexicographically_ordered() {
 1790                    project_handle.update(cx, |project, cx| {
 1791                        project.set_worktrees_reordered(true, cx);
 1792                    });
 1793                }
 1794            }
 1795
 1796            // Get project paths for all of the abs_paths
 1797            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1798                Vec::with_capacity(paths_to_open.len());
 1799
 1800            for path in paths_to_open.into_iter() {
 1801                if let Some((_, project_entry)) = cx
 1802                    .update(|cx| {
 1803                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1804                    })
 1805                    .await
 1806                    .log_err()
 1807                {
 1808                    project_paths.push((path, Some(project_entry)));
 1809                } else {
 1810                    project_paths.push((path, None));
 1811                }
 1812            }
 1813
 1814            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1815                serialized_workspace.id
 1816            } else {
 1817                db.next_id().await.unwrap_or_else(|_| Default::default())
 1818            };
 1819
 1820            let toolchains = db.toolchains(workspace_id).await?;
 1821
 1822            for (toolchain, worktree_path, path) in toolchains {
 1823                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1824                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1825                    this.find_worktree(&worktree_path, cx)
 1826                        .and_then(|(worktree, rel_path)| {
 1827                            if rel_path.is_empty() {
 1828                                Some(worktree.read(cx).id())
 1829                            } else {
 1830                                None
 1831                            }
 1832                        })
 1833                }) else {
 1834                    // We did not find a worktree with a given path, but that's whatever.
 1835                    continue;
 1836                };
 1837                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1838                    continue;
 1839                }
 1840
 1841                project_handle
 1842                    .update(cx, |this, cx| {
 1843                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1844                    })
 1845                    .await;
 1846            }
 1847            if let Some(workspace) = serialized_workspace.as_ref() {
 1848                project_handle.update(cx, |this, cx| {
 1849                    for (scope, toolchains) in &workspace.user_toolchains {
 1850                        for toolchain in toolchains {
 1851                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1852                        }
 1853                    }
 1854                });
 1855            }
 1856
 1857            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1858                if let Some(window) = requesting_window {
 1859                    let centered_layout = serialized_workspace
 1860                        .as_ref()
 1861                        .map(|w| w.centered_layout)
 1862                        .unwrap_or(false);
 1863
 1864                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1865                        let workspace = cx.new(|cx| {
 1866                            let mut workspace = Workspace::new(
 1867                                Some(workspace_id),
 1868                                project_handle.clone(),
 1869                                app_state.clone(),
 1870                                window,
 1871                                cx,
 1872                            );
 1873
 1874                            workspace.centered_layout = centered_layout;
 1875
 1876                            // Call init callback to add items before window renders
 1877                            if let Some(init) = init {
 1878                                init(&mut workspace, window, cx);
 1879                            }
 1880
 1881                            workspace
 1882                        });
 1883                        if activate {
 1884                            multi_workspace.activate(workspace.clone(), cx);
 1885                        } else {
 1886                            multi_workspace.add_workspace(workspace.clone(), cx);
 1887                        }
 1888                        workspace
 1889                    })?;
 1890                    (window, workspace)
 1891                } else {
 1892                    let window_bounds_override = window_bounds_env_override();
 1893
 1894                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1895                        (Some(WindowBounds::Windowed(bounds)), None)
 1896                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1897                        && let Some(display) = workspace.display
 1898                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1899                    {
 1900                        // Reopening an existing workspace - restore its saved bounds
 1901                        (Some(bounds.0), Some(display))
 1902                    } else if let Some((display, bounds)) =
 1903                        persistence::read_default_window_bounds(&kvp)
 1904                    {
 1905                        // New or empty workspace - use the last known window bounds
 1906                        (Some(bounds), Some(display))
 1907                    } else {
 1908                        // New window - let GPUI's default_bounds() handle cascading
 1909                        (None, None)
 1910                    };
 1911
 1912                    // Use the serialized workspace to construct the new window
 1913                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1914                    options.window_bounds = window_bounds;
 1915                    let centered_layout = serialized_workspace
 1916                        .as_ref()
 1917                        .map(|w| w.centered_layout)
 1918                        .unwrap_or(false);
 1919                    let window = cx.open_window(options, {
 1920                        let app_state = app_state.clone();
 1921                        let project_handle = project_handle.clone();
 1922                        move |window, cx| {
 1923                            let workspace = cx.new(|cx| {
 1924                                let mut workspace = Workspace::new(
 1925                                    Some(workspace_id),
 1926                                    project_handle,
 1927                                    app_state,
 1928                                    window,
 1929                                    cx,
 1930                                );
 1931                                workspace.centered_layout = centered_layout;
 1932
 1933                                // Call init callback to add items before window renders
 1934                                if let Some(init) = init {
 1935                                    init(&mut workspace, window, cx);
 1936                                }
 1937
 1938                                workspace
 1939                            });
 1940                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 1941                        }
 1942                    })?;
 1943                    let workspace =
 1944                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 1945                            multi_workspace.workspace().clone()
 1946                        })?;
 1947                    (window, workspace)
 1948                };
 1949
 1950            notify_if_database_failed(window, cx);
 1951            // Check if this is an empty workspace (no paths to open)
 1952            // An empty workspace is one where project_paths is empty
 1953            let is_empty_workspace = project_paths.is_empty();
 1954            // Check if serialized workspace has paths before it's moved
 1955            let serialized_workspace_has_paths = serialized_workspace
 1956                .as_ref()
 1957                .map(|ws| !ws.paths.is_empty())
 1958                .unwrap_or(false);
 1959
 1960            let opened_items = window
 1961                .update(cx, |_, window, cx| {
 1962                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 1963                        open_items(serialized_workspace, project_paths, window, cx)
 1964                    })
 1965                })?
 1966                .await
 1967                .unwrap_or_default();
 1968
 1969            // Restore default dock state for empty workspaces
 1970            // Only restore if:
 1971            // 1. This is an empty workspace (no paths), AND
 1972            // 2. The serialized workspace either doesn't exist or has no paths
 1973            if is_empty_workspace && !serialized_workspace_has_paths {
 1974                if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
 1975                    window
 1976                        .update(cx, |_, window, cx| {
 1977                            workspace.update(cx, |workspace, cx| {
 1978                                for (dock, serialized_dock) in [
 1979                                    (&workspace.right_dock, &default_docks.right),
 1980                                    (&workspace.left_dock, &default_docks.left),
 1981                                    (&workspace.bottom_dock, &default_docks.bottom),
 1982                                ] {
 1983                                    dock.update(cx, |dock, cx| {
 1984                                        dock.serialized_dock = Some(serialized_dock.clone());
 1985                                        dock.restore_state(window, cx);
 1986                                    });
 1987                                }
 1988                                cx.notify();
 1989                            });
 1990                        })
 1991                        .log_err();
 1992                }
 1993            }
 1994
 1995            window
 1996                .update(cx, |_, _window, cx| {
 1997                    workspace.update(cx, |this: &mut Workspace, cx| {
 1998                        this.update_history(cx);
 1999                    });
 2000                })
 2001                .log_err();
 2002            Ok(OpenResult {
 2003                window,
 2004                workspace,
 2005                opened_items,
 2006            })
 2007        })
 2008    }
 2009
 2010    pub fn weak_handle(&self) -> WeakEntity<Self> {
 2011        self.weak_self.clone()
 2012    }
 2013
 2014    pub fn left_dock(&self) -> &Entity<Dock> {
 2015        &self.left_dock
 2016    }
 2017
 2018    pub fn bottom_dock(&self) -> &Entity<Dock> {
 2019        &self.bottom_dock
 2020    }
 2021
 2022    pub fn set_bottom_dock_layout(
 2023        &mut self,
 2024        layout: BottomDockLayout,
 2025        window: &mut Window,
 2026        cx: &mut Context<Self>,
 2027    ) {
 2028        let fs = self.project().read(cx).fs();
 2029        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 2030            content.workspace.bottom_dock_layout = Some(layout);
 2031        });
 2032
 2033        cx.notify();
 2034        self.serialize_workspace(window, cx);
 2035    }
 2036
 2037    pub fn right_dock(&self) -> &Entity<Dock> {
 2038        &self.right_dock
 2039    }
 2040
 2041    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 2042        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 2043    }
 2044
 2045    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 2046        let left_dock = self.left_dock.read(cx);
 2047        let left_visible = left_dock.is_open();
 2048        let left_active_panel = left_dock
 2049            .active_panel()
 2050            .map(|panel| panel.persistent_name().to_string());
 2051        // `zoomed_position` is kept in sync with individual panel zoom state
 2052        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2053        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2054
 2055        let right_dock = self.right_dock.read(cx);
 2056        let right_visible = right_dock.is_open();
 2057        let right_active_panel = right_dock
 2058            .active_panel()
 2059            .map(|panel| panel.persistent_name().to_string());
 2060        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2061
 2062        let bottom_dock = self.bottom_dock.read(cx);
 2063        let bottom_visible = bottom_dock.is_open();
 2064        let bottom_active_panel = bottom_dock
 2065            .active_panel()
 2066            .map(|panel| panel.persistent_name().to_string());
 2067        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2068
 2069        DockStructure {
 2070            left: DockData {
 2071                visible: left_visible,
 2072                active_panel: left_active_panel,
 2073                zoom: left_dock_zoom,
 2074            },
 2075            right: DockData {
 2076                visible: right_visible,
 2077                active_panel: right_active_panel,
 2078                zoom: right_dock_zoom,
 2079            },
 2080            bottom: DockData {
 2081                visible: bottom_visible,
 2082                active_panel: bottom_active_panel,
 2083                zoom: bottom_dock_zoom,
 2084            },
 2085        }
 2086    }
 2087
 2088    pub fn set_dock_structure(
 2089        &self,
 2090        docks: DockStructure,
 2091        window: &mut Window,
 2092        cx: &mut Context<Self>,
 2093    ) {
 2094        for (dock, data) in [
 2095            (&self.left_dock, docks.left),
 2096            (&self.bottom_dock, docks.bottom),
 2097            (&self.right_dock, docks.right),
 2098        ] {
 2099            dock.update(cx, |dock, cx| {
 2100                dock.serialized_dock = Some(data);
 2101                dock.restore_state(window, cx);
 2102            });
 2103        }
 2104    }
 2105
 2106    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2107        self.items(cx)
 2108            .filter_map(|item| {
 2109                let project_path = item.project_path(cx)?;
 2110                self.project.read(cx).absolute_path(&project_path, cx)
 2111            })
 2112            .collect()
 2113    }
 2114
 2115    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2116        match position {
 2117            DockPosition::Left => &self.left_dock,
 2118            DockPosition::Bottom => &self.bottom_dock,
 2119            DockPosition::Right => &self.right_dock,
 2120        }
 2121    }
 2122
 2123    pub fn is_edited(&self) -> bool {
 2124        self.window_edited
 2125    }
 2126
 2127    pub fn add_panel<T: Panel>(
 2128        &mut self,
 2129        panel: Entity<T>,
 2130        window: &mut Window,
 2131        cx: &mut Context<Self>,
 2132    ) {
 2133        let focus_handle = panel.panel_focus_handle(cx);
 2134        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2135            .detach();
 2136
 2137        let dock_position = panel.position(window, cx);
 2138        let dock = self.dock_at_position(dock_position);
 2139        let any_panel = panel.to_any();
 2140
 2141        dock.update(cx, |dock, cx| {
 2142            dock.add_panel(panel, self.weak_self.clone(), window, cx)
 2143        });
 2144
 2145        cx.emit(Event::PanelAdded(any_panel));
 2146    }
 2147
 2148    pub fn remove_panel<T: Panel>(
 2149        &mut self,
 2150        panel: &Entity<T>,
 2151        window: &mut Window,
 2152        cx: &mut Context<Self>,
 2153    ) {
 2154        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2155            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2156        }
 2157    }
 2158
 2159    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2160        &self.status_bar
 2161    }
 2162
 2163    pub fn set_workspace_sidebar_open(
 2164        &self,
 2165        open: bool,
 2166        has_notifications: bool,
 2167        show_toggle: bool,
 2168        cx: &mut App,
 2169    ) {
 2170        self.status_bar.update(cx, |status_bar, cx| {
 2171            status_bar.set_workspace_sidebar_open(open, cx);
 2172            status_bar.set_sidebar_has_notifications(has_notifications, cx);
 2173            status_bar.set_show_sidebar_toggle(show_toggle, cx);
 2174        });
 2175    }
 2176
 2177    pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
 2178        self.sidebar_focus_handle = handle;
 2179    }
 2180
 2181    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2182        StatusBarSettings::get_global(cx).show
 2183    }
 2184
 2185    pub fn app_state(&self) -> &Arc<AppState> {
 2186        &self.app_state
 2187    }
 2188
 2189    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2190        self._panels_task = Some(task);
 2191    }
 2192
 2193    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2194        self._panels_task.take()
 2195    }
 2196
 2197    pub fn user_store(&self) -> &Entity<UserStore> {
 2198        &self.app_state.user_store
 2199    }
 2200
 2201    pub fn project(&self) -> &Entity<Project> {
 2202        &self.project
 2203    }
 2204
 2205    pub fn path_style(&self, cx: &App) -> PathStyle {
 2206        self.project.read(cx).path_style(cx)
 2207    }
 2208
 2209    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2210        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2211
 2212        for pane_handle in &self.panes {
 2213            let pane = pane_handle.read(cx);
 2214
 2215            for entry in pane.activation_history() {
 2216                history.insert(
 2217                    entry.entity_id,
 2218                    history
 2219                        .get(&entry.entity_id)
 2220                        .cloned()
 2221                        .unwrap_or(0)
 2222                        .max(entry.timestamp),
 2223                );
 2224            }
 2225        }
 2226
 2227        history
 2228    }
 2229
 2230    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2231        let mut recent_item: Option<Entity<T>> = None;
 2232        let mut recent_timestamp = 0;
 2233        for pane_handle in &self.panes {
 2234            let pane = pane_handle.read(cx);
 2235            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2236                pane.items().map(|item| (item.item_id(), item)).collect();
 2237            for entry in pane.activation_history() {
 2238                if entry.timestamp > recent_timestamp
 2239                    && let Some(&item) = item_map.get(&entry.entity_id)
 2240                    && let Some(typed_item) = item.act_as::<T>(cx)
 2241                {
 2242                    recent_timestamp = entry.timestamp;
 2243                    recent_item = Some(typed_item);
 2244                }
 2245            }
 2246        }
 2247        recent_item
 2248    }
 2249
 2250    pub fn recent_navigation_history_iter(
 2251        &self,
 2252        cx: &App,
 2253    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2254        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2255        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2256
 2257        for pane in &self.panes {
 2258            let pane = pane.read(cx);
 2259
 2260            pane.nav_history()
 2261                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2262                    if let Some(fs_path) = &fs_path {
 2263                        abs_paths_opened
 2264                            .entry(fs_path.clone())
 2265                            .or_default()
 2266                            .insert(project_path.clone());
 2267                    }
 2268                    let timestamp = entry.timestamp;
 2269                    match history.entry(project_path) {
 2270                        hash_map::Entry::Occupied(mut entry) => {
 2271                            let (_, old_timestamp) = entry.get();
 2272                            if &timestamp > old_timestamp {
 2273                                entry.insert((fs_path, timestamp));
 2274                            }
 2275                        }
 2276                        hash_map::Entry::Vacant(entry) => {
 2277                            entry.insert((fs_path, timestamp));
 2278                        }
 2279                    }
 2280                });
 2281
 2282            if let Some(item) = pane.active_item()
 2283                && let Some(project_path) = item.project_path(cx)
 2284            {
 2285                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2286
 2287                if let Some(fs_path) = &fs_path {
 2288                    abs_paths_opened
 2289                        .entry(fs_path.clone())
 2290                        .or_default()
 2291                        .insert(project_path.clone());
 2292                }
 2293
 2294                history.insert(project_path, (fs_path, std::usize::MAX));
 2295            }
 2296        }
 2297
 2298        history
 2299            .into_iter()
 2300            .sorted_by_key(|(_, (_, order))| *order)
 2301            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2302            .rev()
 2303            .filter(move |(history_path, abs_path)| {
 2304                let latest_project_path_opened = abs_path
 2305                    .as_ref()
 2306                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2307                    .and_then(|project_paths| {
 2308                        project_paths
 2309                            .iter()
 2310                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2311                    });
 2312
 2313                latest_project_path_opened.is_none_or(|path| path == history_path)
 2314            })
 2315    }
 2316
 2317    pub fn recent_navigation_history(
 2318        &self,
 2319        limit: Option<usize>,
 2320        cx: &App,
 2321    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2322        self.recent_navigation_history_iter(cx)
 2323            .take(limit.unwrap_or(usize::MAX))
 2324            .collect()
 2325    }
 2326
 2327    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2328        for pane in &self.panes {
 2329            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2330        }
 2331    }
 2332
 2333    fn navigate_history(
 2334        &mut self,
 2335        pane: WeakEntity<Pane>,
 2336        mode: NavigationMode,
 2337        window: &mut Window,
 2338        cx: &mut Context<Workspace>,
 2339    ) -> Task<Result<()>> {
 2340        self.navigate_history_impl(
 2341            pane,
 2342            mode,
 2343            window,
 2344            &mut |history, cx| history.pop(mode, cx),
 2345            cx,
 2346        )
 2347    }
 2348
 2349    fn navigate_tag_history(
 2350        &mut self,
 2351        pane: WeakEntity<Pane>,
 2352        mode: TagNavigationMode,
 2353        window: &mut Window,
 2354        cx: &mut Context<Workspace>,
 2355    ) -> Task<Result<()>> {
 2356        self.navigate_history_impl(
 2357            pane,
 2358            NavigationMode::Normal,
 2359            window,
 2360            &mut |history, _cx| history.pop_tag(mode),
 2361            cx,
 2362        )
 2363    }
 2364
 2365    fn navigate_history_impl(
 2366        &mut self,
 2367        pane: WeakEntity<Pane>,
 2368        mode: NavigationMode,
 2369        window: &mut Window,
 2370        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2371        cx: &mut Context<Workspace>,
 2372    ) -> Task<Result<()>> {
 2373        let to_load = if let Some(pane) = pane.upgrade() {
 2374            pane.update(cx, |pane, cx| {
 2375                window.focus(&pane.focus_handle(cx), cx);
 2376                loop {
 2377                    // Retrieve the weak item handle from the history.
 2378                    let entry = cb(pane.nav_history_mut(), cx)?;
 2379
 2380                    // If the item is still present in this pane, then activate it.
 2381                    if let Some(index) = entry
 2382                        .item
 2383                        .upgrade()
 2384                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2385                    {
 2386                        let prev_active_item_index = pane.active_item_index();
 2387                        pane.nav_history_mut().set_mode(mode);
 2388                        pane.activate_item(index, true, true, window, cx);
 2389                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2390
 2391                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2392                        if let Some(data) = entry.data {
 2393                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2394                        }
 2395
 2396                        if navigated {
 2397                            break None;
 2398                        }
 2399                    } else {
 2400                        // If the item is no longer present in this pane, then retrieve its
 2401                        // path info in order to reopen it.
 2402                        break pane
 2403                            .nav_history()
 2404                            .path_for_item(entry.item.id())
 2405                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2406                    }
 2407                }
 2408            })
 2409        } else {
 2410            None
 2411        };
 2412
 2413        if let Some((project_path, abs_path, entry)) = to_load {
 2414            // If the item was no longer present, then load it again from its previous path, first try the local path
 2415            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2416
 2417            cx.spawn_in(window, async move  |workspace, cx| {
 2418                let open_by_project_path = open_by_project_path.await;
 2419                let mut navigated = false;
 2420                match open_by_project_path
 2421                    .with_context(|| format!("Navigating to {project_path:?}"))
 2422                {
 2423                    Ok((project_entry_id, build_item)) => {
 2424                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2425                            pane.nav_history_mut().set_mode(mode);
 2426                            pane.active_item().map(|p| p.item_id())
 2427                        })?;
 2428
 2429                        pane.update_in(cx, |pane, window, cx| {
 2430                            let item = pane.open_item(
 2431                                project_entry_id,
 2432                                project_path,
 2433                                true,
 2434                                entry.is_preview,
 2435                                true,
 2436                                None,
 2437                                window, cx,
 2438                                build_item,
 2439                            );
 2440                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2441                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2442                            if let Some(data) = entry.data {
 2443                                navigated |= item.navigate(data, window, cx);
 2444                            }
 2445                        })?;
 2446                    }
 2447                    Err(open_by_project_path_e) => {
 2448                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2449                        // and its worktree is now dropped
 2450                        if let Some(abs_path) = abs_path {
 2451                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2452                                pane.nav_history_mut().set_mode(mode);
 2453                                pane.active_item().map(|p| p.item_id())
 2454                            })?;
 2455                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2456                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2457                            })?;
 2458                            match open_by_abs_path
 2459                                .await
 2460                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2461                            {
 2462                                Ok(item) => {
 2463                                    pane.update_in(cx, |pane, window, cx| {
 2464                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2465                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2466                                        if let Some(data) = entry.data {
 2467                                            navigated |= item.navigate(data, window, cx);
 2468                                        }
 2469                                    })?;
 2470                                }
 2471                                Err(open_by_abs_path_e) => {
 2472                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2473                                }
 2474                            }
 2475                        }
 2476                    }
 2477                }
 2478
 2479                if !navigated {
 2480                    workspace
 2481                        .update_in(cx, |workspace, window, cx| {
 2482                            Self::navigate_history(workspace, pane, mode, window, cx)
 2483                        })?
 2484                        .await?;
 2485                }
 2486
 2487                Ok(())
 2488            })
 2489        } else {
 2490            Task::ready(Ok(()))
 2491        }
 2492    }
 2493
 2494    pub fn go_back(
 2495        &mut self,
 2496        pane: WeakEntity<Pane>,
 2497        window: &mut Window,
 2498        cx: &mut Context<Workspace>,
 2499    ) -> Task<Result<()>> {
 2500        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2501    }
 2502
 2503    pub fn go_forward(
 2504        &mut self,
 2505        pane: WeakEntity<Pane>,
 2506        window: &mut Window,
 2507        cx: &mut Context<Workspace>,
 2508    ) -> Task<Result<()>> {
 2509        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2510    }
 2511
 2512    pub fn reopen_closed_item(
 2513        &mut self,
 2514        window: &mut Window,
 2515        cx: &mut Context<Workspace>,
 2516    ) -> Task<Result<()>> {
 2517        self.navigate_history(
 2518            self.active_pane().downgrade(),
 2519            NavigationMode::ReopeningClosedItem,
 2520            window,
 2521            cx,
 2522        )
 2523    }
 2524
 2525    pub fn client(&self) -> &Arc<Client> {
 2526        &self.app_state.client
 2527    }
 2528
 2529    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2530        self.titlebar_item = Some(item);
 2531        cx.notify();
 2532    }
 2533
 2534    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2535        self.on_prompt_for_new_path = Some(prompt)
 2536    }
 2537
 2538    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2539        self.on_prompt_for_open_path = Some(prompt)
 2540    }
 2541
 2542    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2543        self.terminal_provider = Some(Box::new(provider));
 2544    }
 2545
 2546    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2547        self.debugger_provider = Some(Arc::new(provider));
 2548    }
 2549
 2550    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2551        self.debugger_provider.clone()
 2552    }
 2553
 2554    pub fn prompt_for_open_path(
 2555        &mut self,
 2556        path_prompt_options: PathPromptOptions,
 2557        lister: DirectoryLister,
 2558        window: &mut Window,
 2559        cx: &mut Context<Self>,
 2560    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2561        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2562            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2563            let rx = prompt(self, lister, window, cx);
 2564            self.on_prompt_for_open_path = Some(prompt);
 2565            rx
 2566        } else {
 2567            let (tx, rx) = oneshot::channel();
 2568            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2569
 2570            cx.spawn_in(window, async move |workspace, cx| {
 2571                let Ok(result) = abs_path.await else {
 2572                    return Ok(());
 2573                };
 2574
 2575                match result {
 2576                    Ok(result) => {
 2577                        tx.send(result).ok();
 2578                    }
 2579                    Err(err) => {
 2580                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2581                            workspace.show_portal_error(err.to_string(), cx);
 2582                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2583                            let rx = prompt(workspace, lister, window, cx);
 2584                            workspace.on_prompt_for_open_path = Some(prompt);
 2585                            rx
 2586                        })?;
 2587                        if let Ok(path) = rx.await {
 2588                            tx.send(path).ok();
 2589                        }
 2590                    }
 2591                };
 2592                anyhow::Ok(())
 2593            })
 2594            .detach();
 2595
 2596            rx
 2597        }
 2598    }
 2599
 2600    pub fn prompt_for_new_path(
 2601        &mut self,
 2602        lister: DirectoryLister,
 2603        suggested_name: Option<String>,
 2604        window: &mut Window,
 2605        cx: &mut Context<Self>,
 2606    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2607        if self.project.read(cx).is_via_collab()
 2608            || self.project.read(cx).is_via_remote_server()
 2609            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2610        {
 2611            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2612            let rx = prompt(self, lister, suggested_name, window, cx);
 2613            self.on_prompt_for_new_path = Some(prompt);
 2614            return rx;
 2615        }
 2616
 2617        let (tx, rx) = oneshot::channel();
 2618        cx.spawn_in(window, async move |workspace, cx| {
 2619            let abs_path = workspace.update(cx, |workspace, cx| {
 2620                let relative_to = workspace
 2621                    .most_recent_active_path(cx)
 2622                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2623                    .or_else(|| {
 2624                        let project = workspace.project.read(cx);
 2625                        project.visible_worktrees(cx).find_map(|worktree| {
 2626                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2627                        })
 2628                    })
 2629                    .or_else(std::env::home_dir)
 2630                    .unwrap_or_else(|| PathBuf::from(""));
 2631                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2632            })?;
 2633            let abs_path = match abs_path.await? {
 2634                Ok(path) => path,
 2635                Err(err) => {
 2636                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2637                        workspace.show_portal_error(err.to_string(), cx);
 2638
 2639                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2640                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2641                        workspace.on_prompt_for_new_path = Some(prompt);
 2642                        rx
 2643                    })?;
 2644                    if let Ok(path) = rx.await {
 2645                        tx.send(path).ok();
 2646                    }
 2647                    return anyhow::Ok(());
 2648                }
 2649            };
 2650
 2651            tx.send(abs_path.map(|path| vec![path])).ok();
 2652            anyhow::Ok(())
 2653        })
 2654        .detach();
 2655
 2656        rx
 2657    }
 2658
 2659    pub fn titlebar_item(&self) -> Option<AnyView> {
 2660        self.titlebar_item.clone()
 2661    }
 2662
 2663    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2664    /// When set, git-related operations should use this worktree instead of deriving
 2665    /// the active worktree from the focused file.
 2666    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2667        self.active_worktree_override
 2668    }
 2669
 2670    pub fn set_active_worktree_override(
 2671        &mut self,
 2672        worktree_id: Option<WorktreeId>,
 2673        cx: &mut Context<Self>,
 2674    ) {
 2675        self.active_worktree_override = worktree_id;
 2676        cx.notify();
 2677    }
 2678
 2679    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2680        self.active_worktree_override = None;
 2681        cx.notify();
 2682    }
 2683
 2684    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2685    ///
 2686    /// If the given workspace has a local project, then it will be passed
 2687    /// to the callback. Otherwise, a new empty window will be created.
 2688    pub fn with_local_workspace<T, F>(
 2689        &mut self,
 2690        window: &mut Window,
 2691        cx: &mut Context<Self>,
 2692        callback: F,
 2693    ) -> Task<Result<T>>
 2694    where
 2695        T: 'static,
 2696        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2697    {
 2698        if self.project.read(cx).is_local() {
 2699            Task::ready(Ok(callback(self, window, cx)))
 2700        } else {
 2701            let env = self.project.read(cx).cli_environment(cx);
 2702            let task = Self::new_local(
 2703                Vec::new(),
 2704                self.app_state.clone(),
 2705                None,
 2706                env,
 2707                None,
 2708                true,
 2709                cx,
 2710            );
 2711            cx.spawn_in(window, async move |_vh, cx| {
 2712                let OpenResult {
 2713                    window: multi_workspace_window,
 2714                    ..
 2715                } = task.await?;
 2716                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2717                    let workspace = multi_workspace.workspace().clone();
 2718                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2719                })
 2720            })
 2721        }
 2722    }
 2723
 2724    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2725    ///
 2726    /// If the given workspace has a local project, then it will be passed
 2727    /// to the callback. Otherwise, a new empty window will be created.
 2728    pub fn with_local_or_wsl_workspace<T, F>(
 2729        &mut self,
 2730        window: &mut Window,
 2731        cx: &mut Context<Self>,
 2732        callback: F,
 2733    ) -> Task<Result<T>>
 2734    where
 2735        T: 'static,
 2736        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2737    {
 2738        let project = self.project.read(cx);
 2739        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 2740            Task::ready(Ok(callback(self, window, cx)))
 2741        } else {
 2742            let env = self.project.read(cx).cli_environment(cx);
 2743            let task = Self::new_local(
 2744                Vec::new(),
 2745                self.app_state.clone(),
 2746                None,
 2747                env,
 2748                None,
 2749                true,
 2750                cx,
 2751            );
 2752            cx.spawn_in(window, async move |_vh, cx| {
 2753                let OpenResult {
 2754                    window: multi_workspace_window,
 2755                    ..
 2756                } = task.await?;
 2757                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2758                    let workspace = multi_workspace.workspace().clone();
 2759                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2760                })
 2761            })
 2762        }
 2763    }
 2764
 2765    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2766        self.project.read(cx).worktrees(cx)
 2767    }
 2768
 2769    pub fn visible_worktrees<'a>(
 2770        &self,
 2771        cx: &'a App,
 2772    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2773        self.project.read(cx).visible_worktrees(cx)
 2774    }
 2775
 2776    #[cfg(any(test, feature = "test-support"))]
 2777    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2778        let futures = self
 2779            .worktrees(cx)
 2780            .filter_map(|worktree| worktree.read(cx).as_local())
 2781            .map(|worktree| worktree.scan_complete())
 2782            .collect::<Vec<_>>();
 2783        async move {
 2784            for future in futures {
 2785                future.await;
 2786            }
 2787        }
 2788    }
 2789
 2790    pub fn close_global(cx: &mut App) {
 2791        cx.defer(|cx| {
 2792            cx.windows().iter().find(|window| {
 2793                window
 2794                    .update(cx, |_, window, _| {
 2795                        if window.is_window_active() {
 2796                            //This can only get called when the window's project connection has been lost
 2797                            //so we don't need to prompt the user for anything and instead just close the window
 2798                            window.remove_window();
 2799                            true
 2800                        } else {
 2801                            false
 2802                        }
 2803                    })
 2804                    .unwrap_or(false)
 2805            });
 2806        });
 2807    }
 2808
 2809    pub fn move_focused_panel_to_next_position(
 2810        &mut self,
 2811        _: &MoveFocusedPanelToNextPosition,
 2812        window: &mut Window,
 2813        cx: &mut Context<Self>,
 2814    ) {
 2815        let docks = self.all_docks();
 2816        let active_dock = docks
 2817            .into_iter()
 2818            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 2819
 2820        if let Some(dock) = active_dock {
 2821            dock.update(cx, |dock, cx| {
 2822                let active_panel = dock
 2823                    .active_panel()
 2824                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 2825
 2826                if let Some(panel) = active_panel {
 2827                    panel.move_to_next_position(window, cx);
 2828                }
 2829            })
 2830        }
 2831    }
 2832
 2833    pub fn prepare_to_close(
 2834        &mut self,
 2835        close_intent: CloseIntent,
 2836        window: &mut Window,
 2837        cx: &mut Context<Self>,
 2838    ) -> Task<Result<bool>> {
 2839        let active_call = self.active_global_call();
 2840
 2841        cx.spawn_in(window, async move |this, cx| {
 2842            this.update(cx, |this, _| {
 2843                if close_intent == CloseIntent::CloseWindow {
 2844                    this.removing = true;
 2845                }
 2846            })?;
 2847
 2848            let workspace_count = cx.update(|_window, cx| {
 2849                cx.windows()
 2850                    .iter()
 2851                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 2852                    .count()
 2853            })?;
 2854
 2855            #[cfg(target_os = "macos")]
 2856            let save_last_workspace = false;
 2857
 2858            // On Linux and Windows, closing the last window should restore the last workspace.
 2859            #[cfg(not(target_os = "macos"))]
 2860            let save_last_workspace = {
 2861                let remaining_workspaces = cx.update(|_window, cx| {
 2862                    cx.windows()
 2863                        .iter()
 2864                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 2865                        .filter_map(|multi_workspace| {
 2866                            multi_workspace
 2867                                .update(cx, |multi_workspace, _, cx| {
 2868                                    multi_workspace.workspace().read(cx).removing
 2869                                })
 2870                                .ok()
 2871                        })
 2872                        .filter(|removing| !removing)
 2873                        .count()
 2874                })?;
 2875
 2876                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 2877            };
 2878
 2879            if let Some(active_call) = active_call
 2880                && workspace_count == 1
 2881                && cx
 2882                    .update(|_window, cx| active_call.0.is_in_room(cx))
 2883                    .unwrap_or(false)
 2884            {
 2885                if close_intent == CloseIntent::CloseWindow {
 2886                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 2887                    let answer = cx.update(|window, cx| {
 2888                        window.prompt(
 2889                            PromptLevel::Warning,
 2890                            "Do you want to leave the current call?",
 2891                            None,
 2892                            &["Close window and hang up", "Cancel"],
 2893                            cx,
 2894                        )
 2895                    })?;
 2896
 2897                    if answer.await.log_err() == Some(1) {
 2898                        return anyhow::Ok(false);
 2899                    } else {
 2900                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 2901                            task.await.log_err();
 2902                        }
 2903                    }
 2904                }
 2905                if close_intent == CloseIntent::ReplaceWindow {
 2906                    _ = cx.update(|_window, cx| {
 2907                        let multi_workspace = cx
 2908                            .windows()
 2909                            .iter()
 2910                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 2911                            .next()
 2912                            .unwrap();
 2913                        let project = multi_workspace
 2914                            .read(cx)?
 2915                            .workspace()
 2916                            .read(cx)
 2917                            .project
 2918                            .clone();
 2919                        if project.read(cx).is_shared() {
 2920                            active_call.0.unshare_project(project, cx)?;
 2921                        }
 2922                        Ok::<_, anyhow::Error>(())
 2923                    });
 2924                }
 2925            }
 2926
 2927            let save_result = this
 2928                .update_in(cx, |this, window, cx| {
 2929                    this.save_all_internal(SaveIntent::Close, window, cx)
 2930                })?
 2931                .await;
 2932
 2933            // If we're not quitting, but closing, we remove the workspace from
 2934            // the current session.
 2935            if close_intent != CloseIntent::Quit
 2936                && !save_last_workspace
 2937                && save_result.as_ref().is_ok_and(|&res| res)
 2938            {
 2939                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 2940                    .await;
 2941            }
 2942
 2943            save_result
 2944        })
 2945    }
 2946
 2947    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 2948        self.save_all_internal(
 2949            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 2950            window,
 2951            cx,
 2952        )
 2953        .detach_and_log_err(cx);
 2954    }
 2955
 2956    fn send_keystrokes(
 2957        &mut self,
 2958        action: &SendKeystrokes,
 2959        window: &mut Window,
 2960        cx: &mut Context<Self>,
 2961    ) {
 2962        let keystrokes: Vec<Keystroke> = action
 2963            .0
 2964            .split(' ')
 2965            .flat_map(|k| Keystroke::parse(k).log_err())
 2966            .map(|k| {
 2967                cx.keyboard_mapper()
 2968                    .map_key_equivalent(k, false)
 2969                    .inner()
 2970                    .clone()
 2971            })
 2972            .collect();
 2973        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 2974    }
 2975
 2976    pub fn send_keystrokes_impl(
 2977        &mut self,
 2978        keystrokes: Vec<Keystroke>,
 2979        window: &mut Window,
 2980        cx: &mut Context<Self>,
 2981    ) -> Shared<Task<()>> {
 2982        let mut state = self.dispatching_keystrokes.borrow_mut();
 2983        if !state.dispatched.insert(keystrokes.clone()) {
 2984            cx.propagate();
 2985            return state.task.clone().unwrap();
 2986        }
 2987
 2988        state.queue.extend(keystrokes);
 2989
 2990        let keystrokes = self.dispatching_keystrokes.clone();
 2991        if state.task.is_none() {
 2992            state.task = Some(
 2993                window
 2994                    .spawn(cx, async move |cx| {
 2995                        // limit to 100 keystrokes to avoid infinite recursion.
 2996                        for _ in 0..100 {
 2997                            let keystroke = {
 2998                                let mut state = keystrokes.borrow_mut();
 2999                                let Some(keystroke) = state.queue.pop_front() else {
 3000                                    state.dispatched.clear();
 3001                                    state.task.take();
 3002                                    return;
 3003                                };
 3004                                keystroke
 3005                            };
 3006                            cx.update(|window, cx| {
 3007                                let focused = window.focused(cx);
 3008                                window.dispatch_keystroke(keystroke.clone(), cx);
 3009                                if window.focused(cx) != focused {
 3010                                    // dispatch_keystroke may cause the focus to change.
 3011                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3012                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 3013                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 3014                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3015                                    // )
 3016                                    window.draw(cx).clear();
 3017                                }
 3018                            })
 3019                            .ok();
 3020
 3021                            // Yield between synthetic keystrokes so deferred focus and
 3022                            // other effects can settle before dispatching the next key.
 3023                            yield_now().await;
 3024                        }
 3025
 3026                        *keystrokes.borrow_mut() = Default::default();
 3027                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3028                    })
 3029                    .shared(),
 3030            );
 3031        }
 3032        state.task.clone().unwrap()
 3033    }
 3034
 3035    fn save_all_internal(
 3036        &mut self,
 3037        mut save_intent: SaveIntent,
 3038        window: &mut Window,
 3039        cx: &mut Context<Self>,
 3040    ) -> Task<Result<bool>> {
 3041        if self.project.read(cx).is_disconnected(cx) {
 3042            return Task::ready(Ok(true));
 3043        }
 3044        let dirty_items = self
 3045            .panes
 3046            .iter()
 3047            .flat_map(|pane| {
 3048                pane.read(cx).items().filter_map(|item| {
 3049                    if item.is_dirty(cx) {
 3050                        item.tab_content_text(0, cx);
 3051                        Some((pane.downgrade(), item.boxed_clone()))
 3052                    } else {
 3053                        None
 3054                    }
 3055                })
 3056            })
 3057            .collect::<Vec<_>>();
 3058
 3059        let project = self.project.clone();
 3060        cx.spawn_in(window, async move |workspace, cx| {
 3061            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3062                let (serialize_tasks, remaining_dirty_items) =
 3063                    workspace.update_in(cx, |workspace, window, cx| {
 3064                        let mut remaining_dirty_items = Vec::new();
 3065                        let mut serialize_tasks = Vec::new();
 3066                        for (pane, item) in dirty_items {
 3067                            if let Some(task) = item
 3068                                .to_serializable_item_handle(cx)
 3069                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3070                            {
 3071                                serialize_tasks.push(task);
 3072                            } else {
 3073                                remaining_dirty_items.push((pane, item));
 3074                            }
 3075                        }
 3076                        (serialize_tasks, remaining_dirty_items)
 3077                    })?;
 3078
 3079                futures::future::try_join_all(serialize_tasks).await?;
 3080
 3081                if !remaining_dirty_items.is_empty() {
 3082                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3083                }
 3084
 3085                if remaining_dirty_items.len() > 1 {
 3086                    let answer = workspace.update_in(cx, |_, window, cx| {
 3087                        let detail = Pane::file_names_for_prompt(
 3088                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3089                            cx,
 3090                        );
 3091                        window.prompt(
 3092                            PromptLevel::Warning,
 3093                            "Do you want to save all changes in the following files?",
 3094                            Some(&detail),
 3095                            &["Save all", "Discard all", "Cancel"],
 3096                            cx,
 3097                        )
 3098                    })?;
 3099                    match answer.await.log_err() {
 3100                        Some(0) => save_intent = SaveIntent::SaveAll,
 3101                        Some(1) => save_intent = SaveIntent::Skip,
 3102                        Some(2) => return Ok(false),
 3103                        _ => {}
 3104                    }
 3105                }
 3106
 3107                remaining_dirty_items
 3108            } else {
 3109                dirty_items
 3110            };
 3111
 3112            for (pane, item) in dirty_items {
 3113                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3114                    (
 3115                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3116                        item.project_entry_ids(cx),
 3117                    )
 3118                })?;
 3119                if (singleton || !project_entry_ids.is_empty())
 3120                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3121                {
 3122                    return Ok(false);
 3123                }
 3124            }
 3125            Ok(true)
 3126        })
 3127    }
 3128
 3129    pub fn open_workspace_for_paths(
 3130        &mut self,
 3131        replace_current_window: bool,
 3132        paths: Vec<PathBuf>,
 3133        window: &mut Window,
 3134        cx: &mut Context<Self>,
 3135    ) -> Task<Result<Entity<Workspace>>> {
 3136        let window_handle = window.window_handle().downcast::<MultiWorkspace>();
 3137        let is_remote = self.project.read(cx).is_via_collab();
 3138        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3139        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3140
 3141        let window_to_replace = if replace_current_window {
 3142            window_handle
 3143        } else if is_remote || has_worktree || has_dirty_items {
 3144            None
 3145        } else {
 3146            window_handle
 3147        };
 3148        let app_state = self.app_state.clone();
 3149
 3150        cx.spawn(async move |_, cx| {
 3151            let OpenResult { workspace, .. } = cx
 3152                .update(|cx| {
 3153                    open_paths(
 3154                        &paths,
 3155                        app_state,
 3156                        OpenOptions {
 3157                            replace_window: window_to_replace,
 3158                            ..Default::default()
 3159                        },
 3160                        cx,
 3161                    )
 3162                })
 3163                .await?;
 3164            Ok(workspace)
 3165        })
 3166    }
 3167
 3168    #[allow(clippy::type_complexity)]
 3169    pub fn open_paths(
 3170        &mut self,
 3171        mut abs_paths: Vec<PathBuf>,
 3172        options: OpenOptions,
 3173        pane: Option<WeakEntity<Pane>>,
 3174        window: &mut Window,
 3175        cx: &mut Context<Self>,
 3176    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3177        let fs = self.app_state.fs.clone();
 3178
 3179        let caller_ordered_abs_paths = abs_paths.clone();
 3180
 3181        // Sort the paths to ensure we add worktrees for parents before their children.
 3182        abs_paths.sort_unstable();
 3183        cx.spawn_in(window, async move |this, cx| {
 3184            let mut tasks = Vec::with_capacity(abs_paths.len());
 3185
 3186            for abs_path in &abs_paths {
 3187                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3188                    OpenVisible::All => Some(true),
 3189                    OpenVisible::None => Some(false),
 3190                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3191                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3192                        Some(None) => Some(true),
 3193                        None => None,
 3194                    },
 3195                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3196                        Some(Some(metadata)) => Some(metadata.is_dir),
 3197                        Some(None) => Some(false),
 3198                        None => None,
 3199                    },
 3200                };
 3201                let project_path = match visible {
 3202                    Some(visible) => match this
 3203                        .update(cx, |this, cx| {
 3204                            Workspace::project_path_for_path(
 3205                                this.project.clone(),
 3206                                abs_path,
 3207                                visible,
 3208                                cx,
 3209                            )
 3210                        })
 3211                        .log_err()
 3212                    {
 3213                        Some(project_path) => project_path.await.log_err(),
 3214                        None => None,
 3215                    },
 3216                    None => None,
 3217                };
 3218
 3219                let this = this.clone();
 3220                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3221                let fs = fs.clone();
 3222                let pane = pane.clone();
 3223                let task = cx.spawn(async move |cx| {
 3224                    let (_worktree, project_path) = project_path?;
 3225                    if fs.is_dir(&abs_path).await {
 3226                        // Opening a directory should not race to update the active entry.
 3227                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3228                        None
 3229                    } else {
 3230                        Some(
 3231                            this.update_in(cx, |this, window, cx| {
 3232                                this.open_path(
 3233                                    project_path,
 3234                                    pane,
 3235                                    options.focus.unwrap_or(true),
 3236                                    window,
 3237                                    cx,
 3238                                )
 3239                            })
 3240                            .ok()?
 3241                            .await,
 3242                        )
 3243                    }
 3244                });
 3245                tasks.push(task);
 3246            }
 3247
 3248            let results = futures::future::join_all(tasks).await;
 3249
 3250            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3251            let mut winner: Option<(PathBuf, bool)> = None;
 3252            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3253                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3254                    if !metadata.is_dir {
 3255                        winner = Some((abs_path, false));
 3256                        break;
 3257                    }
 3258                    if winner.is_none() {
 3259                        winner = Some((abs_path, true));
 3260                    }
 3261                } else if winner.is_none() {
 3262                    winner = Some((abs_path, false));
 3263                }
 3264            }
 3265
 3266            // Compute the winner entry id on the foreground thread and emit once, after all
 3267            // paths finish opening. This avoids races between concurrently-opening paths
 3268            // (directories in particular) and makes the resulting project panel selection
 3269            // deterministic.
 3270            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3271                'emit_winner: {
 3272                    let winner_abs_path: Arc<Path> =
 3273                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3274
 3275                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3276                        OpenVisible::All => true,
 3277                        OpenVisible::None => false,
 3278                        OpenVisible::OnlyFiles => !winner_is_dir,
 3279                        OpenVisible::OnlyDirectories => winner_is_dir,
 3280                    };
 3281
 3282                    let Some(worktree_task) = this
 3283                        .update(cx, |workspace, cx| {
 3284                            workspace.project.update(cx, |project, cx| {
 3285                                project.find_or_create_worktree(
 3286                                    winner_abs_path.as_ref(),
 3287                                    visible,
 3288                                    cx,
 3289                                )
 3290                            })
 3291                        })
 3292                        .ok()
 3293                    else {
 3294                        break 'emit_winner;
 3295                    };
 3296
 3297                    let Ok((worktree, _)) = worktree_task.await else {
 3298                        break 'emit_winner;
 3299                    };
 3300
 3301                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3302                        let worktree = worktree.read(cx);
 3303                        let worktree_abs_path = worktree.abs_path();
 3304                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3305                            worktree.root_entry()
 3306                        } else {
 3307                            winner_abs_path
 3308                                .strip_prefix(worktree_abs_path.as_ref())
 3309                                .ok()
 3310                                .and_then(|relative_path| {
 3311                                    let relative_path =
 3312                                        RelPath::new(relative_path, PathStyle::local())
 3313                                            .log_err()?;
 3314                                    worktree.entry_for_path(&relative_path)
 3315                                })
 3316                        }?;
 3317                        Some(entry.id)
 3318                    }) else {
 3319                        break 'emit_winner;
 3320                    };
 3321
 3322                    this.update(cx, |workspace, cx| {
 3323                        workspace.project.update(cx, |_, cx| {
 3324                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3325                        });
 3326                    })
 3327                    .ok();
 3328                }
 3329            }
 3330
 3331            results
 3332        })
 3333    }
 3334
 3335    pub fn open_resolved_path(
 3336        &mut self,
 3337        path: ResolvedPath,
 3338        window: &mut Window,
 3339        cx: &mut Context<Self>,
 3340    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3341        match path {
 3342            ResolvedPath::ProjectPath { project_path, .. } => {
 3343                self.open_path(project_path, None, true, window, cx)
 3344            }
 3345            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3346                PathBuf::from(path),
 3347                OpenOptions {
 3348                    visible: Some(OpenVisible::None),
 3349                    ..Default::default()
 3350                },
 3351                window,
 3352                cx,
 3353            ),
 3354        }
 3355    }
 3356
 3357    pub fn absolute_path_of_worktree(
 3358        &self,
 3359        worktree_id: WorktreeId,
 3360        cx: &mut Context<Self>,
 3361    ) -> Option<PathBuf> {
 3362        self.project
 3363            .read(cx)
 3364            .worktree_for_id(worktree_id, cx)
 3365            // TODO: use `abs_path` or `root_dir`
 3366            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3367    }
 3368
 3369    fn add_folder_to_project(
 3370        &mut self,
 3371        _: &AddFolderToProject,
 3372        window: &mut Window,
 3373        cx: &mut Context<Self>,
 3374    ) {
 3375        let project = self.project.read(cx);
 3376        if project.is_via_collab() {
 3377            self.show_error(
 3378                &anyhow!("You cannot add folders to someone else's project"),
 3379                cx,
 3380            );
 3381            return;
 3382        }
 3383        let paths = self.prompt_for_open_path(
 3384            PathPromptOptions {
 3385                files: false,
 3386                directories: true,
 3387                multiple: true,
 3388                prompt: None,
 3389            },
 3390            DirectoryLister::Project(self.project.clone()),
 3391            window,
 3392            cx,
 3393        );
 3394        cx.spawn_in(window, async move |this, cx| {
 3395            if let Some(paths) = paths.await.log_err().flatten() {
 3396                let results = this
 3397                    .update_in(cx, |this, window, cx| {
 3398                        this.open_paths(
 3399                            paths,
 3400                            OpenOptions {
 3401                                visible: Some(OpenVisible::All),
 3402                                ..Default::default()
 3403                            },
 3404                            None,
 3405                            window,
 3406                            cx,
 3407                        )
 3408                    })?
 3409                    .await;
 3410                for result in results.into_iter().flatten() {
 3411                    result.log_err();
 3412                }
 3413            }
 3414            anyhow::Ok(())
 3415        })
 3416        .detach_and_log_err(cx);
 3417    }
 3418
 3419    pub fn project_path_for_path(
 3420        project: Entity<Project>,
 3421        abs_path: &Path,
 3422        visible: bool,
 3423        cx: &mut App,
 3424    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3425        let entry = project.update(cx, |project, cx| {
 3426            project.find_or_create_worktree(abs_path, visible, cx)
 3427        });
 3428        cx.spawn(async move |cx| {
 3429            let (worktree, path) = entry.await?;
 3430            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3431            Ok((worktree, ProjectPath { worktree_id, path }))
 3432        })
 3433    }
 3434
 3435    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3436        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3437    }
 3438
 3439    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3440        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3441    }
 3442
 3443    pub fn items_of_type<'a, T: Item>(
 3444        &'a self,
 3445        cx: &'a App,
 3446    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3447        self.panes
 3448            .iter()
 3449            .flat_map(|pane| pane.read(cx).items_of_type())
 3450    }
 3451
 3452    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3453        self.active_pane().read(cx).active_item()
 3454    }
 3455
 3456    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3457        let item = self.active_item(cx)?;
 3458        item.to_any_view().downcast::<I>().ok()
 3459    }
 3460
 3461    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3462        self.active_item(cx).and_then(|item| item.project_path(cx))
 3463    }
 3464
 3465    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3466        self.recent_navigation_history_iter(cx)
 3467            .filter_map(|(path, abs_path)| {
 3468                let worktree = self
 3469                    .project
 3470                    .read(cx)
 3471                    .worktree_for_id(path.worktree_id, cx)?;
 3472                if worktree.read(cx).is_visible() {
 3473                    abs_path
 3474                } else {
 3475                    None
 3476                }
 3477            })
 3478            .next()
 3479    }
 3480
 3481    pub fn save_active_item(
 3482        &mut self,
 3483        save_intent: SaveIntent,
 3484        window: &mut Window,
 3485        cx: &mut App,
 3486    ) -> Task<Result<()>> {
 3487        let project = self.project.clone();
 3488        let pane = self.active_pane();
 3489        let item = pane.read(cx).active_item();
 3490        let pane = pane.downgrade();
 3491
 3492        window.spawn(cx, async move |cx| {
 3493            if let Some(item) = item {
 3494                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3495                    .await
 3496                    .map(|_| ())
 3497            } else {
 3498                Ok(())
 3499            }
 3500        })
 3501    }
 3502
 3503    pub fn close_inactive_items_and_panes(
 3504        &mut self,
 3505        action: &CloseInactiveTabsAndPanes,
 3506        window: &mut Window,
 3507        cx: &mut Context<Self>,
 3508    ) {
 3509        if let Some(task) = self.close_all_internal(
 3510            true,
 3511            action.save_intent.unwrap_or(SaveIntent::Close),
 3512            window,
 3513            cx,
 3514        ) {
 3515            task.detach_and_log_err(cx)
 3516        }
 3517    }
 3518
 3519    pub fn close_all_items_and_panes(
 3520        &mut self,
 3521        action: &CloseAllItemsAndPanes,
 3522        window: &mut Window,
 3523        cx: &mut Context<Self>,
 3524    ) {
 3525        if let Some(task) = self.close_all_internal(
 3526            false,
 3527            action.save_intent.unwrap_or(SaveIntent::Close),
 3528            window,
 3529            cx,
 3530        ) {
 3531            task.detach_and_log_err(cx)
 3532        }
 3533    }
 3534
 3535    /// Closes the active item across all panes.
 3536    pub fn close_item_in_all_panes(
 3537        &mut self,
 3538        action: &CloseItemInAllPanes,
 3539        window: &mut Window,
 3540        cx: &mut Context<Self>,
 3541    ) {
 3542        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3543            return;
 3544        };
 3545
 3546        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3547        let close_pinned = action.close_pinned;
 3548
 3549        if let Some(project_path) = active_item.project_path(cx) {
 3550            self.close_items_with_project_path(
 3551                &project_path,
 3552                save_intent,
 3553                close_pinned,
 3554                window,
 3555                cx,
 3556            );
 3557        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3558            let item_id = active_item.item_id();
 3559            self.active_pane().update(cx, |pane, cx| {
 3560                pane.close_item_by_id(item_id, save_intent, window, cx)
 3561                    .detach_and_log_err(cx);
 3562            });
 3563        }
 3564    }
 3565
 3566    /// Closes all items with the given project path across all panes.
 3567    pub fn close_items_with_project_path(
 3568        &mut self,
 3569        project_path: &ProjectPath,
 3570        save_intent: SaveIntent,
 3571        close_pinned: bool,
 3572        window: &mut Window,
 3573        cx: &mut Context<Self>,
 3574    ) {
 3575        let panes = self.panes().to_vec();
 3576        for pane in panes {
 3577            pane.update(cx, |pane, cx| {
 3578                pane.close_items_for_project_path(
 3579                    project_path,
 3580                    save_intent,
 3581                    close_pinned,
 3582                    window,
 3583                    cx,
 3584                )
 3585                .detach_and_log_err(cx);
 3586            });
 3587        }
 3588    }
 3589
 3590    fn close_all_internal(
 3591        &mut self,
 3592        retain_active_pane: bool,
 3593        save_intent: SaveIntent,
 3594        window: &mut Window,
 3595        cx: &mut Context<Self>,
 3596    ) -> Option<Task<Result<()>>> {
 3597        let current_pane = self.active_pane();
 3598
 3599        let mut tasks = Vec::new();
 3600
 3601        if retain_active_pane {
 3602            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3603                pane.close_other_items(
 3604                    &CloseOtherItems {
 3605                        save_intent: None,
 3606                        close_pinned: false,
 3607                    },
 3608                    None,
 3609                    window,
 3610                    cx,
 3611                )
 3612            });
 3613
 3614            tasks.push(current_pane_close);
 3615        }
 3616
 3617        for pane in self.panes() {
 3618            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3619                continue;
 3620            }
 3621
 3622            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3623                pane.close_all_items(
 3624                    &CloseAllItems {
 3625                        save_intent: Some(save_intent),
 3626                        close_pinned: false,
 3627                    },
 3628                    window,
 3629                    cx,
 3630                )
 3631            });
 3632
 3633            tasks.push(close_pane_items)
 3634        }
 3635
 3636        if tasks.is_empty() {
 3637            None
 3638        } else {
 3639            Some(cx.spawn_in(window, async move |_, _| {
 3640                for task in tasks {
 3641                    task.await?
 3642                }
 3643                Ok(())
 3644            }))
 3645        }
 3646    }
 3647
 3648    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3649        self.dock_at_position(position).read(cx).is_open()
 3650    }
 3651
 3652    pub fn toggle_dock(
 3653        &mut self,
 3654        dock_side: DockPosition,
 3655        window: &mut Window,
 3656        cx: &mut Context<Self>,
 3657    ) {
 3658        let mut focus_center = false;
 3659        let mut reveal_dock = false;
 3660
 3661        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3662        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3663
 3664        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3665            telemetry::event!(
 3666                "Panel Button Clicked",
 3667                name = panel.persistent_name(),
 3668                toggle_state = !was_visible
 3669            );
 3670        }
 3671        if was_visible {
 3672            self.save_open_dock_positions(cx);
 3673        }
 3674
 3675        let dock = self.dock_at_position(dock_side);
 3676        dock.update(cx, |dock, cx| {
 3677            dock.set_open(!was_visible, window, cx);
 3678
 3679            if dock.active_panel().is_none() {
 3680                let Some(panel_ix) = dock
 3681                    .first_enabled_panel_idx(cx)
 3682                    .log_with_level(log::Level::Info)
 3683                else {
 3684                    return;
 3685                };
 3686                dock.activate_panel(panel_ix, window, cx);
 3687            }
 3688
 3689            if let Some(active_panel) = dock.active_panel() {
 3690                if was_visible {
 3691                    if active_panel
 3692                        .panel_focus_handle(cx)
 3693                        .contains_focused(window, cx)
 3694                    {
 3695                        focus_center = true;
 3696                    }
 3697                } else {
 3698                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3699                    window.focus(focus_handle, cx);
 3700                    reveal_dock = true;
 3701                }
 3702            }
 3703        });
 3704
 3705        if reveal_dock {
 3706            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3707        }
 3708
 3709        if focus_center {
 3710            self.active_pane
 3711                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3712        }
 3713
 3714        cx.notify();
 3715        self.serialize_workspace(window, cx);
 3716    }
 3717
 3718    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3719        self.all_docks().into_iter().find(|&dock| {
 3720            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3721        })
 3722    }
 3723
 3724    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3725        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3726            self.save_open_dock_positions(cx);
 3727            dock.update(cx, |dock, cx| {
 3728                dock.set_open(false, window, cx);
 3729            });
 3730            return true;
 3731        }
 3732        false
 3733    }
 3734
 3735    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3736        self.save_open_dock_positions(cx);
 3737        for dock in self.all_docks() {
 3738            dock.update(cx, |dock, cx| {
 3739                dock.set_open(false, window, cx);
 3740            });
 3741        }
 3742
 3743        cx.focus_self(window);
 3744        cx.notify();
 3745        self.serialize_workspace(window, cx);
 3746    }
 3747
 3748    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 3749        self.all_docks()
 3750            .into_iter()
 3751            .filter_map(|dock| {
 3752                let dock_ref = dock.read(cx);
 3753                if dock_ref.is_open() {
 3754                    Some(dock_ref.position())
 3755                } else {
 3756                    None
 3757                }
 3758            })
 3759            .collect()
 3760    }
 3761
 3762    /// Saves the positions of currently open docks.
 3763    ///
 3764    /// Updates `last_open_dock_positions` with positions of all currently open
 3765    /// docks, to later be restored by the 'Toggle All Docks' action.
 3766    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 3767        let open_dock_positions = self.get_open_dock_positions(cx);
 3768        if !open_dock_positions.is_empty() {
 3769            self.last_open_dock_positions = open_dock_positions;
 3770        }
 3771    }
 3772
 3773    /// Toggles all docks between open and closed states.
 3774    ///
 3775    /// If any docks are open, closes all and remembers their positions. If all
 3776    /// docks are closed, restores the last remembered dock configuration.
 3777    fn toggle_all_docks(
 3778        &mut self,
 3779        _: &ToggleAllDocks,
 3780        window: &mut Window,
 3781        cx: &mut Context<Self>,
 3782    ) {
 3783        let open_dock_positions = self.get_open_dock_positions(cx);
 3784
 3785        if !open_dock_positions.is_empty() {
 3786            self.close_all_docks(window, cx);
 3787        } else if !self.last_open_dock_positions.is_empty() {
 3788            self.restore_last_open_docks(window, cx);
 3789        }
 3790    }
 3791
 3792    /// Reopens docks from the most recently remembered configuration.
 3793    ///
 3794    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 3795    /// and clears the stored positions.
 3796    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3797        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 3798
 3799        for position in positions_to_open {
 3800            let dock = self.dock_at_position(position);
 3801            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 3802        }
 3803
 3804        cx.focus_self(window);
 3805        cx.notify();
 3806        self.serialize_workspace(window, cx);
 3807    }
 3808
 3809    /// Transfer focus to the panel of the given type.
 3810    pub fn focus_panel<T: Panel>(
 3811        &mut self,
 3812        window: &mut Window,
 3813        cx: &mut Context<Self>,
 3814    ) -> Option<Entity<T>> {
 3815        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 3816        panel.to_any().downcast().ok()
 3817    }
 3818
 3819    /// Focus the panel of the given type if it isn't already focused. If it is
 3820    /// already focused, then transfer focus back to the workspace center.
 3821    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 3822    /// panel when transferring focus back to the center.
 3823    pub fn toggle_panel_focus<T: Panel>(
 3824        &mut self,
 3825        window: &mut Window,
 3826        cx: &mut Context<Self>,
 3827    ) -> bool {
 3828        let mut did_focus_panel = false;
 3829        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 3830            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 3831            did_focus_panel
 3832        });
 3833
 3834        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 3835            self.close_panel::<T>(window, cx);
 3836        }
 3837
 3838        telemetry::event!(
 3839            "Panel Button Clicked",
 3840            name = T::persistent_name(),
 3841            toggle_state = did_focus_panel
 3842        );
 3843
 3844        did_focus_panel
 3845    }
 3846
 3847    pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3848        if let Some(item) = self.active_item(cx) {
 3849            item.item_focus_handle(cx).focus(window, cx);
 3850        } else {
 3851            log::error!("Could not find a focus target when switching focus to the center panes",);
 3852        }
 3853    }
 3854
 3855    pub fn activate_panel_for_proto_id(
 3856        &mut self,
 3857        panel_id: PanelId,
 3858        window: &mut Window,
 3859        cx: &mut Context<Self>,
 3860    ) -> Option<Arc<dyn PanelHandle>> {
 3861        let mut panel = None;
 3862        for dock in self.all_docks() {
 3863            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 3864                panel = dock.update(cx, |dock, cx| {
 3865                    dock.activate_panel(panel_index, window, cx);
 3866                    dock.set_open(true, window, cx);
 3867                    dock.active_panel().cloned()
 3868                });
 3869                break;
 3870            }
 3871        }
 3872
 3873        if panel.is_some() {
 3874            cx.notify();
 3875            self.serialize_workspace(window, cx);
 3876        }
 3877
 3878        panel
 3879    }
 3880
 3881    /// Focus or unfocus the given panel type, depending on the given callback.
 3882    fn focus_or_unfocus_panel<T: Panel>(
 3883        &mut self,
 3884        window: &mut Window,
 3885        cx: &mut Context<Self>,
 3886        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 3887    ) -> Option<Arc<dyn PanelHandle>> {
 3888        let mut result_panel = None;
 3889        let mut serialize = false;
 3890        for dock in self.all_docks() {
 3891            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3892                let mut focus_center = false;
 3893                let panel = dock.update(cx, |dock, cx| {
 3894                    dock.activate_panel(panel_index, window, cx);
 3895
 3896                    let panel = dock.active_panel().cloned();
 3897                    if let Some(panel) = panel.as_ref() {
 3898                        if should_focus(&**panel, window, cx) {
 3899                            dock.set_open(true, window, cx);
 3900                            panel.panel_focus_handle(cx).focus(window, cx);
 3901                        } else {
 3902                            focus_center = true;
 3903                        }
 3904                    }
 3905                    panel
 3906                });
 3907
 3908                if focus_center {
 3909                    self.active_pane
 3910                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3911                }
 3912
 3913                result_panel = panel;
 3914                serialize = true;
 3915                break;
 3916            }
 3917        }
 3918
 3919        if serialize {
 3920            self.serialize_workspace(window, cx);
 3921        }
 3922
 3923        cx.notify();
 3924        result_panel
 3925    }
 3926
 3927    /// Open the panel of the given type
 3928    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3929        for dock in self.all_docks() {
 3930            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3931                dock.update(cx, |dock, cx| {
 3932                    dock.activate_panel(panel_index, window, cx);
 3933                    dock.set_open(true, window, cx);
 3934                });
 3935            }
 3936        }
 3937    }
 3938
 3939    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 3940        for dock in self.all_docks().iter() {
 3941            dock.update(cx, |dock, cx| {
 3942                if dock.panel::<T>().is_some() {
 3943                    dock.set_open(false, window, cx)
 3944                }
 3945            })
 3946        }
 3947    }
 3948
 3949    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 3950        self.all_docks()
 3951            .iter()
 3952            .find_map(|dock| dock.read(cx).panel::<T>())
 3953    }
 3954
 3955    fn dismiss_zoomed_items_to_reveal(
 3956        &mut self,
 3957        dock_to_reveal: Option<DockPosition>,
 3958        window: &mut Window,
 3959        cx: &mut Context<Self>,
 3960    ) {
 3961        // If a center pane is zoomed, unzoom it.
 3962        for pane in &self.panes {
 3963            if pane != &self.active_pane || dock_to_reveal.is_some() {
 3964                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 3965            }
 3966        }
 3967
 3968        // If another dock is zoomed, hide it.
 3969        let mut focus_center = false;
 3970        for dock in self.all_docks() {
 3971            dock.update(cx, |dock, cx| {
 3972                if Some(dock.position()) != dock_to_reveal
 3973                    && let Some(panel) = dock.active_panel()
 3974                    && panel.is_zoomed(window, cx)
 3975                {
 3976                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 3977                    dock.set_open(false, window, cx);
 3978                }
 3979            });
 3980        }
 3981
 3982        if focus_center {
 3983            self.active_pane
 3984                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3985        }
 3986
 3987        if self.zoomed_position != dock_to_reveal {
 3988            self.zoomed = None;
 3989            self.zoomed_position = None;
 3990            cx.emit(Event::ZoomChanged);
 3991        }
 3992
 3993        cx.notify();
 3994    }
 3995
 3996    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 3997        let pane = cx.new(|cx| {
 3998            let mut pane = Pane::new(
 3999                self.weak_handle(),
 4000                self.project.clone(),
 4001                self.pane_history_timestamp.clone(),
 4002                None,
 4003                NewFile.boxed_clone(),
 4004                true,
 4005                window,
 4006                cx,
 4007            );
 4008            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4009            pane
 4010        });
 4011        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4012            .detach();
 4013        self.panes.push(pane.clone());
 4014
 4015        window.focus(&pane.focus_handle(cx), cx);
 4016
 4017        cx.emit(Event::PaneAdded(pane.clone()));
 4018        pane
 4019    }
 4020
 4021    pub fn add_item_to_center(
 4022        &mut self,
 4023        item: Box<dyn ItemHandle>,
 4024        window: &mut Window,
 4025        cx: &mut Context<Self>,
 4026    ) -> bool {
 4027        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4028            if let Some(center_pane) = center_pane.upgrade() {
 4029                center_pane.update(cx, |pane, cx| {
 4030                    pane.add_item(item, true, true, None, window, cx)
 4031                });
 4032                true
 4033            } else {
 4034                false
 4035            }
 4036        } else {
 4037            false
 4038        }
 4039    }
 4040
 4041    pub fn add_item_to_active_pane(
 4042        &mut self,
 4043        item: Box<dyn ItemHandle>,
 4044        destination_index: Option<usize>,
 4045        focus_item: bool,
 4046        window: &mut Window,
 4047        cx: &mut App,
 4048    ) {
 4049        self.add_item(
 4050            self.active_pane.clone(),
 4051            item,
 4052            destination_index,
 4053            false,
 4054            focus_item,
 4055            window,
 4056            cx,
 4057        )
 4058    }
 4059
 4060    pub fn add_item(
 4061        &mut self,
 4062        pane: Entity<Pane>,
 4063        item: Box<dyn ItemHandle>,
 4064        destination_index: Option<usize>,
 4065        activate_pane: bool,
 4066        focus_item: bool,
 4067        window: &mut Window,
 4068        cx: &mut App,
 4069    ) {
 4070        pane.update(cx, |pane, cx| {
 4071            pane.add_item(
 4072                item,
 4073                activate_pane,
 4074                focus_item,
 4075                destination_index,
 4076                window,
 4077                cx,
 4078            )
 4079        });
 4080    }
 4081
 4082    pub fn split_item(
 4083        &mut self,
 4084        split_direction: SplitDirection,
 4085        item: Box<dyn ItemHandle>,
 4086        window: &mut Window,
 4087        cx: &mut Context<Self>,
 4088    ) {
 4089        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4090        self.add_item(new_pane, item, None, true, true, window, cx);
 4091    }
 4092
 4093    pub fn open_abs_path(
 4094        &mut self,
 4095        abs_path: PathBuf,
 4096        options: OpenOptions,
 4097        window: &mut Window,
 4098        cx: &mut Context<Self>,
 4099    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4100        cx.spawn_in(window, async move |workspace, cx| {
 4101            let open_paths_task_result = workspace
 4102                .update_in(cx, |workspace, window, cx| {
 4103                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4104                })
 4105                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4106                .await;
 4107            anyhow::ensure!(
 4108                open_paths_task_result.len() == 1,
 4109                "open abs path {abs_path:?} task returned incorrect number of results"
 4110            );
 4111            match open_paths_task_result
 4112                .into_iter()
 4113                .next()
 4114                .expect("ensured single task result")
 4115            {
 4116                Some(open_result) => {
 4117                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4118                }
 4119                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4120            }
 4121        })
 4122    }
 4123
 4124    pub fn split_abs_path(
 4125        &mut self,
 4126        abs_path: PathBuf,
 4127        visible: bool,
 4128        window: &mut Window,
 4129        cx: &mut Context<Self>,
 4130    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4131        let project_path_task =
 4132            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4133        cx.spawn_in(window, async move |this, cx| {
 4134            let (_, path) = project_path_task.await?;
 4135            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4136                .await
 4137        })
 4138    }
 4139
 4140    pub fn open_path(
 4141        &mut self,
 4142        path: impl Into<ProjectPath>,
 4143        pane: Option<WeakEntity<Pane>>,
 4144        focus_item: bool,
 4145        window: &mut Window,
 4146        cx: &mut App,
 4147    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4148        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4149    }
 4150
 4151    pub fn open_path_preview(
 4152        &mut self,
 4153        path: impl Into<ProjectPath>,
 4154        pane: Option<WeakEntity<Pane>>,
 4155        focus_item: bool,
 4156        allow_preview: bool,
 4157        activate: bool,
 4158        window: &mut Window,
 4159        cx: &mut App,
 4160    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4161        let pane = pane.unwrap_or_else(|| {
 4162            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4163                self.panes
 4164                    .first()
 4165                    .expect("There must be an active pane")
 4166                    .downgrade()
 4167            })
 4168        });
 4169
 4170        let project_path = path.into();
 4171        let task = self.load_path(project_path.clone(), window, cx);
 4172        window.spawn(cx, async move |cx| {
 4173            let (project_entry_id, build_item) = task.await?;
 4174
 4175            pane.update_in(cx, |pane, window, cx| {
 4176                pane.open_item(
 4177                    project_entry_id,
 4178                    project_path,
 4179                    focus_item,
 4180                    allow_preview,
 4181                    activate,
 4182                    None,
 4183                    window,
 4184                    cx,
 4185                    build_item,
 4186                )
 4187            })
 4188        })
 4189    }
 4190
 4191    pub fn split_path(
 4192        &mut self,
 4193        path: impl Into<ProjectPath>,
 4194        window: &mut Window,
 4195        cx: &mut Context<Self>,
 4196    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4197        self.split_path_preview(path, false, None, window, cx)
 4198    }
 4199
 4200    pub fn split_path_preview(
 4201        &mut self,
 4202        path: impl Into<ProjectPath>,
 4203        allow_preview: bool,
 4204        split_direction: Option<SplitDirection>,
 4205        window: &mut Window,
 4206        cx: &mut Context<Self>,
 4207    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4208        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4209            self.panes
 4210                .first()
 4211                .expect("There must be an active pane")
 4212                .downgrade()
 4213        });
 4214
 4215        if let Member::Pane(center_pane) = &self.center.root
 4216            && center_pane.read(cx).items_len() == 0
 4217        {
 4218            return self.open_path(path, Some(pane), true, window, cx);
 4219        }
 4220
 4221        let project_path = path.into();
 4222        let task = self.load_path(project_path.clone(), window, cx);
 4223        cx.spawn_in(window, async move |this, cx| {
 4224            let (project_entry_id, build_item) = task.await?;
 4225            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4226                let pane = pane.upgrade()?;
 4227                let new_pane = this.split_pane(
 4228                    pane,
 4229                    split_direction.unwrap_or(SplitDirection::Right),
 4230                    window,
 4231                    cx,
 4232                );
 4233                new_pane.update(cx, |new_pane, cx| {
 4234                    Some(new_pane.open_item(
 4235                        project_entry_id,
 4236                        project_path,
 4237                        true,
 4238                        allow_preview,
 4239                        true,
 4240                        None,
 4241                        window,
 4242                        cx,
 4243                        build_item,
 4244                    ))
 4245                })
 4246            })
 4247            .map(|option| option.context("pane was dropped"))?
 4248        })
 4249    }
 4250
 4251    fn load_path(
 4252        &mut self,
 4253        path: ProjectPath,
 4254        window: &mut Window,
 4255        cx: &mut App,
 4256    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4257        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4258        registry.open_path(self.project(), &path, window, cx)
 4259    }
 4260
 4261    pub fn find_project_item<T>(
 4262        &self,
 4263        pane: &Entity<Pane>,
 4264        project_item: &Entity<T::Item>,
 4265        cx: &App,
 4266    ) -> Option<Entity<T>>
 4267    where
 4268        T: ProjectItem,
 4269    {
 4270        use project::ProjectItem as _;
 4271        let project_item = project_item.read(cx);
 4272        let entry_id = project_item.entry_id(cx);
 4273        let project_path = project_item.project_path(cx);
 4274
 4275        let mut item = None;
 4276        if let Some(entry_id) = entry_id {
 4277            item = pane.read(cx).item_for_entry(entry_id, cx);
 4278        }
 4279        if item.is_none()
 4280            && let Some(project_path) = project_path
 4281        {
 4282            item = pane.read(cx).item_for_path(project_path, cx);
 4283        }
 4284
 4285        item.and_then(|item| item.downcast::<T>())
 4286    }
 4287
 4288    pub fn is_project_item_open<T>(
 4289        &self,
 4290        pane: &Entity<Pane>,
 4291        project_item: &Entity<T::Item>,
 4292        cx: &App,
 4293    ) -> bool
 4294    where
 4295        T: ProjectItem,
 4296    {
 4297        self.find_project_item::<T>(pane, project_item, cx)
 4298            .is_some()
 4299    }
 4300
 4301    pub fn open_project_item<T>(
 4302        &mut self,
 4303        pane: Entity<Pane>,
 4304        project_item: Entity<T::Item>,
 4305        activate_pane: bool,
 4306        focus_item: bool,
 4307        keep_old_preview: bool,
 4308        allow_new_preview: bool,
 4309        window: &mut Window,
 4310        cx: &mut Context<Self>,
 4311    ) -> Entity<T>
 4312    where
 4313        T: ProjectItem,
 4314    {
 4315        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4316
 4317        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4318            if !keep_old_preview
 4319                && let Some(old_id) = old_item_id
 4320                && old_id != item.item_id()
 4321            {
 4322                // switching to a different item, so unpreview old active item
 4323                pane.update(cx, |pane, _| {
 4324                    pane.unpreview_item_if_preview(old_id);
 4325                });
 4326            }
 4327
 4328            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4329            if !allow_new_preview {
 4330                pane.update(cx, |pane, _| {
 4331                    pane.unpreview_item_if_preview(item.item_id());
 4332                });
 4333            }
 4334            return item;
 4335        }
 4336
 4337        let item = pane.update(cx, |pane, cx| {
 4338            cx.new(|cx| {
 4339                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4340            })
 4341        });
 4342        let mut destination_index = None;
 4343        pane.update(cx, |pane, cx| {
 4344            if !keep_old_preview && let Some(old_id) = old_item_id {
 4345                pane.unpreview_item_if_preview(old_id);
 4346            }
 4347            if allow_new_preview {
 4348                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4349            }
 4350        });
 4351
 4352        self.add_item(
 4353            pane,
 4354            Box::new(item.clone()),
 4355            destination_index,
 4356            activate_pane,
 4357            focus_item,
 4358            window,
 4359            cx,
 4360        );
 4361        item
 4362    }
 4363
 4364    pub fn open_shared_screen(
 4365        &mut self,
 4366        peer_id: PeerId,
 4367        window: &mut Window,
 4368        cx: &mut Context<Self>,
 4369    ) {
 4370        if let Some(shared_screen) =
 4371            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4372        {
 4373            self.active_pane.update(cx, |pane, cx| {
 4374                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4375            });
 4376        }
 4377    }
 4378
 4379    pub fn activate_item(
 4380        &mut self,
 4381        item: &dyn ItemHandle,
 4382        activate_pane: bool,
 4383        focus_item: bool,
 4384        window: &mut Window,
 4385        cx: &mut App,
 4386    ) -> bool {
 4387        let result = self.panes.iter().find_map(|pane| {
 4388            pane.read(cx)
 4389                .index_for_item(item)
 4390                .map(|ix| (pane.clone(), ix))
 4391        });
 4392        if let Some((pane, ix)) = result {
 4393            pane.update(cx, |pane, cx| {
 4394                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4395            });
 4396            true
 4397        } else {
 4398            false
 4399        }
 4400    }
 4401
 4402    fn activate_pane_at_index(
 4403        &mut self,
 4404        action: &ActivatePane,
 4405        window: &mut Window,
 4406        cx: &mut Context<Self>,
 4407    ) {
 4408        let panes = self.center.panes();
 4409        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4410            window.focus(&pane.focus_handle(cx), cx);
 4411        } else {
 4412            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4413                .detach();
 4414        }
 4415    }
 4416
 4417    fn move_item_to_pane_at_index(
 4418        &mut self,
 4419        action: &MoveItemToPane,
 4420        window: &mut Window,
 4421        cx: &mut Context<Self>,
 4422    ) {
 4423        let panes = self.center.panes();
 4424        let destination = match panes.get(action.destination) {
 4425            Some(&destination) => destination.clone(),
 4426            None => {
 4427                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4428                    return;
 4429                }
 4430                let direction = SplitDirection::Right;
 4431                let split_off_pane = self
 4432                    .find_pane_in_direction(direction, cx)
 4433                    .unwrap_or_else(|| self.active_pane.clone());
 4434                let new_pane = self.add_pane(window, cx);
 4435                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4436                new_pane
 4437            }
 4438        };
 4439
 4440        if action.clone {
 4441            if self
 4442                .active_pane
 4443                .read(cx)
 4444                .active_item()
 4445                .is_some_and(|item| item.can_split(cx))
 4446            {
 4447                clone_active_item(
 4448                    self.database_id(),
 4449                    &self.active_pane,
 4450                    &destination,
 4451                    action.focus,
 4452                    window,
 4453                    cx,
 4454                );
 4455                return;
 4456            }
 4457        }
 4458        move_active_item(
 4459            &self.active_pane,
 4460            &destination,
 4461            action.focus,
 4462            true,
 4463            window,
 4464            cx,
 4465        )
 4466    }
 4467
 4468    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4469        let panes = self.center.panes();
 4470        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4471            let next_ix = (ix + 1) % panes.len();
 4472            let next_pane = panes[next_ix].clone();
 4473            window.focus(&next_pane.focus_handle(cx), cx);
 4474        }
 4475    }
 4476
 4477    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4478        let panes = self.center.panes();
 4479        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4480            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4481            let prev_pane = panes[prev_ix].clone();
 4482            window.focus(&prev_pane.focus_handle(cx), cx);
 4483        }
 4484    }
 4485
 4486    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4487        let last_pane = self.center.last_pane();
 4488        window.focus(&last_pane.focus_handle(cx), cx);
 4489    }
 4490
 4491    pub fn activate_pane_in_direction(
 4492        &mut self,
 4493        direction: SplitDirection,
 4494        window: &mut Window,
 4495        cx: &mut App,
 4496    ) {
 4497        use ActivateInDirectionTarget as Target;
 4498        enum Origin {
 4499            Sidebar,
 4500            LeftDock,
 4501            RightDock,
 4502            BottomDock,
 4503            Center,
 4504        }
 4505
 4506        let origin: Origin = if self
 4507            .sidebar_focus_handle
 4508            .as_ref()
 4509            .is_some_and(|h| h.contains_focused(window, cx))
 4510        {
 4511            Origin::Sidebar
 4512        } else {
 4513            [
 4514                (&self.left_dock, Origin::LeftDock),
 4515                (&self.right_dock, Origin::RightDock),
 4516                (&self.bottom_dock, Origin::BottomDock),
 4517            ]
 4518            .into_iter()
 4519            .find_map(|(dock, origin)| {
 4520                if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4521                    Some(origin)
 4522                } else {
 4523                    None
 4524                }
 4525            })
 4526            .unwrap_or(Origin::Center)
 4527        };
 4528
 4529        let get_last_active_pane = || {
 4530            let pane = self
 4531                .last_active_center_pane
 4532                .clone()
 4533                .unwrap_or_else(|| {
 4534                    self.panes
 4535                        .first()
 4536                        .expect("There must be an active pane")
 4537                        .downgrade()
 4538                })
 4539                .upgrade()?;
 4540            (pane.read(cx).items_len() != 0).then_some(pane)
 4541        };
 4542
 4543        let try_dock =
 4544            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4545
 4546        let sidebar_target = self
 4547            .sidebar_focus_handle
 4548            .as_ref()
 4549            .map(|h| Target::Sidebar(h.clone()));
 4550
 4551        let target = match (origin, direction) {
 4552            // From the sidebar, only Right navigates into the workspace.
 4553            (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
 4554                .or_else(|| get_last_active_pane().map(Target::Pane))
 4555                .or_else(|| try_dock(&self.bottom_dock))
 4556                .or_else(|| try_dock(&self.right_dock)),
 4557
 4558            (Origin::Sidebar, _) => None,
 4559
 4560            // We're in the center, so we first try to go to a different pane,
 4561            // otherwise try to go to a dock.
 4562            (Origin::Center, direction) => {
 4563                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4564                    Some(Target::Pane(pane))
 4565                } else {
 4566                    match direction {
 4567                        SplitDirection::Up => None,
 4568                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4569                        SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
 4570                        SplitDirection::Right => try_dock(&self.right_dock),
 4571                    }
 4572                }
 4573            }
 4574
 4575            (Origin::LeftDock, SplitDirection::Right) => {
 4576                if let Some(last_active_pane) = get_last_active_pane() {
 4577                    Some(Target::Pane(last_active_pane))
 4578                } else {
 4579                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4580                }
 4581            }
 4582
 4583            (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
 4584
 4585            (Origin::LeftDock, SplitDirection::Down)
 4586            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4587
 4588            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4589            (Origin::BottomDock, SplitDirection::Left) => {
 4590                try_dock(&self.left_dock).or(sidebar_target)
 4591            }
 4592            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4593
 4594            (Origin::RightDock, SplitDirection::Left) => {
 4595                if let Some(last_active_pane) = get_last_active_pane() {
 4596                    Some(Target::Pane(last_active_pane))
 4597                } else {
 4598                    try_dock(&self.bottom_dock)
 4599                        .or_else(|| try_dock(&self.left_dock))
 4600                        .or(sidebar_target)
 4601                }
 4602            }
 4603
 4604            _ => None,
 4605        };
 4606
 4607        match target {
 4608            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4609                let pane = pane.read(cx);
 4610                if let Some(item) = pane.active_item() {
 4611                    item.item_focus_handle(cx).focus(window, cx);
 4612                } else {
 4613                    log::error!(
 4614                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4615                    );
 4616                }
 4617            }
 4618            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4619                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4620                window.defer(cx, move |window, cx| {
 4621                    let dock = dock.read(cx);
 4622                    if let Some(panel) = dock.active_panel() {
 4623                        panel.panel_focus_handle(cx).focus(window, cx);
 4624                    } else {
 4625                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4626                    }
 4627                })
 4628            }
 4629            Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
 4630                focus_handle.focus(window, cx);
 4631            }
 4632            None => {}
 4633        }
 4634    }
 4635
 4636    pub fn move_item_to_pane_in_direction(
 4637        &mut self,
 4638        action: &MoveItemToPaneInDirection,
 4639        window: &mut Window,
 4640        cx: &mut Context<Self>,
 4641    ) {
 4642        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4643            Some(destination) => destination,
 4644            None => {
 4645                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4646                    return;
 4647                }
 4648                let new_pane = self.add_pane(window, cx);
 4649                self.center
 4650                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4651                new_pane
 4652            }
 4653        };
 4654
 4655        if action.clone {
 4656            if self
 4657                .active_pane
 4658                .read(cx)
 4659                .active_item()
 4660                .is_some_and(|item| item.can_split(cx))
 4661            {
 4662                clone_active_item(
 4663                    self.database_id(),
 4664                    &self.active_pane,
 4665                    &destination,
 4666                    action.focus,
 4667                    window,
 4668                    cx,
 4669                );
 4670                return;
 4671            }
 4672        }
 4673        move_active_item(
 4674            &self.active_pane,
 4675            &destination,
 4676            action.focus,
 4677            true,
 4678            window,
 4679            cx,
 4680        );
 4681    }
 4682
 4683    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4684        self.center.bounding_box_for_pane(pane)
 4685    }
 4686
 4687    pub fn find_pane_in_direction(
 4688        &mut self,
 4689        direction: SplitDirection,
 4690        cx: &App,
 4691    ) -> Option<Entity<Pane>> {
 4692        self.center
 4693            .find_pane_in_direction(&self.active_pane, direction, cx)
 4694            .cloned()
 4695    }
 4696
 4697    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4698        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4699            self.center.swap(&self.active_pane, &to, cx);
 4700            cx.notify();
 4701        }
 4702    }
 4703
 4704    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4705        if self
 4706            .center
 4707            .move_to_border(&self.active_pane, direction, cx)
 4708            .unwrap()
 4709        {
 4710            cx.notify();
 4711        }
 4712    }
 4713
 4714    pub fn resize_pane(
 4715        &mut self,
 4716        axis: gpui::Axis,
 4717        amount: Pixels,
 4718        window: &mut Window,
 4719        cx: &mut Context<Self>,
 4720    ) {
 4721        let docks = self.all_docks();
 4722        let active_dock = docks
 4723            .into_iter()
 4724            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4725
 4726        if let Some(dock) = active_dock {
 4727            let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
 4728                return;
 4729            };
 4730            match dock.read(cx).position() {
 4731                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4732                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4733                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4734            }
 4735        } else {
 4736            self.center
 4737                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 4738        }
 4739        cx.notify();
 4740    }
 4741
 4742    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 4743        self.center.reset_pane_sizes(cx);
 4744        cx.notify();
 4745    }
 4746
 4747    fn handle_pane_focused(
 4748        &mut self,
 4749        pane: Entity<Pane>,
 4750        window: &mut Window,
 4751        cx: &mut Context<Self>,
 4752    ) {
 4753        // This is explicitly hoisted out of the following check for pane identity as
 4754        // terminal panel panes are not registered as a center panes.
 4755        self.status_bar.update(cx, |status_bar, cx| {
 4756            status_bar.set_active_pane(&pane, window, cx);
 4757        });
 4758        if self.active_pane != pane {
 4759            self.set_active_pane(&pane, window, cx);
 4760        }
 4761
 4762        if self.last_active_center_pane.is_none() {
 4763            self.last_active_center_pane = Some(pane.downgrade());
 4764        }
 4765
 4766        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 4767        // This prevents the dock from closing when focus events fire during window activation.
 4768        // We also preserve any dock whose active panel itself has focus — this covers
 4769        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 4770        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 4771            let dock_read = dock.read(cx);
 4772            if let Some(panel) = dock_read.active_panel() {
 4773                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 4774                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 4775                {
 4776                    return Some(dock_read.position());
 4777                }
 4778            }
 4779            None
 4780        });
 4781
 4782        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 4783        if pane.read(cx).is_zoomed() {
 4784            self.zoomed = Some(pane.downgrade().into());
 4785        } else {
 4786            self.zoomed = None;
 4787        }
 4788        self.zoomed_position = None;
 4789        cx.emit(Event::ZoomChanged);
 4790        self.update_active_view_for_followers(window, cx);
 4791        pane.update(cx, |pane, _| {
 4792            pane.track_alternate_file_items();
 4793        });
 4794
 4795        cx.notify();
 4796    }
 4797
 4798    fn set_active_pane(
 4799        &mut self,
 4800        pane: &Entity<Pane>,
 4801        window: &mut Window,
 4802        cx: &mut Context<Self>,
 4803    ) {
 4804        self.active_pane = pane.clone();
 4805        self.active_item_path_changed(true, window, cx);
 4806        self.last_active_center_pane = Some(pane.downgrade());
 4807    }
 4808
 4809    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4810        self.update_active_view_for_followers(window, cx);
 4811    }
 4812
 4813    fn handle_pane_event(
 4814        &mut self,
 4815        pane: &Entity<Pane>,
 4816        event: &pane::Event,
 4817        window: &mut Window,
 4818        cx: &mut Context<Self>,
 4819    ) {
 4820        let mut serialize_workspace = true;
 4821        match event {
 4822            pane::Event::AddItem { item } => {
 4823                item.added_to_pane(self, pane.clone(), window, cx);
 4824                cx.emit(Event::ItemAdded {
 4825                    item: item.boxed_clone(),
 4826                });
 4827            }
 4828            pane::Event::Split { direction, mode } => {
 4829                match mode {
 4830                    SplitMode::ClonePane => {
 4831                        self.split_and_clone(pane.clone(), *direction, window, cx)
 4832                            .detach();
 4833                    }
 4834                    SplitMode::EmptyPane => {
 4835                        self.split_pane(pane.clone(), *direction, window, cx);
 4836                    }
 4837                    SplitMode::MovePane => {
 4838                        self.split_and_move(pane.clone(), *direction, window, cx);
 4839                    }
 4840                };
 4841            }
 4842            pane::Event::JoinIntoNext => {
 4843                self.join_pane_into_next(pane.clone(), window, cx);
 4844            }
 4845            pane::Event::JoinAll => {
 4846                self.join_all_panes(window, cx);
 4847            }
 4848            pane::Event::Remove { focus_on_pane } => {
 4849                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 4850            }
 4851            pane::Event::ActivateItem {
 4852                local,
 4853                focus_changed,
 4854            } => {
 4855                window.invalidate_character_coordinates();
 4856
 4857                pane.update(cx, |pane, _| {
 4858                    pane.track_alternate_file_items();
 4859                });
 4860                if *local {
 4861                    self.unfollow_in_pane(pane, window, cx);
 4862                }
 4863                serialize_workspace = *focus_changed || pane != self.active_pane();
 4864                if pane == self.active_pane() {
 4865                    self.active_item_path_changed(*focus_changed, window, cx);
 4866                    self.update_active_view_for_followers(window, cx);
 4867                } else if *local {
 4868                    self.set_active_pane(pane, window, cx);
 4869                }
 4870            }
 4871            pane::Event::UserSavedItem { item, save_intent } => {
 4872                cx.emit(Event::UserSavedItem {
 4873                    pane: pane.downgrade(),
 4874                    item: item.boxed_clone(),
 4875                    save_intent: *save_intent,
 4876                });
 4877                serialize_workspace = false;
 4878            }
 4879            pane::Event::ChangeItemTitle => {
 4880                if *pane == self.active_pane {
 4881                    self.active_item_path_changed(false, window, cx);
 4882                }
 4883                serialize_workspace = false;
 4884            }
 4885            pane::Event::RemovedItem { item } => {
 4886                cx.emit(Event::ActiveItemChanged);
 4887                self.update_window_edited(window, cx);
 4888                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 4889                    && entry.get().entity_id() == pane.entity_id()
 4890                {
 4891                    entry.remove();
 4892                }
 4893                cx.emit(Event::ItemRemoved {
 4894                    item_id: item.item_id(),
 4895                });
 4896            }
 4897            pane::Event::Focus => {
 4898                window.invalidate_character_coordinates();
 4899                self.handle_pane_focused(pane.clone(), window, cx);
 4900            }
 4901            pane::Event::ZoomIn => {
 4902                if *pane == self.active_pane {
 4903                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 4904                    if pane.read(cx).has_focus(window, cx) {
 4905                        self.zoomed = Some(pane.downgrade().into());
 4906                        self.zoomed_position = None;
 4907                        cx.emit(Event::ZoomChanged);
 4908                    }
 4909                    cx.notify();
 4910                }
 4911            }
 4912            pane::Event::ZoomOut => {
 4913                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4914                if self.zoomed_position.is_none() {
 4915                    self.zoomed = None;
 4916                    cx.emit(Event::ZoomChanged);
 4917                }
 4918                cx.notify();
 4919            }
 4920            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 4921        }
 4922
 4923        if serialize_workspace {
 4924            self.serialize_workspace(window, cx);
 4925        }
 4926    }
 4927
 4928    pub fn unfollow_in_pane(
 4929        &mut self,
 4930        pane: &Entity<Pane>,
 4931        window: &mut Window,
 4932        cx: &mut Context<Workspace>,
 4933    ) -> Option<CollaboratorId> {
 4934        let leader_id = self.leader_for_pane(pane)?;
 4935        self.unfollow(leader_id, window, cx);
 4936        Some(leader_id)
 4937    }
 4938
 4939    pub fn split_pane(
 4940        &mut self,
 4941        pane_to_split: Entity<Pane>,
 4942        split_direction: SplitDirection,
 4943        window: &mut Window,
 4944        cx: &mut Context<Self>,
 4945    ) -> Entity<Pane> {
 4946        let new_pane = self.add_pane(window, cx);
 4947        self.center
 4948            .split(&pane_to_split, &new_pane, split_direction, cx);
 4949        cx.notify();
 4950        new_pane
 4951    }
 4952
 4953    pub fn split_and_move(
 4954        &mut self,
 4955        pane: Entity<Pane>,
 4956        direction: SplitDirection,
 4957        window: &mut Window,
 4958        cx: &mut Context<Self>,
 4959    ) {
 4960        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 4961            return;
 4962        };
 4963        let new_pane = self.add_pane(window, cx);
 4964        new_pane.update(cx, |pane, cx| {
 4965            pane.add_item(item, true, true, None, window, cx)
 4966        });
 4967        self.center.split(&pane, &new_pane, direction, cx);
 4968        cx.notify();
 4969    }
 4970
 4971    pub fn split_and_clone(
 4972        &mut self,
 4973        pane: Entity<Pane>,
 4974        direction: SplitDirection,
 4975        window: &mut Window,
 4976        cx: &mut Context<Self>,
 4977    ) -> Task<Option<Entity<Pane>>> {
 4978        let Some(item) = pane.read(cx).active_item() else {
 4979            return Task::ready(None);
 4980        };
 4981        if !item.can_split(cx) {
 4982            return Task::ready(None);
 4983        }
 4984        let task = item.clone_on_split(self.database_id(), window, cx);
 4985        cx.spawn_in(window, async move |this, cx| {
 4986            if let Some(clone) = task.await {
 4987                this.update_in(cx, |this, window, cx| {
 4988                    let new_pane = this.add_pane(window, cx);
 4989                    let nav_history = pane.read(cx).fork_nav_history();
 4990                    new_pane.update(cx, |pane, cx| {
 4991                        pane.set_nav_history(nav_history, cx);
 4992                        pane.add_item(clone, true, true, None, window, cx)
 4993                    });
 4994                    this.center.split(&pane, &new_pane, direction, cx);
 4995                    cx.notify();
 4996                    new_pane
 4997                })
 4998                .ok()
 4999            } else {
 5000                None
 5001            }
 5002        })
 5003    }
 5004
 5005    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5006        let active_item = self.active_pane.read(cx).active_item();
 5007        for pane in &self.panes {
 5008            join_pane_into_active(&self.active_pane, pane, window, cx);
 5009        }
 5010        if let Some(active_item) = active_item {
 5011            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5012        }
 5013        cx.notify();
 5014    }
 5015
 5016    pub fn join_pane_into_next(
 5017        &mut self,
 5018        pane: Entity<Pane>,
 5019        window: &mut Window,
 5020        cx: &mut Context<Self>,
 5021    ) {
 5022        let next_pane = self
 5023            .find_pane_in_direction(SplitDirection::Right, cx)
 5024            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5025            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5026            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5027        let Some(next_pane) = next_pane else {
 5028            return;
 5029        };
 5030        move_all_items(&pane, &next_pane, window, cx);
 5031        cx.notify();
 5032    }
 5033
 5034    fn remove_pane(
 5035        &mut self,
 5036        pane: Entity<Pane>,
 5037        focus_on: Option<Entity<Pane>>,
 5038        window: &mut Window,
 5039        cx: &mut Context<Self>,
 5040    ) {
 5041        if self.center.remove(&pane, cx).unwrap() {
 5042            self.force_remove_pane(&pane, &focus_on, window, cx);
 5043            self.unfollow_in_pane(&pane, window, cx);
 5044            self.last_leaders_by_pane.remove(&pane.downgrade());
 5045            for removed_item in pane.read(cx).items() {
 5046                self.panes_by_item.remove(&removed_item.item_id());
 5047            }
 5048
 5049            cx.notify();
 5050        } else {
 5051            self.active_item_path_changed(true, window, cx);
 5052        }
 5053        cx.emit(Event::PaneRemoved);
 5054    }
 5055
 5056    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5057        &mut self.panes
 5058    }
 5059
 5060    pub fn panes(&self) -> &[Entity<Pane>] {
 5061        &self.panes
 5062    }
 5063
 5064    pub fn active_pane(&self) -> &Entity<Pane> {
 5065        &self.active_pane
 5066    }
 5067
 5068    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5069        for dock in self.all_docks() {
 5070            if dock.focus_handle(cx).contains_focused(window, cx)
 5071                && let Some(pane) = dock
 5072                    .read(cx)
 5073                    .active_panel()
 5074                    .and_then(|panel| panel.pane(cx))
 5075            {
 5076                return pane;
 5077            }
 5078        }
 5079        self.active_pane().clone()
 5080    }
 5081
 5082    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5083        self.find_pane_in_direction(SplitDirection::Right, cx)
 5084            .unwrap_or_else(|| {
 5085                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5086            })
 5087    }
 5088
 5089    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5090        self.pane_for_item_id(handle.item_id())
 5091    }
 5092
 5093    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5094        let weak_pane = self.panes_by_item.get(&item_id)?;
 5095        weak_pane.upgrade()
 5096    }
 5097
 5098    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5099        self.panes
 5100            .iter()
 5101            .find(|pane| pane.entity_id() == entity_id)
 5102            .cloned()
 5103    }
 5104
 5105    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5106        self.follower_states.retain(|leader_id, state| {
 5107            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5108                for item in state.items_by_leader_view_id.values() {
 5109                    item.view.set_leader_id(None, window, cx);
 5110                }
 5111                false
 5112            } else {
 5113                true
 5114            }
 5115        });
 5116        cx.notify();
 5117    }
 5118
 5119    pub fn start_following(
 5120        &mut self,
 5121        leader_id: impl Into<CollaboratorId>,
 5122        window: &mut Window,
 5123        cx: &mut Context<Self>,
 5124    ) -> Option<Task<Result<()>>> {
 5125        let leader_id = leader_id.into();
 5126        let pane = self.active_pane().clone();
 5127
 5128        self.last_leaders_by_pane
 5129            .insert(pane.downgrade(), leader_id);
 5130        self.unfollow(leader_id, window, cx);
 5131        self.unfollow_in_pane(&pane, window, cx);
 5132        self.follower_states.insert(
 5133            leader_id,
 5134            FollowerState {
 5135                center_pane: pane.clone(),
 5136                dock_pane: None,
 5137                active_view_id: None,
 5138                items_by_leader_view_id: Default::default(),
 5139            },
 5140        );
 5141        cx.notify();
 5142
 5143        match leader_id {
 5144            CollaboratorId::PeerId(leader_peer_id) => {
 5145                let room_id = self.active_call()?.room_id(cx)?;
 5146                let project_id = self.project.read(cx).remote_id();
 5147                let request = self.app_state.client.request(proto::Follow {
 5148                    room_id,
 5149                    project_id,
 5150                    leader_id: Some(leader_peer_id),
 5151                });
 5152
 5153                Some(cx.spawn_in(window, async move |this, cx| {
 5154                    let response = request.await?;
 5155                    this.update(cx, |this, _| {
 5156                        let state = this
 5157                            .follower_states
 5158                            .get_mut(&leader_id)
 5159                            .context("following interrupted")?;
 5160                        state.active_view_id = response
 5161                            .active_view
 5162                            .as_ref()
 5163                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5164                        anyhow::Ok(())
 5165                    })??;
 5166                    if let Some(view) = response.active_view {
 5167                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5168                    }
 5169                    this.update_in(cx, |this, window, cx| {
 5170                        this.leader_updated(leader_id, window, cx)
 5171                    })?;
 5172                    Ok(())
 5173                }))
 5174            }
 5175            CollaboratorId::Agent => {
 5176                self.leader_updated(leader_id, window, cx)?;
 5177                Some(Task::ready(Ok(())))
 5178            }
 5179        }
 5180    }
 5181
 5182    pub fn follow_next_collaborator(
 5183        &mut self,
 5184        _: &FollowNextCollaborator,
 5185        window: &mut Window,
 5186        cx: &mut Context<Self>,
 5187    ) {
 5188        let collaborators = self.project.read(cx).collaborators();
 5189        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5190            let mut collaborators = collaborators.keys().copied();
 5191            for peer_id in collaborators.by_ref() {
 5192                if CollaboratorId::PeerId(peer_id) == leader_id {
 5193                    break;
 5194                }
 5195            }
 5196            collaborators.next().map(CollaboratorId::PeerId)
 5197        } else if let Some(last_leader_id) =
 5198            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5199        {
 5200            match last_leader_id {
 5201                CollaboratorId::PeerId(peer_id) => {
 5202                    if collaborators.contains_key(peer_id) {
 5203                        Some(*last_leader_id)
 5204                    } else {
 5205                        None
 5206                    }
 5207                }
 5208                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5209            }
 5210        } else {
 5211            None
 5212        };
 5213
 5214        let pane = self.active_pane.clone();
 5215        let Some(leader_id) = next_leader_id.or_else(|| {
 5216            Some(CollaboratorId::PeerId(
 5217                collaborators.keys().copied().next()?,
 5218            ))
 5219        }) else {
 5220            return;
 5221        };
 5222        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5223            return;
 5224        }
 5225        if let Some(task) = self.start_following(leader_id, window, cx) {
 5226            task.detach_and_log_err(cx)
 5227        }
 5228    }
 5229
 5230    pub fn follow(
 5231        &mut self,
 5232        leader_id: impl Into<CollaboratorId>,
 5233        window: &mut Window,
 5234        cx: &mut Context<Self>,
 5235    ) {
 5236        let leader_id = leader_id.into();
 5237
 5238        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5239            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5240                return;
 5241            };
 5242            let Some(remote_participant) =
 5243                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5244            else {
 5245                return;
 5246            };
 5247
 5248            let project = self.project.read(cx);
 5249
 5250            let other_project_id = match remote_participant.location {
 5251                ParticipantLocation::External => None,
 5252                ParticipantLocation::UnsharedProject => None,
 5253                ParticipantLocation::SharedProject { project_id } => {
 5254                    if Some(project_id) == project.remote_id() {
 5255                        None
 5256                    } else {
 5257                        Some(project_id)
 5258                    }
 5259                }
 5260            };
 5261
 5262            // if they are active in another project, follow there.
 5263            if let Some(project_id) = other_project_id {
 5264                let app_state = self.app_state.clone();
 5265                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5266                    .detach_and_log_err(cx);
 5267            }
 5268        }
 5269
 5270        // if you're already following, find the right pane and focus it.
 5271        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5272            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5273
 5274            return;
 5275        }
 5276
 5277        // Otherwise, follow.
 5278        if let Some(task) = self.start_following(leader_id, window, cx) {
 5279            task.detach_and_log_err(cx)
 5280        }
 5281    }
 5282
 5283    pub fn unfollow(
 5284        &mut self,
 5285        leader_id: impl Into<CollaboratorId>,
 5286        window: &mut Window,
 5287        cx: &mut Context<Self>,
 5288    ) -> Option<()> {
 5289        cx.notify();
 5290
 5291        let leader_id = leader_id.into();
 5292        let state = self.follower_states.remove(&leader_id)?;
 5293        for (_, item) in state.items_by_leader_view_id {
 5294            item.view.set_leader_id(None, window, cx);
 5295        }
 5296
 5297        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5298            let project_id = self.project.read(cx).remote_id();
 5299            let room_id = self.active_call()?.room_id(cx)?;
 5300            self.app_state
 5301                .client
 5302                .send(proto::Unfollow {
 5303                    room_id,
 5304                    project_id,
 5305                    leader_id: Some(leader_peer_id),
 5306                })
 5307                .log_err();
 5308        }
 5309
 5310        Some(())
 5311    }
 5312
 5313    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5314        self.follower_states.contains_key(&id.into())
 5315    }
 5316
 5317    fn active_item_path_changed(
 5318        &mut self,
 5319        focus_changed: bool,
 5320        window: &mut Window,
 5321        cx: &mut Context<Self>,
 5322    ) {
 5323        cx.emit(Event::ActiveItemChanged);
 5324        let active_entry = self.active_project_path(cx);
 5325        self.project.update(cx, |project, cx| {
 5326            project.set_active_path(active_entry.clone(), cx)
 5327        });
 5328
 5329        if focus_changed && let Some(project_path) = &active_entry {
 5330            let git_store_entity = self.project.read(cx).git_store().clone();
 5331            git_store_entity.update(cx, |git_store, cx| {
 5332                git_store.set_active_repo_for_path(project_path, cx);
 5333            });
 5334        }
 5335
 5336        self.update_window_title(window, cx);
 5337    }
 5338
 5339    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5340        let project = self.project().read(cx);
 5341        let mut title = String::new();
 5342
 5343        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5344            let name = {
 5345                let settings_location = SettingsLocation {
 5346                    worktree_id: worktree.read(cx).id(),
 5347                    path: RelPath::empty(),
 5348                };
 5349
 5350                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5351                match &settings.project_name {
 5352                    Some(name) => name.as_str(),
 5353                    None => worktree.read(cx).root_name_str(),
 5354                }
 5355            };
 5356            if i > 0 {
 5357                title.push_str(", ");
 5358            }
 5359            title.push_str(name);
 5360        }
 5361
 5362        if title.is_empty() {
 5363            title = "empty project".to_string();
 5364        }
 5365
 5366        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5367            let filename = path.path.file_name().or_else(|| {
 5368                Some(
 5369                    project
 5370                        .worktree_for_id(path.worktree_id, cx)?
 5371                        .read(cx)
 5372                        .root_name_str(),
 5373                )
 5374            });
 5375
 5376            if let Some(filename) = filename {
 5377                title.push_str("");
 5378                title.push_str(filename.as_ref());
 5379            }
 5380        }
 5381
 5382        if project.is_via_collab() {
 5383            title.push_str("");
 5384        } else if project.is_shared() {
 5385            title.push_str("");
 5386        }
 5387
 5388        if let Some(last_title) = self.last_window_title.as_ref()
 5389            && &title == last_title
 5390        {
 5391            return;
 5392        }
 5393        window.set_window_title(&title);
 5394        SystemWindowTabController::update_tab_title(
 5395            cx,
 5396            window.window_handle().window_id(),
 5397            SharedString::from(&title),
 5398        );
 5399        self.last_window_title = Some(title);
 5400    }
 5401
 5402    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5403        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5404        if is_edited != self.window_edited {
 5405            self.window_edited = is_edited;
 5406            window.set_window_edited(self.window_edited)
 5407        }
 5408    }
 5409
 5410    fn update_item_dirty_state(
 5411        &mut self,
 5412        item: &dyn ItemHandle,
 5413        window: &mut Window,
 5414        cx: &mut App,
 5415    ) {
 5416        let is_dirty = item.is_dirty(cx);
 5417        let item_id = item.item_id();
 5418        let was_dirty = self.dirty_items.contains_key(&item_id);
 5419        if is_dirty == was_dirty {
 5420            return;
 5421        }
 5422        if was_dirty {
 5423            self.dirty_items.remove(&item_id);
 5424            self.update_window_edited(window, cx);
 5425            return;
 5426        }
 5427
 5428        let workspace = self.weak_handle();
 5429        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5430            return;
 5431        };
 5432        let on_release_callback = Box::new(move |cx: &mut App| {
 5433            window_handle
 5434                .update(cx, |_, window, cx| {
 5435                    workspace
 5436                        .update(cx, |workspace, cx| {
 5437                            workspace.dirty_items.remove(&item_id);
 5438                            workspace.update_window_edited(window, cx)
 5439                        })
 5440                        .ok();
 5441                })
 5442                .ok();
 5443        });
 5444
 5445        let s = item.on_release(cx, on_release_callback);
 5446        self.dirty_items.insert(item_id, s);
 5447        self.update_window_edited(window, cx);
 5448    }
 5449
 5450    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5451        if self.notifications.is_empty() {
 5452            None
 5453        } else {
 5454            Some(
 5455                div()
 5456                    .absolute()
 5457                    .right_3()
 5458                    .bottom_3()
 5459                    .w_112()
 5460                    .h_full()
 5461                    .flex()
 5462                    .flex_col()
 5463                    .justify_end()
 5464                    .gap_2()
 5465                    .children(
 5466                        self.notifications
 5467                            .iter()
 5468                            .map(|(_, notification)| notification.clone().into_any()),
 5469                    ),
 5470            )
 5471        }
 5472    }
 5473
 5474    // RPC handlers
 5475
 5476    fn active_view_for_follower(
 5477        &self,
 5478        follower_project_id: Option<u64>,
 5479        window: &mut Window,
 5480        cx: &mut Context<Self>,
 5481    ) -> Option<proto::View> {
 5482        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5483        let item = item?;
 5484        let leader_id = self
 5485            .pane_for(&*item)
 5486            .and_then(|pane| self.leader_for_pane(&pane));
 5487        let leader_peer_id = match leader_id {
 5488            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5489            Some(CollaboratorId::Agent) | None => None,
 5490        };
 5491
 5492        let item_handle = item.to_followable_item_handle(cx)?;
 5493        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5494        let variant = item_handle.to_state_proto(window, cx)?;
 5495
 5496        if item_handle.is_project_item(window, cx)
 5497            && (follower_project_id.is_none()
 5498                || follower_project_id != self.project.read(cx).remote_id())
 5499        {
 5500            return None;
 5501        }
 5502
 5503        Some(proto::View {
 5504            id: id.to_proto(),
 5505            leader_id: leader_peer_id,
 5506            variant: Some(variant),
 5507            panel_id: panel_id.map(|id| id as i32),
 5508        })
 5509    }
 5510
 5511    fn handle_follow(
 5512        &mut self,
 5513        follower_project_id: Option<u64>,
 5514        window: &mut Window,
 5515        cx: &mut Context<Self>,
 5516    ) -> proto::FollowResponse {
 5517        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5518
 5519        cx.notify();
 5520        proto::FollowResponse {
 5521            views: active_view.iter().cloned().collect(),
 5522            active_view,
 5523        }
 5524    }
 5525
 5526    fn handle_update_followers(
 5527        &mut self,
 5528        leader_id: PeerId,
 5529        message: proto::UpdateFollowers,
 5530        _window: &mut Window,
 5531        _cx: &mut Context<Self>,
 5532    ) {
 5533        self.leader_updates_tx
 5534            .unbounded_send((leader_id, message))
 5535            .ok();
 5536    }
 5537
 5538    async fn process_leader_update(
 5539        this: &WeakEntity<Self>,
 5540        leader_id: PeerId,
 5541        update: proto::UpdateFollowers,
 5542        cx: &mut AsyncWindowContext,
 5543    ) -> Result<()> {
 5544        match update.variant.context("invalid update")? {
 5545            proto::update_followers::Variant::CreateView(view) => {
 5546                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5547                let should_add_view = this.update(cx, |this, _| {
 5548                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5549                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5550                    } else {
 5551                        anyhow::Ok(false)
 5552                    }
 5553                })??;
 5554
 5555                if should_add_view {
 5556                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5557                }
 5558            }
 5559            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5560                let should_add_view = this.update(cx, |this, _| {
 5561                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5562                        state.active_view_id = update_active_view
 5563                            .view
 5564                            .as_ref()
 5565                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5566
 5567                        if state.active_view_id.is_some_and(|view_id| {
 5568                            !state.items_by_leader_view_id.contains_key(&view_id)
 5569                        }) {
 5570                            anyhow::Ok(true)
 5571                        } else {
 5572                            anyhow::Ok(false)
 5573                        }
 5574                    } else {
 5575                        anyhow::Ok(false)
 5576                    }
 5577                })??;
 5578
 5579                if should_add_view && let Some(view) = update_active_view.view {
 5580                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5581                }
 5582            }
 5583            proto::update_followers::Variant::UpdateView(update_view) => {
 5584                let variant = update_view.variant.context("missing update view variant")?;
 5585                let id = update_view.id.context("missing update view id")?;
 5586                let mut tasks = Vec::new();
 5587                this.update_in(cx, |this, window, cx| {
 5588                    let project = this.project.clone();
 5589                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5590                        let view_id = ViewId::from_proto(id.clone())?;
 5591                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5592                            tasks.push(item.view.apply_update_proto(
 5593                                &project,
 5594                                variant.clone(),
 5595                                window,
 5596                                cx,
 5597                            ));
 5598                        }
 5599                    }
 5600                    anyhow::Ok(())
 5601                })??;
 5602                try_join_all(tasks).await.log_err();
 5603            }
 5604        }
 5605        this.update_in(cx, |this, window, cx| {
 5606            this.leader_updated(leader_id, window, cx)
 5607        })?;
 5608        Ok(())
 5609    }
 5610
 5611    async fn add_view_from_leader(
 5612        this: WeakEntity<Self>,
 5613        leader_id: PeerId,
 5614        view: &proto::View,
 5615        cx: &mut AsyncWindowContext,
 5616    ) -> Result<()> {
 5617        let this = this.upgrade().context("workspace dropped")?;
 5618
 5619        let Some(id) = view.id.clone() else {
 5620            anyhow::bail!("no id for view");
 5621        };
 5622        let id = ViewId::from_proto(id)?;
 5623        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5624
 5625        let pane = this.update(cx, |this, _cx| {
 5626            let state = this
 5627                .follower_states
 5628                .get(&leader_id.into())
 5629                .context("stopped following")?;
 5630            anyhow::Ok(state.pane().clone())
 5631        })?;
 5632        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5633            let client = this.read(cx).client().clone();
 5634            pane.items().find_map(|item| {
 5635                let item = item.to_followable_item_handle(cx)?;
 5636                if item.remote_id(&client, window, cx) == Some(id) {
 5637                    Some(item)
 5638                } else {
 5639                    None
 5640                }
 5641            })
 5642        })?;
 5643        let item = if let Some(existing_item) = existing_item {
 5644            existing_item
 5645        } else {
 5646            let variant = view.variant.clone();
 5647            anyhow::ensure!(variant.is_some(), "missing view variant");
 5648
 5649            let task = cx.update(|window, cx| {
 5650                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5651            })?;
 5652
 5653            let Some(task) = task else {
 5654                anyhow::bail!(
 5655                    "failed to construct view from leader (maybe from a different version of zed?)"
 5656                );
 5657            };
 5658
 5659            let mut new_item = task.await?;
 5660            pane.update_in(cx, |pane, window, cx| {
 5661                let mut item_to_remove = None;
 5662                for (ix, item) in pane.items().enumerate() {
 5663                    if let Some(item) = item.to_followable_item_handle(cx) {
 5664                        match new_item.dedup(item.as_ref(), window, cx) {
 5665                            Some(item::Dedup::KeepExisting) => {
 5666                                new_item =
 5667                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5668                                break;
 5669                            }
 5670                            Some(item::Dedup::ReplaceExisting) => {
 5671                                item_to_remove = Some((ix, item.item_id()));
 5672                                break;
 5673                            }
 5674                            None => {}
 5675                        }
 5676                    }
 5677                }
 5678
 5679                if let Some((ix, id)) = item_to_remove {
 5680                    pane.remove_item(id, false, false, window, cx);
 5681                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5682                }
 5683            })?;
 5684
 5685            new_item
 5686        };
 5687
 5688        this.update_in(cx, |this, window, cx| {
 5689            let state = this.follower_states.get_mut(&leader_id.into())?;
 5690            item.set_leader_id(Some(leader_id.into()), window, cx);
 5691            state.items_by_leader_view_id.insert(
 5692                id,
 5693                FollowerView {
 5694                    view: item,
 5695                    location: panel_id,
 5696                },
 5697            );
 5698
 5699            Some(())
 5700        })
 5701        .context("no follower state")?;
 5702
 5703        Ok(())
 5704    }
 5705
 5706    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5707        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5708            return;
 5709        };
 5710
 5711        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5712            let buffer_entity_id = agent_location.buffer.entity_id();
 5713            let view_id = ViewId {
 5714                creator: CollaboratorId::Agent,
 5715                id: buffer_entity_id.as_u64(),
 5716            };
 5717            follower_state.active_view_id = Some(view_id);
 5718
 5719            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5720                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5721                hash_map::Entry::Vacant(entry) => {
 5722                    let existing_view =
 5723                        follower_state
 5724                            .center_pane
 5725                            .read(cx)
 5726                            .items()
 5727                            .find_map(|item| {
 5728                                let item = item.to_followable_item_handle(cx)?;
 5729                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5730                                    && item.project_item_model_ids(cx).as_slice()
 5731                                        == [buffer_entity_id]
 5732                                {
 5733                                    Some(item)
 5734                                } else {
 5735                                    None
 5736                                }
 5737                            });
 5738                    let view = existing_view.or_else(|| {
 5739                        agent_location.buffer.upgrade().and_then(|buffer| {
 5740                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 5741                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 5742                            })?
 5743                            .to_followable_item_handle(cx)
 5744                        })
 5745                    });
 5746
 5747                    view.map(|view| {
 5748                        entry.insert(FollowerView {
 5749                            view,
 5750                            location: None,
 5751                        })
 5752                    })
 5753                }
 5754            };
 5755
 5756            if let Some(item) = item {
 5757                item.view
 5758                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 5759                item.view
 5760                    .update_agent_location(agent_location.position, window, cx);
 5761            }
 5762        } else {
 5763            follower_state.active_view_id = None;
 5764        }
 5765
 5766        self.leader_updated(CollaboratorId::Agent, window, cx);
 5767    }
 5768
 5769    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 5770        let mut is_project_item = true;
 5771        let mut update = proto::UpdateActiveView::default();
 5772        if window.is_window_active() {
 5773            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 5774
 5775            if let Some(item) = active_item
 5776                && item.item_focus_handle(cx).contains_focused(window, cx)
 5777            {
 5778                let leader_id = self
 5779                    .pane_for(&*item)
 5780                    .and_then(|pane| self.leader_for_pane(&pane));
 5781                let leader_peer_id = match leader_id {
 5782                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5783                    Some(CollaboratorId::Agent) | None => None,
 5784                };
 5785
 5786                if let Some(item) = item.to_followable_item_handle(cx) {
 5787                    let id = item
 5788                        .remote_id(&self.app_state.client, window, cx)
 5789                        .map(|id| id.to_proto());
 5790
 5791                    if let Some(id) = id
 5792                        && let Some(variant) = item.to_state_proto(window, cx)
 5793                    {
 5794                        let view = Some(proto::View {
 5795                            id,
 5796                            leader_id: leader_peer_id,
 5797                            variant: Some(variant),
 5798                            panel_id: panel_id.map(|id| id as i32),
 5799                        });
 5800
 5801                        is_project_item = item.is_project_item(window, cx);
 5802                        update = proto::UpdateActiveView { view };
 5803                    };
 5804                }
 5805            }
 5806        }
 5807
 5808        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 5809        if active_view_id != self.last_active_view_id.as_ref() {
 5810            self.last_active_view_id = active_view_id.cloned();
 5811            self.update_followers(
 5812                is_project_item,
 5813                proto::update_followers::Variant::UpdateActiveView(update),
 5814                window,
 5815                cx,
 5816            );
 5817        }
 5818    }
 5819
 5820    fn active_item_for_followers(
 5821        &self,
 5822        window: &mut Window,
 5823        cx: &mut App,
 5824    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 5825        let mut active_item = None;
 5826        let mut panel_id = None;
 5827        for dock in self.all_docks() {
 5828            if dock.focus_handle(cx).contains_focused(window, cx)
 5829                && let Some(panel) = dock.read(cx).active_panel()
 5830                && let Some(pane) = panel.pane(cx)
 5831                && let Some(item) = pane.read(cx).active_item()
 5832            {
 5833                active_item = Some(item);
 5834                panel_id = panel.remote_id();
 5835                break;
 5836            }
 5837        }
 5838
 5839        if active_item.is_none() {
 5840            active_item = self.active_pane().read(cx).active_item();
 5841        }
 5842        (active_item, panel_id)
 5843    }
 5844
 5845    fn update_followers(
 5846        &self,
 5847        project_only: bool,
 5848        update: proto::update_followers::Variant,
 5849        _: &mut Window,
 5850        cx: &mut App,
 5851    ) -> Option<()> {
 5852        // If this update only applies to for followers in the current project,
 5853        // then skip it unless this project is shared. If it applies to all
 5854        // followers, regardless of project, then set `project_id` to none,
 5855        // indicating that it goes to all followers.
 5856        let project_id = if project_only {
 5857            Some(self.project.read(cx).remote_id()?)
 5858        } else {
 5859            None
 5860        };
 5861        self.app_state().workspace_store.update(cx, |store, cx| {
 5862            store.update_followers(project_id, update, cx)
 5863        })
 5864    }
 5865
 5866    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 5867        self.follower_states.iter().find_map(|(leader_id, state)| {
 5868            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 5869                Some(*leader_id)
 5870            } else {
 5871                None
 5872            }
 5873        })
 5874    }
 5875
 5876    fn leader_updated(
 5877        &mut self,
 5878        leader_id: impl Into<CollaboratorId>,
 5879        window: &mut Window,
 5880        cx: &mut Context<Self>,
 5881    ) -> Option<Box<dyn ItemHandle>> {
 5882        cx.notify();
 5883
 5884        let leader_id = leader_id.into();
 5885        let (panel_id, item) = match leader_id {
 5886            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 5887            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 5888        };
 5889
 5890        let state = self.follower_states.get(&leader_id)?;
 5891        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 5892        let pane;
 5893        if let Some(panel_id) = panel_id {
 5894            pane = self
 5895                .activate_panel_for_proto_id(panel_id, window, cx)?
 5896                .pane(cx)?;
 5897            let state = self.follower_states.get_mut(&leader_id)?;
 5898            state.dock_pane = Some(pane.clone());
 5899        } else {
 5900            pane = state.center_pane.clone();
 5901            let state = self.follower_states.get_mut(&leader_id)?;
 5902            if let Some(dock_pane) = state.dock_pane.take() {
 5903                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 5904            }
 5905        }
 5906
 5907        pane.update(cx, |pane, cx| {
 5908            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 5909            if let Some(index) = pane.index_for_item(item.as_ref()) {
 5910                pane.activate_item(index, false, false, window, cx);
 5911            } else {
 5912                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 5913            }
 5914
 5915            if focus_active_item {
 5916                pane.focus_active_item(window, cx)
 5917            }
 5918        });
 5919
 5920        Some(item)
 5921    }
 5922
 5923    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 5924        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 5925        let active_view_id = state.active_view_id?;
 5926        Some(
 5927            state
 5928                .items_by_leader_view_id
 5929                .get(&active_view_id)?
 5930                .view
 5931                .boxed_clone(),
 5932        )
 5933    }
 5934
 5935    fn active_item_for_peer(
 5936        &self,
 5937        peer_id: PeerId,
 5938        window: &mut Window,
 5939        cx: &mut Context<Self>,
 5940    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 5941        let call = self.active_call()?;
 5942        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 5943        let leader_in_this_app;
 5944        let leader_in_this_project;
 5945        match participant.location {
 5946            ParticipantLocation::SharedProject { project_id } => {
 5947                leader_in_this_app = true;
 5948                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 5949            }
 5950            ParticipantLocation::UnsharedProject => {
 5951                leader_in_this_app = true;
 5952                leader_in_this_project = false;
 5953            }
 5954            ParticipantLocation::External => {
 5955                leader_in_this_app = false;
 5956                leader_in_this_project = false;
 5957            }
 5958        };
 5959        let state = self.follower_states.get(&peer_id.into())?;
 5960        let mut item_to_activate = None;
 5961        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 5962            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 5963                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 5964            {
 5965                item_to_activate = Some((item.location, item.view.boxed_clone()));
 5966            }
 5967        } else if let Some(shared_screen) =
 5968            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 5969        {
 5970            item_to_activate = Some((None, Box::new(shared_screen)));
 5971        }
 5972        item_to_activate
 5973    }
 5974
 5975    fn shared_screen_for_peer(
 5976        &self,
 5977        peer_id: PeerId,
 5978        pane: &Entity<Pane>,
 5979        window: &mut Window,
 5980        cx: &mut App,
 5981    ) -> Option<Entity<SharedScreen>> {
 5982        self.active_call()?
 5983            .create_shared_screen(peer_id, pane, window, cx)
 5984    }
 5985
 5986    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5987        if window.is_window_active() {
 5988            self.update_active_view_for_followers(window, cx);
 5989
 5990            if let Some(database_id) = self.database_id {
 5991                let db = WorkspaceDb::global(cx);
 5992                cx.background_spawn(async move { db.update_timestamp(database_id).await })
 5993                    .detach();
 5994            }
 5995        } else {
 5996            for pane in &self.panes {
 5997                pane.update(cx, |pane, cx| {
 5998                    if let Some(item) = pane.active_item() {
 5999                        item.workspace_deactivated(window, cx);
 6000                    }
 6001                    for item in pane.items() {
 6002                        if matches!(
 6003                            item.workspace_settings(cx).autosave,
 6004                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6005                        ) {
 6006                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6007                                .detach_and_log_err(cx);
 6008                        }
 6009                    }
 6010                });
 6011            }
 6012        }
 6013    }
 6014
 6015    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6016        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6017    }
 6018
 6019    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6020        self.active_call.as_ref().map(|(call, _)| call.clone())
 6021    }
 6022
 6023    fn on_active_call_event(
 6024        &mut self,
 6025        event: &ActiveCallEvent,
 6026        window: &mut Window,
 6027        cx: &mut Context<Self>,
 6028    ) {
 6029        match event {
 6030            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6031            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6032                self.leader_updated(participant_id, window, cx);
 6033            }
 6034        }
 6035    }
 6036
 6037    pub fn database_id(&self) -> Option<WorkspaceId> {
 6038        self.database_id
 6039    }
 6040
 6041    #[cfg(any(test, feature = "test-support"))]
 6042    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6043        self.database_id = Some(id);
 6044    }
 6045
 6046    pub fn session_id(&self) -> Option<String> {
 6047        self.session_id.clone()
 6048    }
 6049
 6050    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6051        let Some(display) = window.display(cx) else {
 6052            return Task::ready(());
 6053        };
 6054        let Ok(display_uuid) = display.uuid() else {
 6055            return Task::ready(());
 6056        };
 6057
 6058        let window_bounds = window.inner_window_bounds();
 6059        let database_id = self.database_id;
 6060        let has_paths = !self.root_paths(cx).is_empty();
 6061        let db = WorkspaceDb::global(cx);
 6062        let kvp = db::kvp::KeyValueStore::global(cx);
 6063
 6064        cx.background_executor().spawn(async move {
 6065            if !has_paths {
 6066                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6067                    .await
 6068                    .log_err();
 6069            }
 6070            if let Some(database_id) = database_id {
 6071                db.set_window_open_status(
 6072                    database_id,
 6073                    SerializedWindowBounds(window_bounds),
 6074                    display_uuid,
 6075                )
 6076                .await
 6077                .log_err();
 6078            } else {
 6079                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6080                    .await
 6081                    .log_err();
 6082            }
 6083        })
 6084    }
 6085
 6086    /// Bypass the 200ms serialization throttle and write workspace state to
 6087    /// the DB immediately. Returns a task the caller can await to ensure the
 6088    /// write completes. Used by the quit handler so the most recent state
 6089    /// isn't lost to a pending throttle timer when the process exits.
 6090    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6091        self._schedule_serialize_workspace.take();
 6092        self._serialize_workspace_task.take();
 6093        self.bounds_save_task_queued.take();
 6094
 6095        let bounds_task = self.save_window_bounds(window, cx);
 6096        let serialize_task = self.serialize_workspace_internal(window, cx);
 6097        cx.spawn(async move |_| {
 6098            bounds_task.await;
 6099            serialize_task.await;
 6100        })
 6101    }
 6102
 6103    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6104        let project = self.project().read(cx);
 6105        project
 6106            .visible_worktrees(cx)
 6107            .map(|worktree| worktree.read(cx).abs_path())
 6108            .collect::<Vec<_>>()
 6109    }
 6110
 6111    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6112        match member {
 6113            Member::Axis(PaneAxis { members, .. }) => {
 6114                for child in members.iter() {
 6115                    self.remove_panes(child.clone(), window, cx)
 6116                }
 6117            }
 6118            Member::Pane(pane) => {
 6119                self.force_remove_pane(&pane, &None, window, cx);
 6120            }
 6121        }
 6122    }
 6123
 6124    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6125        self.session_id.take();
 6126        self.serialize_workspace_internal(window, cx)
 6127    }
 6128
 6129    fn force_remove_pane(
 6130        &mut self,
 6131        pane: &Entity<Pane>,
 6132        focus_on: &Option<Entity<Pane>>,
 6133        window: &mut Window,
 6134        cx: &mut Context<Workspace>,
 6135    ) {
 6136        self.panes.retain(|p| p != pane);
 6137        if let Some(focus_on) = focus_on {
 6138            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6139        } else if self.active_pane() == pane {
 6140            self.panes
 6141                .last()
 6142                .unwrap()
 6143                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6144        }
 6145        if self.last_active_center_pane == Some(pane.downgrade()) {
 6146            self.last_active_center_pane = None;
 6147        }
 6148        cx.notify();
 6149    }
 6150
 6151    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6152        if self._schedule_serialize_workspace.is_none() {
 6153            self._schedule_serialize_workspace =
 6154                Some(cx.spawn_in(window, async move |this, cx| {
 6155                    cx.background_executor()
 6156                        .timer(SERIALIZATION_THROTTLE_TIME)
 6157                        .await;
 6158                    this.update_in(cx, |this, window, cx| {
 6159                        this._serialize_workspace_task =
 6160                            Some(this.serialize_workspace_internal(window, cx));
 6161                        this._schedule_serialize_workspace.take();
 6162                    })
 6163                    .log_err();
 6164                }));
 6165        }
 6166    }
 6167
 6168    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6169        let Some(database_id) = self.database_id() else {
 6170            return Task::ready(());
 6171        };
 6172
 6173        fn serialize_pane_handle(
 6174            pane_handle: &Entity<Pane>,
 6175            window: &mut Window,
 6176            cx: &mut App,
 6177        ) -> SerializedPane {
 6178            let (items, active, pinned_count) = {
 6179                let pane = pane_handle.read(cx);
 6180                let active_item_id = pane.active_item().map(|item| item.item_id());
 6181                (
 6182                    pane.items()
 6183                        .filter_map(|handle| {
 6184                            let handle = handle.to_serializable_item_handle(cx)?;
 6185
 6186                            Some(SerializedItem {
 6187                                kind: Arc::from(handle.serialized_item_kind()),
 6188                                item_id: handle.item_id().as_u64(),
 6189                                active: Some(handle.item_id()) == active_item_id,
 6190                                preview: pane.is_active_preview_item(handle.item_id()),
 6191                            })
 6192                        })
 6193                        .collect::<Vec<_>>(),
 6194                    pane.has_focus(window, cx),
 6195                    pane.pinned_count(),
 6196                )
 6197            };
 6198
 6199            SerializedPane::new(items, active, pinned_count)
 6200        }
 6201
 6202        fn build_serialized_pane_group(
 6203            pane_group: &Member,
 6204            window: &mut Window,
 6205            cx: &mut App,
 6206        ) -> SerializedPaneGroup {
 6207            match pane_group {
 6208                Member::Axis(PaneAxis {
 6209                    axis,
 6210                    members,
 6211                    flexes,
 6212                    bounding_boxes: _,
 6213                }) => SerializedPaneGroup::Group {
 6214                    axis: SerializedAxis(*axis),
 6215                    children: members
 6216                        .iter()
 6217                        .map(|member| build_serialized_pane_group(member, window, cx))
 6218                        .collect::<Vec<_>>(),
 6219                    flexes: Some(flexes.lock().clone()),
 6220                },
 6221                Member::Pane(pane_handle) => {
 6222                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6223                }
 6224            }
 6225        }
 6226
 6227        fn build_serialized_docks(
 6228            this: &Workspace,
 6229            window: &mut Window,
 6230            cx: &mut App,
 6231        ) -> DockStructure {
 6232            this.capture_dock_state(window, cx)
 6233        }
 6234
 6235        match self.workspace_location(cx) {
 6236            WorkspaceLocation::Location(location, paths) => {
 6237                let breakpoints = self.project.update(cx, |project, cx| {
 6238                    project
 6239                        .breakpoint_store()
 6240                        .read(cx)
 6241                        .all_source_breakpoints(cx)
 6242                });
 6243                let user_toolchains = self
 6244                    .project
 6245                    .read(cx)
 6246                    .user_toolchains(cx)
 6247                    .unwrap_or_default();
 6248
 6249                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6250                let docks = build_serialized_docks(self, window, cx);
 6251                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6252
 6253                let serialized_workspace = SerializedWorkspace {
 6254                    id: database_id,
 6255                    location,
 6256                    paths,
 6257                    center_group,
 6258                    window_bounds,
 6259                    display: Default::default(),
 6260                    docks,
 6261                    centered_layout: self.centered_layout,
 6262                    session_id: self.session_id.clone(),
 6263                    breakpoints,
 6264                    window_id: Some(window.window_handle().window_id().as_u64()),
 6265                    user_toolchains,
 6266                };
 6267
 6268                let db = WorkspaceDb::global(cx);
 6269                window.spawn(cx, async move |_| {
 6270                    db.save_workspace(serialized_workspace).await;
 6271                })
 6272            }
 6273            WorkspaceLocation::DetachFromSession => {
 6274                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6275                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6276                // Save dock state for empty local workspaces
 6277                let docks = build_serialized_docks(self, window, cx);
 6278                let db = WorkspaceDb::global(cx);
 6279                let kvp = db::kvp::KeyValueStore::global(cx);
 6280                window.spawn(cx, async move |_| {
 6281                    db.set_window_open_status(
 6282                        database_id,
 6283                        window_bounds,
 6284                        display.unwrap_or_default(),
 6285                    )
 6286                    .await
 6287                    .log_err();
 6288                    db.set_session_id(database_id, None).await.log_err();
 6289                    persistence::write_default_dock_state(&kvp, docks)
 6290                        .await
 6291                        .log_err();
 6292                })
 6293            }
 6294            WorkspaceLocation::None => {
 6295                // Save dock state for empty non-local workspaces
 6296                let docks = build_serialized_docks(self, window, cx);
 6297                let kvp = db::kvp::KeyValueStore::global(cx);
 6298                window.spawn(cx, async move |_| {
 6299                    persistence::write_default_dock_state(&kvp, docks)
 6300                        .await
 6301                        .log_err();
 6302                })
 6303            }
 6304        }
 6305    }
 6306
 6307    fn has_any_items_open(&self, cx: &App) -> bool {
 6308        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6309    }
 6310
 6311    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6312        let paths = PathList::new(&self.root_paths(cx));
 6313        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6314            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6315        } else if self.project.read(cx).is_local() {
 6316            if !paths.is_empty() || self.has_any_items_open(cx) {
 6317                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6318            } else {
 6319                WorkspaceLocation::DetachFromSession
 6320            }
 6321        } else {
 6322            WorkspaceLocation::None
 6323        }
 6324    }
 6325
 6326    fn update_history(&self, cx: &mut App) {
 6327        let Some(id) = self.database_id() else {
 6328            return;
 6329        };
 6330        if !self.project.read(cx).is_local() {
 6331            return;
 6332        }
 6333        if let Some(manager) = HistoryManager::global(cx) {
 6334            let paths = PathList::new(&self.root_paths(cx));
 6335            manager.update(cx, |this, cx| {
 6336                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6337            });
 6338        }
 6339    }
 6340
 6341    async fn serialize_items(
 6342        this: &WeakEntity<Self>,
 6343        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6344        cx: &mut AsyncWindowContext,
 6345    ) -> Result<()> {
 6346        const CHUNK_SIZE: usize = 200;
 6347
 6348        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6349
 6350        while let Some(items_received) = serializable_items.next().await {
 6351            let unique_items =
 6352                items_received
 6353                    .into_iter()
 6354                    .fold(HashMap::default(), |mut acc, item| {
 6355                        acc.entry(item.item_id()).or_insert(item);
 6356                        acc
 6357                    });
 6358
 6359            // We use into_iter() here so that the references to the items are moved into
 6360            // the tasks and not kept alive while we're sleeping.
 6361            for (_, item) in unique_items.into_iter() {
 6362                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6363                    item.serialize(workspace, false, window, cx)
 6364                }) {
 6365                    cx.background_spawn(async move { task.await.log_err() })
 6366                        .detach();
 6367                }
 6368            }
 6369
 6370            cx.background_executor()
 6371                .timer(SERIALIZATION_THROTTLE_TIME)
 6372                .await;
 6373        }
 6374
 6375        Ok(())
 6376    }
 6377
 6378    pub(crate) fn enqueue_item_serialization(
 6379        &mut self,
 6380        item: Box<dyn SerializableItemHandle>,
 6381    ) -> Result<()> {
 6382        self.serializable_items_tx
 6383            .unbounded_send(item)
 6384            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6385    }
 6386
 6387    pub(crate) fn load_workspace(
 6388        serialized_workspace: SerializedWorkspace,
 6389        paths_to_open: Vec<Option<ProjectPath>>,
 6390        window: &mut Window,
 6391        cx: &mut Context<Workspace>,
 6392    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6393        cx.spawn_in(window, async move |workspace, cx| {
 6394            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6395
 6396            let mut center_group = None;
 6397            let mut center_items = None;
 6398
 6399            // Traverse the splits tree and add to things
 6400            if let Some((group, active_pane, items)) = serialized_workspace
 6401                .center_group
 6402                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6403                .await
 6404            {
 6405                center_items = Some(items);
 6406                center_group = Some((group, active_pane))
 6407            }
 6408
 6409            let mut items_by_project_path = HashMap::default();
 6410            let mut item_ids_by_kind = HashMap::default();
 6411            let mut all_deserialized_items = Vec::default();
 6412            cx.update(|_, cx| {
 6413                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6414                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6415                        item_ids_by_kind
 6416                            .entry(serializable_item_handle.serialized_item_kind())
 6417                            .or_insert(Vec::new())
 6418                            .push(item.item_id().as_u64() as ItemId);
 6419                    }
 6420
 6421                    if let Some(project_path) = item.project_path(cx) {
 6422                        items_by_project_path.insert(project_path, item.clone());
 6423                    }
 6424                    all_deserialized_items.push(item);
 6425                }
 6426            })?;
 6427
 6428            let opened_items = paths_to_open
 6429                .into_iter()
 6430                .map(|path_to_open| {
 6431                    path_to_open
 6432                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6433                })
 6434                .collect::<Vec<_>>();
 6435
 6436            // Remove old panes from workspace panes list
 6437            workspace.update_in(cx, |workspace, window, cx| {
 6438                if let Some((center_group, active_pane)) = center_group {
 6439                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6440
 6441                    // Swap workspace center group
 6442                    workspace.center = PaneGroup::with_root(center_group);
 6443                    workspace.center.set_is_center(true);
 6444                    workspace.center.mark_positions(cx);
 6445
 6446                    if let Some(active_pane) = active_pane {
 6447                        workspace.set_active_pane(&active_pane, window, cx);
 6448                        cx.focus_self(window);
 6449                    } else {
 6450                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6451                    }
 6452                }
 6453
 6454                let docks = serialized_workspace.docks;
 6455
 6456                for (dock, serialized_dock) in [
 6457                    (&mut workspace.right_dock, docks.right),
 6458                    (&mut workspace.left_dock, docks.left),
 6459                    (&mut workspace.bottom_dock, docks.bottom),
 6460                ]
 6461                .iter_mut()
 6462                {
 6463                    dock.update(cx, |dock, cx| {
 6464                        dock.serialized_dock = Some(serialized_dock.clone());
 6465                        dock.restore_state(window, cx);
 6466                    });
 6467                }
 6468
 6469                cx.notify();
 6470            })?;
 6471
 6472            let _ = project
 6473                .update(cx, |project, cx| {
 6474                    project
 6475                        .breakpoint_store()
 6476                        .update(cx, |breakpoint_store, cx| {
 6477                            breakpoint_store
 6478                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6479                        })
 6480                })
 6481                .await;
 6482
 6483            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6484            // after loading the items, we might have different items and in order to avoid
 6485            // the database filling up, we delete items that haven't been loaded now.
 6486            //
 6487            // The items that have been loaded, have been saved after they've been added to the workspace.
 6488            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6489                item_ids_by_kind
 6490                    .into_iter()
 6491                    .map(|(item_kind, loaded_items)| {
 6492                        SerializableItemRegistry::cleanup(
 6493                            item_kind,
 6494                            serialized_workspace.id,
 6495                            loaded_items,
 6496                            window,
 6497                            cx,
 6498                        )
 6499                        .log_err()
 6500                    })
 6501                    .collect::<Vec<_>>()
 6502            })?;
 6503
 6504            futures::future::join_all(clean_up_tasks).await;
 6505
 6506            workspace
 6507                .update_in(cx, |workspace, window, cx| {
 6508                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6509                    workspace.serialize_workspace_internal(window, cx).detach();
 6510
 6511                    // Ensure that we mark the window as edited if we did load dirty items
 6512                    workspace.update_window_edited(window, cx);
 6513                })
 6514                .ok();
 6515
 6516            Ok(opened_items)
 6517        })
 6518    }
 6519
 6520    pub fn key_context(&self, cx: &App) -> KeyContext {
 6521        let mut context = KeyContext::new_with_defaults();
 6522        context.add("Workspace");
 6523        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6524        if let Some(status) = self
 6525            .debugger_provider
 6526            .as_ref()
 6527            .and_then(|provider| provider.active_thread_state(cx))
 6528        {
 6529            match status {
 6530                ThreadStatus::Running | ThreadStatus::Stepping => {
 6531                    context.add("debugger_running");
 6532                }
 6533                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6534                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6535            }
 6536        }
 6537
 6538        if self.left_dock.read(cx).is_open() {
 6539            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6540                context.set("left_dock", active_panel.panel_key());
 6541            }
 6542        }
 6543
 6544        if self.right_dock.read(cx).is_open() {
 6545            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6546                context.set("right_dock", active_panel.panel_key());
 6547            }
 6548        }
 6549
 6550        if self.bottom_dock.read(cx).is_open() {
 6551            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6552                context.set("bottom_dock", active_panel.panel_key());
 6553            }
 6554        }
 6555
 6556        context
 6557    }
 6558
 6559    /// Multiworkspace uses this to add workspace action handling to itself
 6560    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6561        self.add_workspace_actions_listeners(div, window, cx)
 6562            .on_action(cx.listener(
 6563                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6564                    for action in &action_sequence.0 {
 6565                        window.dispatch_action(action.boxed_clone(), cx);
 6566                    }
 6567                },
 6568            ))
 6569            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6570            .on_action(cx.listener(Self::close_all_items_and_panes))
 6571            .on_action(cx.listener(Self::close_item_in_all_panes))
 6572            .on_action(cx.listener(Self::save_all))
 6573            .on_action(cx.listener(Self::send_keystrokes))
 6574            .on_action(cx.listener(Self::add_folder_to_project))
 6575            .on_action(cx.listener(Self::follow_next_collaborator))
 6576            .on_action(cx.listener(Self::activate_pane_at_index))
 6577            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6578            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6579            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6580            .on_action(cx.listener(Self::toggle_theme_mode))
 6581            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6582                let pane = workspace.active_pane().clone();
 6583                workspace.unfollow_in_pane(&pane, window, cx);
 6584            }))
 6585            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6586                workspace
 6587                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6588                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6589            }))
 6590            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6591                workspace
 6592                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6593                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6594            }))
 6595            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6596                workspace
 6597                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6598                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6599            }))
 6600            .on_action(
 6601                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6602                    workspace.activate_previous_pane(window, cx)
 6603                }),
 6604            )
 6605            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6606                workspace.activate_next_pane(window, cx)
 6607            }))
 6608            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6609                workspace.activate_last_pane(window, cx)
 6610            }))
 6611            .on_action(
 6612                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6613                    workspace.activate_next_window(cx)
 6614                }),
 6615            )
 6616            .on_action(
 6617                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6618                    workspace.activate_previous_window(cx)
 6619                }),
 6620            )
 6621            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6622                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6623            }))
 6624            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6625                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6626            }))
 6627            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6628                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6629            }))
 6630            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6631                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6632            }))
 6633            .on_action(cx.listener(
 6634                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6635                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6636                },
 6637            ))
 6638            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6639                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6640            }))
 6641            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6642                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6643            }))
 6644            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6645                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6646            }))
 6647            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6648                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6649            }))
 6650            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6651                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6652                    SplitDirection::Down,
 6653                    SplitDirection::Up,
 6654                    SplitDirection::Right,
 6655                    SplitDirection::Left,
 6656                ];
 6657                for dir in DIRECTION_PRIORITY {
 6658                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6659                        workspace.swap_pane_in_direction(dir, cx);
 6660                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6661                        break;
 6662                    }
 6663                }
 6664            }))
 6665            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6666                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6667            }))
 6668            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6669                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6670            }))
 6671            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6672                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6673            }))
 6674            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6675                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6676            }))
 6677            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6678                this.toggle_dock(DockPosition::Left, window, cx);
 6679            }))
 6680            .on_action(cx.listener(
 6681                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6682                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6683                },
 6684            ))
 6685            .on_action(cx.listener(
 6686                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6687                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6688                },
 6689            ))
 6690            .on_action(cx.listener(
 6691                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6692                    if !workspace.close_active_dock(window, cx) {
 6693                        cx.propagate();
 6694                    }
 6695                },
 6696            ))
 6697            .on_action(
 6698                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6699                    workspace.close_all_docks(window, cx);
 6700                }),
 6701            )
 6702            .on_action(cx.listener(Self::toggle_all_docks))
 6703            .on_action(cx.listener(
 6704                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6705                    workspace.clear_all_notifications(cx);
 6706                },
 6707            ))
 6708            .on_action(cx.listener(
 6709                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6710                    workspace.clear_navigation_history(window, cx);
 6711                },
 6712            ))
 6713            .on_action(cx.listener(
 6714                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6715                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6716                        workspace.suppress_notification(&notification_id, cx);
 6717                    }
 6718                },
 6719            ))
 6720            .on_action(cx.listener(
 6721                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6722                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6723                },
 6724            ))
 6725            .on_action(
 6726                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6727                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6728                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6729                            trusted_worktrees.clear_trusted_paths()
 6730                        });
 6731                        let db = WorkspaceDb::global(cx);
 6732                        cx.spawn(async move |_, cx| {
 6733                            if db.clear_trusted_worktrees().await.log_err().is_some() {
 6734                                cx.update(|cx| reload(cx));
 6735                            }
 6736                        })
 6737                        .detach();
 6738                    }
 6739                }),
 6740            )
 6741            .on_action(cx.listener(
 6742                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 6743                    workspace.reopen_closed_item(window, cx).detach();
 6744                },
 6745            ))
 6746            .on_action(cx.listener(
 6747                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 6748                    for dock in workspace.all_docks() {
 6749                        if dock.focus_handle(cx).contains_focused(window, cx) {
 6750                            let Some(panel) = dock.read(cx).active_panel() else {
 6751                                return;
 6752                            };
 6753
 6754                            // Set to `None`, then the size will fall back to the default.
 6755                            panel.clone().set_size(None, window, cx);
 6756
 6757                            return;
 6758                        }
 6759                    }
 6760                },
 6761            ))
 6762            .on_action(cx.listener(
 6763                |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
 6764                    for dock in workspace.all_docks() {
 6765                        if let Some(panel) = dock.read(cx).visible_panel() {
 6766                            // Set to `None`, then the size will fall back to the default.
 6767                            panel.clone().set_size(None, window, cx);
 6768                        }
 6769                    }
 6770                },
 6771            ))
 6772            .on_action(cx.listener(
 6773                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 6774                    adjust_active_dock_size_by_px(
 6775                        px_with_ui_font_fallback(act.px, cx),
 6776                        workspace,
 6777                        window,
 6778                        cx,
 6779                    );
 6780                },
 6781            ))
 6782            .on_action(cx.listener(
 6783                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 6784                    adjust_active_dock_size_by_px(
 6785                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6786                        workspace,
 6787                        window,
 6788                        cx,
 6789                    );
 6790                },
 6791            ))
 6792            .on_action(cx.listener(
 6793                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 6794                    adjust_open_docks_size_by_px(
 6795                        px_with_ui_font_fallback(act.px, cx),
 6796                        workspace,
 6797                        window,
 6798                        cx,
 6799                    );
 6800                },
 6801            ))
 6802            .on_action(cx.listener(
 6803                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 6804                    adjust_open_docks_size_by_px(
 6805                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6806                        workspace,
 6807                        window,
 6808                        cx,
 6809                    );
 6810                },
 6811            ))
 6812            .on_action(cx.listener(Workspace::toggle_centered_layout))
 6813            .on_action(cx.listener(
 6814                |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
 6815                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6816                        let dock = active_dock.read(cx);
 6817                        if let Some(active_panel) = dock.active_panel() {
 6818                            if active_panel.pane(cx).is_none() {
 6819                                let mut recent_pane: Option<Entity<Pane>> = None;
 6820                                let mut recent_timestamp = 0;
 6821                                for pane_handle in workspace.panes() {
 6822                                    let pane = pane_handle.read(cx);
 6823                                    for entry in pane.activation_history() {
 6824                                        if entry.timestamp > recent_timestamp {
 6825                                            recent_timestamp = entry.timestamp;
 6826                                            recent_pane = Some(pane_handle.clone());
 6827                                        }
 6828                                    }
 6829                                }
 6830
 6831                                if let Some(pane) = recent_pane {
 6832                                    pane.update(cx, |pane, cx| {
 6833                                        let current_index = pane.active_item_index();
 6834                                        let items_len = pane.items_len();
 6835                                        if items_len > 0 {
 6836                                            let next_index = if current_index + 1 < items_len {
 6837                                                current_index + 1
 6838                                            } else {
 6839                                                0
 6840                                            };
 6841                                            pane.activate_item(
 6842                                                next_index, false, false, window, cx,
 6843                                            );
 6844                                        }
 6845                                    });
 6846                                    return;
 6847                                }
 6848                            }
 6849                        }
 6850                    }
 6851                    cx.propagate();
 6852                },
 6853            ))
 6854            .on_action(cx.listener(
 6855                |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
 6856                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6857                        let dock = active_dock.read(cx);
 6858                        if let Some(active_panel) = dock.active_panel() {
 6859                            if active_panel.pane(cx).is_none() {
 6860                                let mut recent_pane: Option<Entity<Pane>> = None;
 6861                                let mut recent_timestamp = 0;
 6862                                for pane_handle in workspace.panes() {
 6863                                    let pane = pane_handle.read(cx);
 6864                                    for entry in pane.activation_history() {
 6865                                        if entry.timestamp > recent_timestamp {
 6866                                            recent_timestamp = entry.timestamp;
 6867                                            recent_pane = Some(pane_handle.clone());
 6868                                        }
 6869                                    }
 6870                                }
 6871
 6872                                if let Some(pane) = recent_pane {
 6873                                    pane.update(cx, |pane, cx| {
 6874                                        let current_index = pane.active_item_index();
 6875                                        let items_len = pane.items_len();
 6876                                        if items_len > 0 {
 6877                                            let prev_index = if current_index > 0 {
 6878                                                current_index - 1
 6879                                            } else {
 6880                                                items_len.saturating_sub(1)
 6881                                            };
 6882                                            pane.activate_item(
 6883                                                prev_index, false, false, window, cx,
 6884                                            );
 6885                                        }
 6886                                    });
 6887                                    return;
 6888                                }
 6889                            }
 6890                        }
 6891                    }
 6892                    cx.propagate();
 6893                },
 6894            ))
 6895            .on_action(cx.listener(
 6896                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 6897                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6898                        let dock = active_dock.read(cx);
 6899                        if let Some(active_panel) = dock.active_panel() {
 6900                            if active_panel.pane(cx).is_none() {
 6901                                let active_pane = workspace.active_pane().clone();
 6902                                active_pane.update(cx, |pane, cx| {
 6903                                    pane.close_active_item(action, window, cx)
 6904                                        .detach_and_log_err(cx);
 6905                                });
 6906                                return;
 6907                            }
 6908                        }
 6909                    }
 6910                    cx.propagate();
 6911                },
 6912            ))
 6913            .on_action(
 6914                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 6915                    let pane = workspace.active_pane().clone();
 6916                    if let Some(item) = pane.read(cx).active_item() {
 6917                        item.toggle_read_only(window, cx);
 6918                    }
 6919                }),
 6920            )
 6921            .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
 6922                workspace.focus_center_pane(window, cx);
 6923            }))
 6924            .on_action(cx.listener(Workspace::cancel))
 6925    }
 6926
 6927    #[cfg(any(test, feature = "test-support"))]
 6928    pub fn set_random_database_id(&mut self) {
 6929        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 6930    }
 6931
 6932    #[cfg(any(test, feature = "test-support"))]
 6933    pub(crate) fn test_new(
 6934        project: Entity<Project>,
 6935        window: &mut Window,
 6936        cx: &mut Context<Self>,
 6937    ) -> Self {
 6938        use node_runtime::NodeRuntime;
 6939        use session::Session;
 6940
 6941        let client = project.read(cx).client();
 6942        let user_store = project.read(cx).user_store();
 6943        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 6944        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 6945        window.activate_window();
 6946        let app_state = Arc::new(AppState {
 6947            languages: project.read(cx).languages().clone(),
 6948            workspace_store,
 6949            client,
 6950            user_store,
 6951            fs: project.read(cx).fs().clone(),
 6952            build_window_options: |_, _| Default::default(),
 6953            node_runtime: NodeRuntime::unavailable(),
 6954            session,
 6955        });
 6956        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 6957        workspace
 6958            .active_pane
 6959            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6960        workspace
 6961    }
 6962
 6963    pub fn register_action<A: Action>(
 6964        &mut self,
 6965        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 6966    ) -> &mut Self {
 6967        let callback = Arc::new(callback);
 6968
 6969        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 6970            let callback = callback.clone();
 6971            div.on_action(cx.listener(move |workspace, event, window, cx| {
 6972                (callback)(workspace, event, window, cx)
 6973            }))
 6974        }));
 6975        self
 6976    }
 6977    pub fn register_action_renderer(
 6978        &mut self,
 6979        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 6980    ) -> &mut Self {
 6981        self.workspace_actions.push(Box::new(callback));
 6982        self
 6983    }
 6984
 6985    fn add_workspace_actions_listeners(
 6986        &self,
 6987        mut div: Div,
 6988        window: &mut Window,
 6989        cx: &mut Context<Self>,
 6990    ) -> Div {
 6991        for action in self.workspace_actions.iter() {
 6992            div = (action)(div, self, window, cx)
 6993        }
 6994        div
 6995    }
 6996
 6997    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 6998        self.modal_layer.read(cx).has_active_modal()
 6999    }
 7000
 7001    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7002        self.modal_layer.read(cx).active_modal()
 7003    }
 7004
 7005    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7006    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7007    /// If no modal is active, the new modal will be shown.
 7008    ///
 7009    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7010    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7011    /// will not be shown.
 7012    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7013    where
 7014        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7015    {
 7016        self.modal_layer.update(cx, |modal_layer, cx| {
 7017            modal_layer.toggle_modal(window, cx, build)
 7018        })
 7019    }
 7020
 7021    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7022        self.modal_layer
 7023            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7024    }
 7025
 7026    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7027        self.toast_layer
 7028            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7029    }
 7030
 7031    pub fn toggle_centered_layout(
 7032        &mut self,
 7033        _: &ToggleCenteredLayout,
 7034        _: &mut Window,
 7035        cx: &mut Context<Self>,
 7036    ) {
 7037        self.centered_layout = !self.centered_layout;
 7038        if let Some(database_id) = self.database_id() {
 7039            let db = WorkspaceDb::global(cx);
 7040            let centered_layout = self.centered_layout;
 7041            cx.background_spawn(async move {
 7042                db.set_centered_layout(database_id, centered_layout).await
 7043            })
 7044            .detach_and_log_err(cx);
 7045        }
 7046        cx.notify();
 7047    }
 7048
 7049    fn adjust_padding(padding: Option<f32>) -> f32 {
 7050        padding
 7051            .unwrap_or(CenteredPaddingSettings::default().0)
 7052            .clamp(
 7053                CenteredPaddingSettings::MIN_PADDING,
 7054                CenteredPaddingSettings::MAX_PADDING,
 7055            )
 7056    }
 7057
 7058    fn render_dock(
 7059        &self,
 7060        position: DockPosition,
 7061        dock: &Entity<Dock>,
 7062        window: &mut Window,
 7063        cx: &mut App,
 7064    ) -> Option<Div> {
 7065        if self.zoomed_position == Some(position) {
 7066            return None;
 7067        }
 7068
 7069        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7070            let pane = panel.pane(cx)?;
 7071            let follower_states = &self.follower_states;
 7072            leader_border_for_pane(follower_states, &pane, window, cx)
 7073        });
 7074
 7075        Some(
 7076            div()
 7077                .flex()
 7078                .flex_none()
 7079                .overflow_hidden()
 7080                .child(dock.clone())
 7081                .children(leader_border),
 7082        )
 7083    }
 7084
 7085    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7086        window
 7087            .root::<MultiWorkspace>()
 7088            .flatten()
 7089            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7090    }
 7091
 7092    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7093        self.zoomed.as_ref()
 7094    }
 7095
 7096    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7097        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7098            return;
 7099        };
 7100        let windows = cx.windows();
 7101        let next_window =
 7102            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7103                || {
 7104                    windows
 7105                        .iter()
 7106                        .cycle()
 7107                        .skip_while(|window| window.window_id() != current_window_id)
 7108                        .nth(1)
 7109                },
 7110            );
 7111
 7112        if let Some(window) = next_window {
 7113            window
 7114                .update(cx, |_, window, _| window.activate_window())
 7115                .ok();
 7116        }
 7117    }
 7118
 7119    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7120        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7121            return;
 7122        };
 7123        let windows = cx.windows();
 7124        let prev_window =
 7125            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7126                || {
 7127                    windows
 7128                        .iter()
 7129                        .rev()
 7130                        .cycle()
 7131                        .skip_while(|window| window.window_id() != current_window_id)
 7132                        .nth(1)
 7133                },
 7134            );
 7135
 7136        if let Some(window) = prev_window {
 7137            window
 7138                .update(cx, |_, window, _| window.activate_window())
 7139                .ok();
 7140        }
 7141    }
 7142
 7143    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7144        if cx.stop_active_drag(window) {
 7145        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7146            dismiss_app_notification(&notification_id, cx);
 7147        } else {
 7148            cx.propagate();
 7149        }
 7150    }
 7151
 7152    fn adjust_dock_size_by_px(
 7153        &mut self,
 7154        panel_size: Pixels,
 7155        dock_pos: DockPosition,
 7156        px: Pixels,
 7157        window: &mut Window,
 7158        cx: &mut Context<Self>,
 7159    ) {
 7160        match dock_pos {
 7161            DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
 7162            DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
 7163            DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
 7164        }
 7165    }
 7166
 7167    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7168        let workspace_width = self.bounds.size.width;
 7169        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7170
 7171        self.right_dock.read_with(cx, |right_dock, cx| {
 7172            let right_dock_size = right_dock
 7173                .active_panel_size(window, cx)
 7174                .unwrap_or(Pixels::ZERO);
 7175            if right_dock_size + size > workspace_width {
 7176                size = workspace_width - right_dock_size
 7177            }
 7178        });
 7179
 7180        self.left_dock.update(cx, |left_dock, cx| {
 7181            if WorkspaceSettings::get_global(cx)
 7182                .resize_all_panels_in_dock
 7183                .contains(&DockPosition::Left)
 7184            {
 7185                left_dock.resize_all_panels(Some(size), window, cx);
 7186            } else {
 7187                left_dock.resize_active_panel(Some(size), window, cx);
 7188            }
 7189        });
 7190    }
 7191
 7192    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7193        let workspace_width = self.bounds.size.width;
 7194        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7195        self.left_dock.read_with(cx, |left_dock, cx| {
 7196            let left_dock_size = left_dock
 7197                .active_panel_size(window, cx)
 7198                .unwrap_or(Pixels::ZERO);
 7199            if left_dock_size + size > workspace_width {
 7200                size = workspace_width - left_dock_size
 7201            }
 7202        });
 7203        self.right_dock.update(cx, |right_dock, cx| {
 7204            if WorkspaceSettings::get_global(cx)
 7205                .resize_all_panels_in_dock
 7206                .contains(&DockPosition::Right)
 7207            {
 7208                right_dock.resize_all_panels(Some(size), window, cx);
 7209            } else {
 7210                right_dock.resize_active_panel(Some(size), window, cx);
 7211            }
 7212        });
 7213    }
 7214
 7215    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7216        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7217        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7218            if WorkspaceSettings::get_global(cx)
 7219                .resize_all_panels_in_dock
 7220                .contains(&DockPosition::Bottom)
 7221            {
 7222                bottom_dock.resize_all_panels(Some(size), window, cx);
 7223            } else {
 7224                bottom_dock.resize_active_panel(Some(size), window, cx);
 7225            }
 7226        });
 7227    }
 7228
 7229    fn toggle_edit_predictions_all_files(
 7230        &mut self,
 7231        _: &ToggleEditPrediction,
 7232        _window: &mut Window,
 7233        cx: &mut Context<Self>,
 7234    ) {
 7235        let fs = self.project().read(cx).fs().clone();
 7236        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7237        update_settings_file(fs, cx, move |file, _| {
 7238            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7239        });
 7240    }
 7241
 7242    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7243        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7244        let next_mode = match current_mode {
 7245            Some(theme::ThemeAppearanceMode::Light) => theme::ThemeAppearanceMode::Dark,
 7246            Some(theme::ThemeAppearanceMode::Dark) => theme::ThemeAppearanceMode::Light,
 7247            Some(theme::ThemeAppearanceMode::System) | None => match cx.theme().appearance() {
 7248                theme::Appearance::Light => theme::ThemeAppearanceMode::Dark,
 7249                theme::Appearance::Dark => theme::ThemeAppearanceMode::Light,
 7250            },
 7251        };
 7252
 7253        let fs = self.project().read(cx).fs().clone();
 7254        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7255            theme::set_mode(settings, next_mode);
 7256        });
 7257    }
 7258
 7259    pub fn show_worktree_trust_security_modal(
 7260        &mut self,
 7261        toggle: bool,
 7262        window: &mut Window,
 7263        cx: &mut Context<Self>,
 7264    ) {
 7265        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7266            if toggle {
 7267                security_modal.update(cx, |security_modal, cx| {
 7268                    security_modal.dismiss(cx);
 7269                })
 7270            } else {
 7271                security_modal.update(cx, |security_modal, cx| {
 7272                    security_modal.refresh_restricted_paths(cx);
 7273                });
 7274            }
 7275        } else {
 7276            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7277                .map(|trusted_worktrees| {
 7278                    trusted_worktrees
 7279                        .read(cx)
 7280                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7281                })
 7282                .unwrap_or(false);
 7283            if has_restricted_worktrees {
 7284                let project = self.project().read(cx);
 7285                let remote_host = project
 7286                    .remote_connection_options(cx)
 7287                    .map(RemoteHostLocation::from);
 7288                let worktree_store = project.worktree_store().downgrade();
 7289                self.toggle_modal(window, cx, |_, cx| {
 7290                    SecurityModal::new(worktree_store, remote_host, cx)
 7291                });
 7292            }
 7293        }
 7294    }
 7295}
 7296
 7297pub trait AnyActiveCall {
 7298    fn entity(&self) -> AnyEntity;
 7299    fn is_in_room(&self, _: &App) -> bool;
 7300    fn room_id(&self, _: &App) -> Option<u64>;
 7301    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7302    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7303    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7304    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7305    fn is_sharing_project(&self, _: &App) -> bool;
 7306    fn has_remote_participants(&self, _: &App) -> bool;
 7307    fn local_participant_is_guest(&self, _: &App) -> bool;
 7308    fn client(&self, _: &App) -> Arc<Client>;
 7309    fn share_on_join(&self, _: &App) -> bool;
 7310    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7311    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7312    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7313    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7314    fn join_project(
 7315        &self,
 7316        _: u64,
 7317        _: Arc<LanguageRegistry>,
 7318        _: Arc<dyn Fs>,
 7319        _: &mut App,
 7320    ) -> Task<Result<Entity<Project>>>;
 7321    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7322    fn subscribe(
 7323        &self,
 7324        _: &mut Window,
 7325        _: &mut Context<Workspace>,
 7326        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7327    ) -> Subscription;
 7328    fn create_shared_screen(
 7329        &self,
 7330        _: PeerId,
 7331        _: &Entity<Pane>,
 7332        _: &mut Window,
 7333        _: &mut App,
 7334    ) -> Option<Entity<SharedScreen>>;
 7335}
 7336
 7337#[derive(Clone)]
 7338pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7339impl Global for GlobalAnyActiveCall {}
 7340
 7341impl GlobalAnyActiveCall {
 7342    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7343        cx.try_global()
 7344    }
 7345
 7346    pub(crate) fn global(cx: &App) -> &Self {
 7347        cx.global()
 7348    }
 7349}
 7350
 7351pub fn merge_conflict_notification_id() -> NotificationId {
 7352    struct MergeConflictNotification;
 7353    NotificationId::unique::<MergeConflictNotification>()
 7354}
 7355
 7356/// Workspace-local view of a remote participant's location.
 7357#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7358pub enum ParticipantLocation {
 7359    SharedProject { project_id: u64 },
 7360    UnsharedProject,
 7361    External,
 7362}
 7363
 7364impl ParticipantLocation {
 7365    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7366        match location
 7367            .and_then(|l| l.variant)
 7368            .context("participant location was not provided")?
 7369        {
 7370            proto::participant_location::Variant::SharedProject(project) => {
 7371                Ok(Self::SharedProject {
 7372                    project_id: project.id,
 7373                })
 7374            }
 7375            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7376            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7377        }
 7378    }
 7379}
 7380/// Workspace-local view of a remote collaborator's state.
 7381/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7382#[derive(Clone)]
 7383pub struct RemoteCollaborator {
 7384    pub user: Arc<User>,
 7385    pub peer_id: PeerId,
 7386    pub location: ParticipantLocation,
 7387    pub participant_index: ParticipantIndex,
 7388}
 7389
 7390pub enum ActiveCallEvent {
 7391    ParticipantLocationChanged { participant_id: PeerId },
 7392    RemoteVideoTracksChanged { participant_id: PeerId },
 7393}
 7394
 7395fn leader_border_for_pane(
 7396    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7397    pane: &Entity<Pane>,
 7398    _: &Window,
 7399    cx: &App,
 7400) -> Option<Div> {
 7401    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7402        if state.pane() == pane {
 7403            Some((*leader_id, state))
 7404        } else {
 7405            None
 7406        }
 7407    })?;
 7408
 7409    let mut leader_color = match leader_id {
 7410        CollaboratorId::PeerId(leader_peer_id) => {
 7411            let leader = GlobalAnyActiveCall::try_global(cx)?
 7412                .0
 7413                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7414
 7415            cx.theme()
 7416                .players()
 7417                .color_for_participant(leader.participant_index.0)
 7418                .cursor
 7419        }
 7420        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7421    };
 7422    leader_color.fade_out(0.3);
 7423    Some(
 7424        div()
 7425            .absolute()
 7426            .size_full()
 7427            .left_0()
 7428            .top_0()
 7429            .border_2()
 7430            .border_color(leader_color),
 7431    )
 7432}
 7433
 7434fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7435    ZED_WINDOW_POSITION
 7436        .zip(*ZED_WINDOW_SIZE)
 7437        .map(|(position, size)| Bounds {
 7438            origin: position,
 7439            size,
 7440        })
 7441}
 7442
 7443fn open_items(
 7444    serialized_workspace: Option<SerializedWorkspace>,
 7445    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7446    window: &mut Window,
 7447    cx: &mut Context<Workspace>,
 7448) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7449    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7450        Workspace::load_workspace(
 7451            serialized_workspace,
 7452            project_paths_to_open
 7453                .iter()
 7454                .map(|(_, project_path)| project_path)
 7455                .cloned()
 7456                .collect(),
 7457            window,
 7458            cx,
 7459        )
 7460    });
 7461
 7462    cx.spawn_in(window, async move |workspace, cx| {
 7463        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7464
 7465        if let Some(restored_items) = restored_items {
 7466            let restored_items = restored_items.await?;
 7467
 7468            let restored_project_paths = restored_items
 7469                .iter()
 7470                .filter_map(|item| {
 7471                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7472                        .ok()
 7473                        .flatten()
 7474                })
 7475                .collect::<HashSet<_>>();
 7476
 7477            for restored_item in restored_items {
 7478                opened_items.push(restored_item.map(Ok));
 7479            }
 7480
 7481            project_paths_to_open
 7482                .iter_mut()
 7483                .for_each(|(_, project_path)| {
 7484                    if let Some(project_path_to_open) = project_path
 7485                        && restored_project_paths.contains(project_path_to_open)
 7486                    {
 7487                        *project_path = None;
 7488                    }
 7489                });
 7490        } else {
 7491            for _ in 0..project_paths_to_open.len() {
 7492                opened_items.push(None);
 7493            }
 7494        }
 7495        assert!(opened_items.len() == project_paths_to_open.len());
 7496
 7497        let tasks =
 7498            project_paths_to_open
 7499                .into_iter()
 7500                .enumerate()
 7501                .map(|(ix, (abs_path, project_path))| {
 7502                    let workspace = workspace.clone();
 7503                    cx.spawn(async move |cx| {
 7504                        let file_project_path = project_path?;
 7505                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7506                            workspace.project().update(cx, |project, cx| {
 7507                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7508                            })
 7509                        });
 7510
 7511                        // We only want to open file paths here. If one of the items
 7512                        // here is a directory, it was already opened further above
 7513                        // with a `find_or_create_worktree`.
 7514                        if let Ok(task) = abs_path_task
 7515                            && task.await.is_none_or(|p| p.is_file())
 7516                        {
 7517                            return Some((
 7518                                ix,
 7519                                workspace
 7520                                    .update_in(cx, |workspace, window, cx| {
 7521                                        workspace.open_path(
 7522                                            file_project_path,
 7523                                            None,
 7524                                            true,
 7525                                            window,
 7526                                            cx,
 7527                                        )
 7528                                    })
 7529                                    .log_err()?
 7530                                    .await,
 7531                            ));
 7532                        }
 7533                        None
 7534                    })
 7535                });
 7536
 7537        let tasks = tasks.collect::<Vec<_>>();
 7538
 7539        let tasks = futures::future::join_all(tasks);
 7540        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7541            opened_items[ix] = Some(path_open_result);
 7542        }
 7543
 7544        Ok(opened_items)
 7545    })
 7546}
 7547
 7548#[derive(Clone)]
 7549enum ActivateInDirectionTarget {
 7550    Pane(Entity<Pane>),
 7551    Dock(Entity<Dock>),
 7552    Sidebar(FocusHandle),
 7553}
 7554
 7555fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7556    window
 7557        .update(cx, |multi_workspace, _, cx| {
 7558            let workspace = multi_workspace.workspace().clone();
 7559            workspace.update(cx, |workspace, cx| {
 7560                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7561                    struct DatabaseFailedNotification;
 7562
 7563                    workspace.show_notification(
 7564                        NotificationId::unique::<DatabaseFailedNotification>(),
 7565                        cx,
 7566                        |cx| {
 7567                            cx.new(|cx| {
 7568                                MessageNotification::new("Failed to load the database file.", cx)
 7569                                    .primary_message("File an Issue")
 7570                                    .primary_icon(IconName::Plus)
 7571                                    .primary_on_click(|window, cx| {
 7572                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7573                                    })
 7574                            })
 7575                        },
 7576                    );
 7577                }
 7578            });
 7579        })
 7580        .log_err();
 7581}
 7582
 7583fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7584    if val == 0 {
 7585        ThemeSettings::get_global(cx).ui_font_size(cx)
 7586    } else {
 7587        px(val as f32)
 7588    }
 7589}
 7590
 7591fn adjust_active_dock_size_by_px(
 7592    px: Pixels,
 7593    workspace: &mut Workspace,
 7594    window: &mut Window,
 7595    cx: &mut Context<Workspace>,
 7596) {
 7597    let Some(active_dock) = workspace
 7598        .all_docks()
 7599        .into_iter()
 7600        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7601    else {
 7602        return;
 7603    };
 7604    let dock = active_dock.read(cx);
 7605    let Some(panel_size) = dock.active_panel_size(window, cx) else {
 7606        return;
 7607    };
 7608    let dock_pos = dock.position();
 7609    workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
 7610}
 7611
 7612fn adjust_open_docks_size_by_px(
 7613    px: Pixels,
 7614    workspace: &mut Workspace,
 7615    window: &mut Window,
 7616    cx: &mut Context<Workspace>,
 7617) {
 7618    let docks = workspace
 7619        .all_docks()
 7620        .into_iter()
 7621        .filter_map(|dock| {
 7622            if dock.read(cx).is_open() {
 7623                let dock = dock.read(cx);
 7624                let panel_size = dock.active_panel_size(window, cx)?;
 7625                let dock_pos = dock.position();
 7626                Some((panel_size, dock_pos, px))
 7627            } else {
 7628                None
 7629            }
 7630        })
 7631        .collect::<Vec<_>>();
 7632
 7633    docks
 7634        .into_iter()
 7635        .for_each(|(panel_size, dock_pos, offset)| {
 7636            workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
 7637        });
 7638}
 7639
 7640impl Focusable for Workspace {
 7641    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7642        self.active_pane.focus_handle(cx)
 7643    }
 7644}
 7645
 7646#[derive(Clone)]
 7647struct DraggedDock(DockPosition);
 7648
 7649impl Render for DraggedDock {
 7650    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7651        gpui::Empty
 7652    }
 7653}
 7654
 7655impl Render for Workspace {
 7656    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 7657        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 7658        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 7659            log::info!("Rendered first frame");
 7660        }
 7661
 7662        let centered_layout = self.centered_layout
 7663            && self.center.panes().len() == 1
 7664            && self.active_item(cx).is_some();
 7665        let render_padding = |size| {
 7666            (size > 0.0).then(|| {
 7667                div()
 7668                    .h_full()
 7669                    .w(relative(size))
 7670                    .bg(cx.theme().colors().editor_background)
 7671                    .border_color(cx.theme().colors().pane_group_border)
 7672            })
 7673        };
 7674        let paddings = if centered_layout {
 7675            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 7676            (
 7677                render_padding(Self::adjust_padding(
 7678                    settings.left_padding.map(|padding| padding.0),
 7679                )),
 7680                render_padding(Self::adjust_padding(
 7681                    settings.right_padding.map(|padding| padding.0),
 7682                )),
 7683            )
 7684        } else {
 7685            (None, None)
 7686        };
 7687        let ui_font = theme::setup_ui_font(window, cx);
 7688
 7689        let theme = cx.theme().clone();
 7690        let colors = theme.colors();
 7691        let notification_entities = self
 7692            .notifications
 7693            .iter()
 7694            .map(|(_, notification)| notification.entity_id())
 7695            .collect::<Vec<_>>();
 7696        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 7697
 7698        div()
 7699            .relative()
 7700            .size_full()
 7701            .flex()
 7702            .flex_col()
 7703            .font(ui_font)
 7704            .gap_0()
 7705                .justify_start()
 7706                .items_start()
 7707                .text_color(colors.text)
 7708                .overflow_hidden()
 7709                .children(self.titlebar_item.clone())
 7710                .on_modifiers_changed(move |_, _, cx| {
 7711                    for &id in &notification_entities {
 7712                        cx.notify(id);
 7713                    }
 7714                })
 7715                .child(
 7716                    div()
 7717                        .size_full()
 7718                        .relative()
 7719                        .flex_1()
 7720                        .flex()
 7721                        .flex_col()
 7722                        .child(
 7723                            div()
 7724                                .id("workspace")
 7725                                .bg(colors.background)
 7726                                .relative()
 7727                                .flex_1()
 7728                                .w_full()
 7729                                .flex()
 7730                                .flex_col()
 7731                                .overflow_hidden()
 7732                                .border_t_1()
 7733                                .border_b_1()
 7734                                .border_color(colors.border)
 7735                                .child({
 7736                                    let this = cx.entity();
 7737                                    canvas(
 7738                                        move |bounds, window, cx| {
 7739                                            this.update(cx, |this, cx| {
 7740                                                let bounds_changed = this.bounds != bounds;
 7741                                                this.bounds = bounds;
 7742
 7743                                                if bounds_changed {
 7744                                                    this.left_dock.update(cx, |dock, cx| {
 7745                                                        dock.clamp_panel_size(
 7746                                                            bounds.size.width,
 7747                                                            window,
 7748                                                            cx,
 7749                                                        )
 7750                                                    });
 7751
 7752                                                    this.right_dock.update(cx, |dock, cx| {
 7753                                                        dock.clamp_panel_size(
 7754                                                            bounds.size.width,
 7755                                                            window,
 7756                                                            cx,
 7757                                                        )
 7758                                                    });
 7759
 7760                                                    this.bottom_dock.update(cx, |dock, cx| {
 7761                                                        dock.clamp_panel_size(
 7762                                                            bounds.size.height,
 7763                                                            window,
 7764                                                            cx,
 7765                                                        )
 7766                                                    });
 7767                                                }
 7768                                            })
 7769                                        },
 7770                                        |_, _, _, _| {},
 7771                                    )
 7772                                    .absolute()
 7773                                    .size_full()
 7774                                })
 7775                                .when(self.zoomed.is_none(), |this| {
 7776                                    this.on_drag_move(cx.listener(
 7777                                        move |workspace,
 7778                                              e: &DragMoveEvent<DraggedDock>,
 7779                                              window,
 7780                                              cx| {
 7781                                            if workspace.previous_dock_drag_coordinates
 7782                                                != Some(e.event.position)
 7783                                            {
 7784                                                workspace.previous_dock_drag_coordinates =
 7785                                                    Some(e.event.position);
 7786
 7787                                                match e.drag(cx).0 {
 7788                                                    DockPosition::Left => {
 7789                                                        workspace.resize_left_dock(
 7790                                                            e.event.position.x
 7791                                                                - workspace.bounds.left(),
 7792                                                            window,
 7793                                                            cx,
 7794                                                        );
 7795                                                    }
 7796                                                    DockPosition::Right => {
 7797                                                        workspace.resize_right_dock(
 7798                                                            workspace.bounds.right()
 7799                                                                - e.event.position.x,
 7800                                                            window,
 7801                                                            cx,
 7802                                                        );
 7803                                                    }
 7804                                                    DockPosition::Bottom => {
 7805                                                        workspace.resize_bottom_dock(
 7806                                                            workspace.bounds.bottom()
 7807                                                                - e.event.position.y,
 7808                                                            window,
 7809                                                            cx,
 7810                                                        );
 7811                                                    }
 7812                                                };
 7813                                                workspace.serialize_workspace(window, cx);
 7814                                            }
 7815                                        },
 7816                                    ))
 7817
 7818                                })
 7819                                .child({
 7820                                    match bottom_dock_layout {
 7821                                        BottomDockLayout::Full => div()
 7822                                            .flex()
 7823                                            .flex_col()
 7824                                            .h_full()
 7825                                            .child(
 7826                                                div()
 7827                                                    .flex()
 7828                                                    .flex_row()
 7829                                                    .flex_1()
 7830                                                    .overflow_hidden()
 7831                                                    .children(self.render_dock(
 7832                                                        DockPosition::Left,
 7833                                                        &self.left_dock,
 7834                                                        window,
 7835                                                        cx,
 7836                                                    ))
 7837
 7838                                                    .child(
 7839                                                        div()
 7840                                                            .flex()
 7841                                                            .flex_col()
 7842                                                            .flex_1()
 7843                                                            .overflow_hidden()
 7844                                                            .child(
 7845                                                                h_flex()
 7846                                                                    .flex_1()
 7847                                                                    .when_some(
 7848                                                                        paddings.0,
 7849                                                                        |this, p| {
 7850                                                                            this.child(
 7851                                                                                p.border_r_1(),
 7852                                                                            )
 7853                                                                        },
 7854                                                                    )
 7855                                                                    .child(self.center.render(
 7856                                                                        self.zoomed.as_ref(),
 7857                                                                        &PaneRenderContext {
 7858                                                                            follower_states:
 7859                                                                                &self.follower_states,
 7860                                                                            active_call: self.active_call(),
 7861                                                                            active_pane: &self.active_pane,
 7862                                                                            app_state: &self.app_state,
 7863                                                                            project: &self.project,
 7864                                                                            workspace: &self.weak_self,
 7865                                                                        },
 7866                                                                        window,
 7867                                                                        cx,
 7868                                                                    ))
 7869                                                                    .when_some(
 7870                                                                        paddings.1,
 7871                                                                        |this, p| {
 7872                                                                            this.child(
 7873                                                                                p.border_l_1(),
 7874                                                                            )
 7875                                                                        },
 7876                                                                    ),
 7877                                                            ),
 7878                                                    )
 7879
 7880                                                    .children(self.render_dock(
 7881                                                        DockPosition::Right,
 7882                                                        &self.right_dock,
 7883                                                        window,
 7884                                                        cx,
 7885                                                    )),
 7886                                            )
 7887                                            .child(div().w_full().children(self.render_dock(
 7888                                                DockPosition::Bottom,
 7889                                                &self.bottom_dock,
 7890                                                window,
 7891                                                cx
 7892                                            ))),
 7893
 7894                                        BottomDockLayout::LeftAligned => div()
 7895                                            .flex()
 7896                                            .flex_row()
 7897                                            .h_full()
 7898                                            .child(
 7899                                                div()
 7900                                                    .flex()
 7901                                                    .flex_col()
 7902                                                    .flex_1()
 7903                                                    .h_full()
 7904                                                    .child(
 7905                                                        div()
 7906                                                            .flex()
 7907                                                            .flex_row()
 7908                                                            .flex_1()
 7909                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 7910
 7911                                                            .child(
 7912                                                                div()
 7913                                                                    .flex()
 7914                                                                    .flex_col()
 7915                                                                    .flex_1()
 7916                                                                    .overflow_hidden()
 7917                                                                    .child(
 7918                                                                        h_flex()
 7919                                                                            .flex_1()
 7920                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7921                                                                            .child(self.center.render(
 7922                                                                                self.zoomed.as_ref(),
 7923                                                                                &PaneRenderContext {
 7924                                                                                    follower_states:
 7925                                                                                        &self.follower_states,
 7926                                                                                    active_call: self.active_call(),
 7927                                                                                    active_pane: &self.active_pane,
 7928                                                                                    app_state: &self.app_state,
 7929                                                                                    project: &self.project,
 7930                                                                                    workspace: &self.weak_self,
 7931                                                                                },
 7932                                                                                window,
 7933                                                                                cx,
 7934                                                                            ))
 7935                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7936                                                                    )
 7937                                                            )
 7938
 7939                                                    )
 7940                                                    .child(
 7941                                                        div()
 7942                                                            .w_full()
 7943                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7944                                                    ),
 7945                                            )
 7946                                            .children(self.render_dock(
 7947                                                DockPosition::Right,
 7948                                                &self.right_dock,
 7949                                                window,
 7950                                                cx,
 7951                                            )),
 7952                                        BottomDockLayout::RightAligned => div()
 7953                                            .flex()
 7954                                            .flex_row()
 7955                                            .h_full()
 7956                                            .children(self.render_dock(
 7957                                                DockPosition::Left,
 7958                                                &self.left_dock,
 7959                                                window,
 7960                                                cx,
 7961                                            ))
 7962
 7963                                            .child(
 7964                                                div()
 7965                                                    .flex()
 7966                                                    .flex_col()
 7967                                                    .flex_1()
 7968                                                    .h_full()
 7969                                                    .child(
 7970                                                        div()
 7971                                                            .flex()
 7972                                                            .flex_row()
 7973                                                            .flex_1()
 7974                                                            .child(
 7975                                                                div()
 7976                                                                    .flex()
 7977                                                                    .flex_col()
 7978                                                                    .flex_1()
 7979                                                                    .overflow_hidden()
 7980                                                                    .child(
 7981                                                                        h_flex()
 7982                                                                            .flex_1()
 7983                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7984                                                                            .child(self.center.render(
 7985                                                                                self.zoomed.as_ref(),
 7986                                                                                &PaneRenderContext {
 7987                                                                                    follower_states:
 7988                                                                                        &self.follower_states,
 7989                                                                                    active_call: self.active_call(),
 7990                                                                                    active_pane: &self.active_pane,
 7991                                                                                    app_state: &self.app_state,
 7992                                                                                    project: &self.project,
 7993                                                                                    workspace: &self.weak_self,
 7994                                                                                },
 7995                                                                                window,
 7996                                                                                cx,
 7997                                                                            ))
 7998                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7999                                                                    )
 8000                                                            )
 8001
 8002                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 8003                                                    )
 8004                                                    .child(
 8005                                                        div()
 8006                                                            .w_full()
 8007                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8008                                                    ),
 8009                                            ),
 8010                                        BottomDockLayout::Contained => div()
 8011                                            .flex()
 8012                                            .flex_row()
 8013                                            .h_full()
 8014                                            .children(self.render_dock(
 8015                                                DockPosition::Left,
 8016                                                &self.left_dock,
 8017                                                window,
 8018                                                cx,
 8019                                            ))
 8020
 8021                                            .child(
 8022                                                div()
 8023                                                    .flex()
 8024                                                    .flex_col()
 8025                                                    .flex_1()
 8026                                                    .overflow_hidden()
 8027                                                    .child(
 8028                                                        h_flex()
 8029                                                            .flex_1()
 8030                                                            .when_some(paddings.0, |this, p| {
 8031                                                                this.child(p.border_r_1())
 8032                                                            })
 8033                                                            .child(self.center.render(
 8034                                                                self.zoomed.as_ref(),
 8035                                                                &PaneRenderContext {
 8036                                                                    follower_states:
 8037                                                                        &self.follower_states,
 8038                                                                    active_call: self.active_call(),
 8039                                                                    active_pane: &self.active_pane,
 8040                                                                    app_state: &self.app_state,
 8041                                                                    project: &self.project,
 8042                                                                    workspace: &self.weak_self,
 8043                                                                },
 8044                                                                window,
 8045                                                                cx,
 8046                                                            ))
 8047                                                            .when_some(paddings.1, |this, p| {
 8048                                                                this.child(p.border_l_1())
 8049                                                            }),
 8050                                                    )
 8051                                                    .children(self.render_dock(
 8052                                                        DockPosition::Bottom,
 8053                                                        &self.bottom_dock,
 8054                                                        window,
 8055                                                        cx,
 8056                                                    )),
 8057                                            )
 8058
 8059                                            .children(self.render_dock(
 8060                                                DockPosition::Right,
 8061                                                &self.right_dock,
 8062                                                window,
 8063                                                cx,
 8064                                            )),
 8065                                    }
 8066                                })
 8067                                .children(self.zoomed.as_ref().and_then(|view| {
 8068                                    let zoomed_view = view.upgrade()?;
 8069                                    let div = div()
 8070                                        .occlude()
 8071                                        .absolute()
 8072                                        .overflow_hidden()
 8073                                        .border_color(colors.border)
 8074                                        .bg(colors.background)
 8075                                        .child(zoomed_view)
 8076                                        .inset_0()
 8077                                        .shadow_lg();
 8078
 8079                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8080                                       return Some(div);
 8081                                    }
 8082
 8083                                    Some(match self.zoomed_position {
 8084                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8085                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8086                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8087                                        None => {
 8088                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8089                                        }
 8090                                    })
 8091                                }))
 8092                                .children(self.render_notifications(window, cx)),
 8093                        )
 8094                        .when(self.status_bar_visible(cx), |parent| {
 8095                            parent.child(self.status_bar.clone())
 8096                        })
 8097                        .child(self.toast_layer.clone()),
 8098                )
 8099    }
 8100}
 8101
 8102impl WorkspaceStore {
 8103    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8104        Self {
 8105            workspaces: Default::default(),
 8106            _subscriptions: vec![
 8107                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8108                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8109            ],
 8110            client,
 8111        }
 8112    }
 8113
 8114    pub fn update_followers(
 8115        &self,
 8116        project_id: Option<u64>,
 8117        update: proto::update_followers::Variant,
 8118        cx: &App,
 8119    ) -> Option<()> {
 8120        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8121        let room_id = active_call.0.room_id(cx)?;
 8122        self.client
 8123            .send(proto::UpdateFollowers {
 8124                room_id,
 8125                project_id,
 8126                variant: Some(update),
 8127            })
 8128            .log_err()
 8129    }
 8130
 8131    pub async fn handle_follow(
 8132        this: Entity<Self>,
 8133        envelope: TypedEnvelope<proto::Follow>,
 8134        mut cx: AsyncApp,
 8135    ) -> Result<proto::FollowResponse> {
 8136        this.update(&mut cx, |this, cx| {
 8137            let follower = Follower {
 8138                project_id: envelope.payload.project_id,
 8139                peer_id: envelope.original_sender_id()?,
 8140            };
 8141
 8142            let mut response = proto::FollowResponse::default();
 8143
 8144            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8145                let Some(workspace) = weak_workspace.upgrade() else {
 8146                    return false;
 8147                };
 8148                window_handle
 8149                    .update(cx, |_, window, cx| {
 8150                        workspace.update(cx, |workspace, cx| {
 8151                            let handler_response =
 8152                                workspace.handle_follow(follower.project_id, window, cx);
 8153                            if let Some(active_view) = handler_response.active_view
 8154                                && workspace.project.read(cx).remote_id() == follower.project_id
 8155                            {
 8156                                response.active_view = Some(active_view)
 8157                            }
 8158                        });
 8159                    })
 8160                    .is_ok()
 8161            });
 8162
 8163            Ok(response)
 8164        })
 8165    }
 8166
 8167    async fn handle_update_followers(
 8168        this: Entity<Self>,
 8169        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8170        mut cx: AsyncApp,
 8171    ) -> Result<()> {
 8172        let leader_id = envelope.original_sender_id()?;
 8173        let update = envelope.payload;
 8174
 8175        this.update(&mut cx, |this, cx| {
 8176            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8177                let Some(workspace) = weak_workspace.upgrade() else {
 8178                    return false;
 8179                };
 8180                window_handle
 8181                    .update(cx, |_, window, cx| {
 8182                        workspace.update(cx, |workspace, cx| {
 8183                            let project_id = workspace.project.read(cx).remote_id();
 8184                            if update.project_id != project_id && update.project_id.is_some() {
 8185                                return;
 8186                            }
 8187                            workspace.handle_update_followers(
 8188                                leader_id,
 8189                                update.clone(),
 8190                                window,
 8191                                cx,
 8192                            );
 8193                        });
 8194                    })
 8195                    .is_ok()
 8196            });
 8197            Ok(())
 8198        })
 8199    }
 8200
 8201    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8202        self.workspaces.iter().map(|(_, weak)| weak)
 8203    }
 8204
 8205    pub fn workspaces_with_windows(
 8206        &self,
 8207    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8208        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8209    }
 8210}
 8211
 8212impl ViewId {
 8213    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8214        Ok(Self {
 8215            creator: message
 8216                .creator
 8217                .map(CollaboratorId::PeerId)
 8218                .context("creator is missing")?,
 8219            id: message.id,
 8220        })
 8221    }
 8222
 8223    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8224        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8225            Some(proto::ViewId {
 8226                creator: Some(peer_id),
 8227                id: self.id,
 8228            })
 8229        } else {
 8230            None
 8231        }
 8232    }
 8233}
 8234
 8235impl FollowerState {
 8236    fn pane(&self) -> &Entity<Pane> {
 8237        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8238    }
 8239}
 8240
 8241pub trait WorkspaceHandle {
 8242    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8243}
 8244
 8245impl WorkspaceHandle for Entity<Workspace> {
 8246    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8247        self.read(cx)
 8248            .worktrees(cx)
 8249            .flat_map(|worktree| {
 8250                let worktree_id = worktree.read(cx).id();
 8251                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8252                    worktree_id,
 8253                    path: f.path.clone(),
 8254                })
 8255            })
 8256            .collect::<Vec<_>>()
 8257    }
 8258}
 8259
 8260pub async fn last_opened_workspace_location(
 8261    db: &WorkspaceDb,
 8262    fs: &dyn fs::Fs,
 8263) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8264    db.last_workspace(fs)
 8265        .await
 8266        .log_err()
 8267        .flatten()
 8268        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8269}
 8270
 8271pub async fn last_session_workspace_locations(
 8272    db: &WorkspaceDb,
 8273    last_session_id: &str,
 8274    last_session_window_stack: Option<Vec<WindowId>>,
 8275    fs: &dyn fs::Fs,
 8276) -> Option<Vec<SessionWorkspace>> {
 8277    db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8278        .await
 8279        .log_err()
 8280}
 8281
 8282pub struct MultiWorkspaceRestoreResult {
 8283    pub window_handle: WindowHandle<MultiWorkspace>,
 8284    pub errors: Vec<anyhow::Error>,
 8285}
 8286
 8287pub async fn restore_multiworkspace(
 8288    multi_workspace: SerializedMultiWorkspace,
 8289    app_state: Arc<AppState>,
 8290    cx: &mut AsyncApp,
 8291) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8292    let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
 8293    let mut group_iter = workspaces.into_iter();
 8294    let first = group_iter
 8295        .next()
 8296        .context("window group must not be empty")?;
 8297
 8298    let window_handle = if first.paths.is_empty() {
 8299        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8300            .await?
 8301    } else {
 8302        let OpenResult { window, .. } = cx
 8303            .update(|cx| {
 8304                Workspace::new_local(
 8305                    first.paths.paths().to_vec(),
 8306                    app_state.clone(),
 8307                    None,
 8308                    None,
 8309                    None,
 8310                    true,
 8311                    cx,
 8312                )
 8313            })
 8314            .await?;
 8315        window
 8316    };
 8317
 8318    let mut errors = Vec::new();
 8319
 8320    for session_workspace in group_iter {
 8321        let error = if session_workspace.paths.is_empty() {
 8322            cx.update(|cx| {
 8323                open_workspace_by_id(
 8324                    session_workspace.workspace_id,
 8325                    app_state.clone(),
 8326                    Some(window_handle),
 8327                    cx,
 8328                )
 8329            })
 8330            .await
 8331            .err()
 8332        } else {
 8333            cx.update(|cx| {
 8334                Workspace::new_local(
 8335                    session_workspace.paths.paths().to_vec(),
 8336                    app_state.clone(),
 8337                    Some(window_handle),
 8338                    None,
 8339                    None,
 8340                    false,
 8341                    cx,
 8342                )
 8343            })
 8344            .await
 8345            .err()
 8346        };
 8347
 8348        if let Some(error) = error {
 8349            errors.push(error);
 8350        }
 8351    }
 8352
 8353    if let Some(target_id) = state.active_workspace_id {
 8354        window_handle
 8355            .update(cx, |multi_workspace, window, cx| {
 8356                let target_index = multi_workspace
 8357                    .workspaces()
 8358                    .iter()
 8359                    .position(|ws| ws.read(cx).database_id() == Some(target_id));
 8360                if let Some(index) = target_index {
 8361                    multi_workspace.activate_index(index, window, cx);
 8362                } else if !multi_workspace.workspaces().is_empty() {
 8363                    multi_workspace.activate_index(0, window, cx);
 8364                }
 8365            })
 8366            .ok();
 8367    } else {
 8368        window_handle
 8369            .update(cx, |multi_workspace, window, cx| {
 8370                if !multi_workspace.workspaces().is_empty() {
 8371                    multi_workspace.activate_index(0, window, cx);
 8372                }
 8373            })
 8374            .ok();
 8375    }
 8376
 8377    if state.sidebar_open {
 8378        window_handle
 8379            .update(cx, |multi_workspace, _, cx| {
 8380                multi_workspace.open_sidebar(cx);
 8381            })
 8382            .ok();
 8383    }
 8384
 8385    window_handle
 8386        .update(cx, |_, window, _cx| {
 8387            window.activate_window();
 8388        })
 8389        .ok();
 8390
 8391    Ok(MultiWorkspaceRestoreResult {
 8392        window_handle,
 8393        errors,
 8394    })
 8395}
 8396
 8397actions!(
 8398    collab,
 8399    [
 8400        /// Opens the channel notes for the current call.
 8401        ///
 8402        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8403        /// channel in the collab panel.
 8404        ///
 8405        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8406        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8407        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8408        OpenChannelNotes,
 8409        /// Mutes your microphone.
 8410        Mute,
 8411        /// Deafens yourself (mute both microphone and speakers).
 8412        Deafen,
 8413        /// Leaves the current call.
 8414        LeaveCall,
 8415        /// Shares the current project with collaborators.
 8416        ShareProject,
 8417        /// Shares your screen with collaborators.
 8418        ScreenShare,
 8419        /// Copies the current room name and session id for debugging purposes.
 8420        CopyRoomId,
 8421    ]
 8422);
 8423
 8424/// Opens the channel notes for a specific channel by its ID.
 8425#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8426#[action(namespace = collab)]
 8427#[serde(deny_unknown_fields)]
 8428pub struct OpenChannelNotesById {
 8429    pub channel_id: u64,
 8430}
 8431
 8432actions!(
 8433    zed,
 8434    [
 8435        /// Opens the Zed log file.
 8436        OpenLog,
 8437        /// Reveals the Zed log file in the system file manager.
 8438        RevealLogInFileManager
 8439    ]
 8440);
 8441
 8442async fn join_channel_internal(
 8443    channel_id: ChannelId,
 8444    app_state: &Arc<AppState>,
 8445    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8446    requesting_workspace: Option<WeakEntity<Workspace>>,
 8447    active_call: &dyn AnyActiveCall,
 8448    cx: &mut AsyncApp,
 8449) -> Result<bool> {
 8450    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8451        if !active_call.is_in_room(cx) {
 8452            return (false, false);
 8453        }
 8454
 8455        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8456        let should_prompt = active_call.is_sharing_project(cx)
 8457            && active_call.has_remote_participants(cx)
 8458            && !already_in_channel;
 8459        (should_prompt, already_in_channel)
 8460    });
 8461
 8462    if already_in_channel {
 8463        let task = cx.update(|cx| {
 8464            if let Some((project, host)) = active_call.most_active_project(cx) {
 8465                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8466            } else {
 8467                None
 8468            }
 8469        });
 8470        if let Some(task) = task {
 8471            task.await?;
 8472        }
 8473        return anyhow::Ok(true);
 8474    }
 8475
 8476    if should_prompt {
 8477        if let Some(multi_workspace) = requesting_window {
 8478            let answer = multi_workspace
 8479                .update(cx, |_, window, cx| {
 8480                    window.prompt(
 8481                        PromptLevel::Warning,
 8482                        "Do you want to switch channels?",
 8483                        Some("Leaving this call will unshare your current project."),
 8484                        &["Yes, Join Channel", "Cancel"],
 8485                        cx,
 8486                    )
 8487                })?
 8488                .await;
 8489
 8490            if answer == Ok(1) {
 8491                return Ok(false);
 8492            }
 8493        } else {
 8494            return Ok(false);
 8495        }
 8496    }
 8497
 8498    let client = cx.update(|cx| active_call.client(cx));
 8499
 8500    let mut client_status = client.status();
 8501
 8502    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8503    'outer: loop {
 8504        let Some(status) = client_status.recv().await else {
 8505            anyhow::bail!("error connecting");
 8506        };
 8507
 8508        match status {
 8509            Status::Connecting
 8510            | Status::Authenticating
 8511            | Status::Authenticated
 8512            | Status::Reconnecting
 8513            | Status::Reauthenticating
 8514            | Status::Reauthenticated => continue,
 8515            Status::Connected { .. } => break 'outer,
 8516            Status::SignedOut | Status::AuthenticationError => {
 8517                return Err(ErrorCode::SignedOut.into());
 8518            }
 8519            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8520            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8521                return Err(ErrorCode::Disconnected.into());
 8522            }
 8523        }
 8524    }
 8525
 8526    let joined = cx
 8527        .update(|cx| active_call.join_channel(channel_id, cx))
 8528        .await?;
 8529
 8530    if !joined {
 8531        return anyhow::Ok(true);
 8532    }
 8533
 8534    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8535
 8536    let task = cx.update(|cx| {
 8537        if let Some((project, host)) = active_call.most_active_project(cx) {
 8538            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8539        }
 8540
 8541        // If you are the first to join a channel, see if you should share your project.
 8542        if !active_call.has_remote_participants(cx)
 8543            && !active_call.local_participant_is_guest(cx)
 8544            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8545        {
 8546            let project = workspace.update(cx, |workspace, cx| {
 8547                let project = workspace.project.read(cx);
 8548
 8549                if !active_call.share_on_join(cx) {
 8550                    return None;
 8551                }
 8552
 8553                if (project.is_local() || project.is_via_remote_server())
 8554                    && project.visible_worktrees(cx).any(|tree| {
 8555                        tree.read(cx)
 8556                            .root_entry()
 8557                            .is_some_and(|entry| entry.is_dir())
 8558                    })
 8559                {
 8560                    Some(workspace.project.clone())
 8561                } else {
 8562                    None
 8563                }
 8564            });
 8565            if let Some(project) = project {
 8566                let share_task = active_call.share_project(project, cx);
 8567                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8568                    share_task.await?;
 8569                    Ok(())
 8570                }));
 8571            }
 8572        }
 8573
 8574        None
 8575    });
 8576    if let Some(task) = task {
 8577        task.await?;
 8578        return anyhow::Ok(true);
 8579    }
 8580    anyhow::Ok(false)
 8581}
 8582
 8583pub fn join_channel(
 8584    channel_id: ChannelId,
 8585    app_state: Arc<AppState>,
 8586    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8587    requesting_workspace: Option<WeakEntity<Workspace>>,
 8588    cx: &mut App,
 8589) -> Task<Result<()>> {
 8590    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8591    cx.spawn(async move |cx| {
 8592        let result = join_channel_internal(
 8593            channel_id,
 8594            &app_state,
 8595            requesting_window,
 8596            requesting_workspace,
 8597            &*active_call.0,
 8598            cx,
 8599        )
 8600        .await;
 8601
 8602        // join channel succeeded, and opened a window
 8603        if matches!(result, Ok(true)) {
 8604            return anyhow::Ok(());
 8605        }
 8606
 8607        // find an existing workspace to focus and show call controls
 8608        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8609        if active_window.is_none() {
 8610            // no open workspaces, make one to show the error in (blergh)
 8611            let OpenResult {
 8612                window: window_handle,
 8613                ..
 8614            } = cx
 8615                .update(|cx| {
 8616                    Workspace::new_local(
 8617                        vec![],
 8618                        app_state.clone(),
 8619                        requesting_window,
 8620                        None,
 8621                        None,
 8622                        true,
 8623                        cx,
 8624                    )
 8625                })
 8626                .await?;
 8627
 8628            window_handle
 8629                .update(cx, |_, window, _cx| {
 8630                    window.activate_window();
 8631                })
 8632                .ok();
 8633
 8634            if result.is_ok() {
 8635                cx.update(|cx| {
 8636                    cx.dispatch_action(&OpenChannelNotes);
 8637                });
 8638            }
 8639
 8640            active_window = Some(window_handle);
 8641        }
 8642
 8643        if let Err(err) = result {
 8644            log::error!("failed to join channel: {}", err);
 8645            if let Some(active_window) = active_window {
 8646                active_window
 8647                    .update(cx, |_, window, cx| {
 8648                        let detail: SharedString = match err.error_code() {
 8649                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 8650                            ErrorCode::UpgradeRequired => concat!(
 8651                                "Your are running an unsupported version of Zed. ",
 8652                                "Please update to continue."
 8653                            )
 8654                            .into(),
 8655                            ErrorCode::NoSuchChannel => concat!(
 8656                                "No matching channel was found. ",
 8657                                "Please check the link and try again."
 8658                            )
 8659                            .into(),
 8660                            ErrorCode::Forbidden => concat!(
 8661                                "This channel is private, and you do not have access. ",
 8662                                "Please ask someone to add you and try again."
 8663                            )
 8664                            .into(),
 8665                            ErrorCode::Disconnected => {
 8666                                "Please check your internet connection and try again.".into()
 8667                            }
 8668                            _ => format!("{}\n\nPlease try again.", err).into(),
 8669                        };
 8670                        window.prompt(
 8671                            PromptLevel::Critical,
 8672                            "Failed to join channel",
 8673                            Some(&detail),
 8674                            &["Ok"],
 8675                            cx,
 8676                        )
 8677                    })?
 8678                    .await
 8679                    .ok();
 8680            }
 8681        }
 8682
 8683        // return ok, we showed the error to the user.
 8684        anyhow::Ok(())
 8685    })
 8686}
 8687
 8688pub async fn get_any_active_multi_workspace(
 8689    app_state: Arc<AppState>,
 8690    mut cx: AsyncApp,
 8691) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8692    // find an existing workspace to focus and show call controls
 8693    let active_window = activate_any_workspace_window(&mut cx);
 8694    if active_window.is_none() {
 8695        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
 8696            .await?;
 8697    }
 8698    activate_any_workspace_window(&mut cx).context("could not open zed")
 8699}
 8700
 8701fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 8702    cx.update(|cx| {
 8703        if let Some(workspace_window) = cx
 8704            .active_window()
 8705            .and_then(|window| window.downcast::<MultiWorkspace>())
 8706        {
 8707            return Some(workspace_window);
 8708        }
 8709
 8710        for window in cx.windows() {
 8711            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 8712                workspace_window
 8713                    .update(cx, |_, window, _| window.activate_window())
 8714                    .ok();
 8715                return Some(workspace_window);
 8716            }
 8717        }
 8718        None
 8719    })
 8720}
 8721
 8722pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 8723    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 8724}
 8725
 8726pub fn workspace_windows_for_location(
 8727    serialized_location: &SerializedWorkspaceLocation,
 8728    cx: &App,
 8729) -> Vec<WindowHandle<MultiWorkspace>> {
 8730    cx.windows()
 8731        .into_iter()
 8732        .filter_map(|window| window.downcast::<MultiWorkspace>())
 8733        .filter(|multi_workspace| {
 8734            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 8735                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 8736                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 8737                }
 8738                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 8739                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 8740                    a.distro_name == b.distro_name
 8741                }
 8742                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 8743                    a.container_id == b.container_id
 8744                }
 8745                #[cfg(any(test, feature = "test-support"))]
 8746                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 8747                    a.id == b.id
 8748                }
 8749                _ => false,
 8750            };
 8751
 8752            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 8753                multi_workspace.workspaces().iter().any(|workspace| {
 8754                    match workspace.read(cx).workspace_location(cx) {
 8755                        WorkspaceLocation::Location(location, _) => {
 8756                            match (&location, serialized_location) {
 8757                                (
 8758                                    SerializedWorkspaceLocation::Local,
 8759                                    SerializedWorkspaceLocation::Local,
 8760                                ) => true,
 8761                                (
 8762                                    SerializedWorkspaceLocation::Remote(a),
 8763                                    SerializedWorkspaceLocation::Remote(b),
 8764                                ) => same_host(a, b),
 8765                                _ => false,
 8766                            }
 8767                        }
 8768                        _ => false,
 8769                    }
 8770                })
 8771            })
 8772        })
 8773        .collect()
 8774}
 8775
 8776pub async fn find_existing_workspace(
 8777    abs_paths: &[PathBuf],
 8778    open_options: &OpenOptions,
 8779    location: &SerializedWorkspaceLocation,
 8780    cx: &mut AsyncApp,
 8781) -> (
 8782    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 8783    OpenVisible,
 8784) {
 8785    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 8786    let mut open_visible = OpenVisible::All;
 8787    let mut best_match = None;
 8788
 8789    if open_options.open_new_workspace != Some(true) {
 8790        cx.update(|cx| {
 8791            for window in workspace_windows_for_location(location, cx) {
 8792                if let Ok(multi_workspace) = window.read(cx) {
 8793                    for workspace in multi_workspace.workspaces() {
 8794                        let project = workspace.read(cx).project.read(cx);
 8795                        let m = project.visibility_for_paths(
 8796                            abs_paths,
 8797                            open_options.open_new_workspace == None,
 8798                            cx,
 8799                        );
 8800                        if m > best_match {
 8801                            existing = Some((window, workspace.clone()));
 8802                            best_match = m;
 8803                        } else if best_match.is_none()
 8804                            && open_options.open_new_workspace == Some(false)
 8805                        {
 8806                            existing = Some((window, workspace.clone()))
 8807                        }
 8808                    }
 8809                }
 8810            }
 8811        });
 8812
 8813        let all_paths_are_files = existing
 8814            .as_ref()
 8815            .and_then(|(_, target_workspace)| {
 8816                cx.update(|cx| {
 8817                    let workspace = target_workspace.read(cx);
 8818                    let project = workspace.project.read(cx);
 8819                    let path_style = workspace.path_style(cx);
 8820                    Some(!abs_paths.iter().any(|path| {
 8821                        let path = util::paths::SanitizedPath::new(path);
 8822                        project.worktrees(cx).any(|worktree| {
 8823                            let worktree = worktree.read(cx);
 8824                            let abs_path = worktree.abs_path();
 8825                            path_style
 8826                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 8827                                .and_then(|rel| worktree.entry_for_path(&rel))
 8828                                .is_some_and(|e| e.is_dir())
 8829                        })
 8830                    }))
 8831                })
 8832            })
 8833            .unwrap_or(false);
 8834
 8835        if open_options.open_new_workspace.is_none()
 8836            && existing.is_some()
 8837            && open_options.wait
 8838            && all_paths_are_files
 8839        {
 8840            cx.update(|cx| {
 8841                let windows = workspace_windows_for_location(location, cx);
 8842                let window = cx
 8843                    .active_window()
 8844                    .and_then(|window| window.downcast::<MultiWorkspace>())
 8845                    .filter(|window| windows.contains(window))
 8846                    .or_else(|| windows.into_iter().next());
 8847                if let Some(window) = window {
 8848                    if let Ok(multi_workspace) = window.read(cx) {
 8849                        let active_workspace = multi_workspace.workspace().clone();
 8850                        existing = Some((window, active_workspace));
 8851                        open_visible = OpenVisible::None;
 8852                    }
 8853                }
 8854            });
 8855        }
 8856    }
 8857    (existing, open_visible)
 8858}
 8859
 8860#[derive(Default, Clone)]
 8861pub struct OpenOptions {
 8862    pub visible: Option<OpenVisible>,
 8863    pub focus: Option<bool>,
 8864    pub open_new_workspace: Option<bool>,
 8865    pub wait: bool,
 8866    pub replace_window: Option<WindowHandle<MultiWorkspace>>,
 8867    pub env: Option<HashMap<String, String>>,
 8868}
 8869
 8870/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 8871/// or [`Workspace::open_workspace_for_paths`].
 8872pub struct OpenResult {
 8873    pub window: WindowHandle<MultiWorkspace>,
 8874    pub workspace: Entity<Workspace>,
 8875    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 8876}
 8877
 8878/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 8879pub fn open_workspace_by_id(
 8880    workspace_id: WorkspaceId,
 8881    app_state: Arc<AppState>,
 8882    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8883    cx: &mut App,
 8884) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 8885    let project_handle = Project::local(
 8886        app_state.client.clone(),
 8887        app_state.node_runtime.clone(),
 8888        app_state.user_store.clone(),
 8889        app_state.languages.clone(),
 8890        app_state.fs.clone(),
 8891        None,
 8892        project::LocalProjectFlags {
 8893            init_worktree_trust: true,
 8894            ..project::LocalProjectFlags::default()
 8895        },
 8896        cx,
 8897    );
 8898
 8899    let db = WorkspaceDb::global(cx);
 8900    let kvp = db::kvp::KeyValueStore::global(cx);
 8901    cx.spawn(async move |cx| {
 8902        let serialized_workspace = db
 8903            .workspace_for_id(workspace_id)
 8904            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 8905
 8906        let centered_layout = serialized_workspace.centered_layout;
 8907
 8908        let (window, workspace) = if let Some(window) = requesting_window {
 8909            let workspace = window.update(cx, |multi_workspace, window, cx| {
 8910                let workspace = cx.new(|cx| {
 8911                    let mut workspace = Workspace::new(
 8912                        Some(workspace_id),
 8913                        project_handle.clone(),
 8914                        app_state.clone(),
 8915                        window,
 8916                        cx,
 8917                    );
 8918                    workspace.centered_layout = centered_layout;
 8919                    workspace
 8920                });
 8921                multi_workspace.add_workspace(workspace.clone(), cx);
 8922                workspace
 8923            })?;
 8924            (window, workspace)
 8925        } else {
 8926            let window_bounds_override = window_bounds_env_override();
 8927
 8928            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 8929                (Some(WindowBounds::Windowed(bounds)), None)
 8930            } else if let Some(display) = serialized_workspace.display
 8931                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 8932            {
 8933                (Some(bounds.0), Some(display))
 8934            } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
 8935                (Some(bounds), Some(display))
 8936            } else {
 8937                (None, None)
 8938            };
 8939
 8940            let options = cx.update(|cx| {
 8941                let mut options = (app_state.build_window_options)(display, cx);
 8942                options.window_bounds = window_bounds;
 8943                options
 8944            });
 8945
 8946            let window = cx.open_window(options, {
 8947                let app_state = app_state.clone();
 8948                let project_handle = project_handle.clone();
 8949                move |window, cx| {
 8950                    let workspace = cx.new(|cx| {
 8951                        let mut workspace = Workspace::new(
 8952                            Some(workspace_id),
 8953                            project_handle,
 8954                            app_state,
 8955                            window,
 8956                            cx,
 8957                        );
 8958                        workspace.centered_layout = centered_layout;
 8959                        workspace
 8960                    });
 8961                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 8962                }
 8963            })?;
 8964
 8965            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 8966                multi_workspace.workspace().clone()
 8967            })?;
 8968
 8969            (window, workspace)
 8970        };
 8971
 8972        notify_if_database_failed(window, cx);
 8973
 8974        // Restore items from the serialized workspace
 8975        window
 8976            .update(cx, |_, window, cx| {
 8977                workspace.update(cx, |_workspace, cx| {
 8978                    open_items(Some(serialized_workspace), vec![], window, cx)
 8979                })
 8980            })?
 8981            .await?;
 8982
 8983        window.update(cx, |_, window, cx| {
 8984            workspace.update(cx, |workspace, cx| {
 8985                workspace.serialize_workspace(window, cx);
 8986            });
 8987        })?;
 8988
 8989        Ok(window)
 8990    })
 8991}
 8992
 8993#[allow(clippy::type_complexity)]
 8994pub fn open_paths(
 8995    abs_paths: &[PathBuf],
 8996    app_state: Arc<AppState>,
 8997    open_options: OpenOptions,
 8998    cx: &mut App,
 8999) -> Task<anyhow::Result<OpenResult>> {
 9000    let abs_paths = abs_paths.to_vec();
 9001    #[cfg(target_os = "windows")]
 9002    let wsl_path = abs_paths
 9003        .iter()
 9004        .find_map(|p| util::paths::WslPath::from_path(p));
 9005
 9006    cx.spawn(async move |cx| {
 9007        let (mut existing, mut open_visible) = find_existing_workspace(
 9008            &abs_paths,
 9009            &open_options,
 9010            &SerializedWorkspaceLocation::Local,
 9011            cx,
 9012        )
 9013        .await;
 9014
 9015        // Fallback: if no workspace contains the paths and all paths are files,
 9016        // prefer an existing local workspace window (active window first).
 9017        if open_options.open_new_workspace.is_none() && existing.is_none() {
 9018            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 9019            let all_metadatas = futures::future::join_all(all_paths)
 9020                .await
 9021                .into_iter()
 9022                .filter_map(|result| result.ok().flatten())
 9023                .collect::<Vec<_>>();
 9024
 9025            if all_metadatas.iter().all(|file| !file.is_dir) {
 9026                cx.update(|cx| {
 9027                    let windows = workspace_windows_for_location(
 9028                        &SerializedWorkspaceLocation::Local,
 9029                        cx,
 9030                    );
 9031                    let window = cx
 9032                        .active_window()
 9033                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9034                        .filter(|window| windows.contains(window))
 9035                        .or_else(|| windows.into_iter().next());
 9036                    if let Some(window) = window {
 9037                        if let Ok(multi_workspace) = window.read(cx) {
 9038                            let active_workspace = multi_workspace.workspace().clone();
 9039                            existing = Some((window, active_workspace));
 9040                            open_visible = OpenVisible::None;
 9041                        }
 9042                    }
 9043                });
 9044            }
 9045        }
 9046
 9047        let result = if let Some((existing, target_workspace)) = existing {
 9048            let open_task = existing
 9049                .update(cx, |multi_workspace, window, cx| {
 9050                    window.activate_window();
 9051                    multi_workspace.activate(target_workspace.clone(), cx);
 9052                    target_workspace.update(cx, |workspace, cx| {
 9053                        workspace.open_paths(
 9054                            abs_paths,
 9055                            OpenOptions {
 9056                                visible: Some(open_visible),
 9057                                ..Default::default()
 9058                            },
 9059                            None,
 9060                            window,
 9061                            cx,
 9062                        )
 9063                    })
 9064                })?
 9065                .await;
 9066
 9067            _ = existing.update(cx, |multi_workspace, _, cx| {
 9068                let workspace = multi_workspace.workspace().clone();
 9069                workspace.update(cx, |workspace, cx| {
 9070                    for item in open_task.iter().flatten() {
 9071                        if let Err(e) = item {
 9072                            workspace.show_error(&e, cx);
 9073                        }
 9074                    }
 9075                });
 9076            });
 9077
 9078            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9079        } else {
 9080            let result = cx
 9081                .update(move |cx| {
 9082                    Workspace::new_local(
 9083                        abs_paths,
 9084                        app_state.clone(),
 9085                        open_options.replace_window,
 9086                        open_options.env,
 9087                        None,
 9088                        true,
 9089                        cx,
 9090                    )
 9091                })
 9092                .await;
 9093
 9094            if let Ok(ref result) = result {
 9095                result.window
 9096                    .update(cx, |_, window, _cx| {
 9097                        window.activate_window();
 9098                    })
 9099                    .log_err();
 9100            }
 9101
 9102            result
 9103        };
 9104
 9105        #[cfg(target_os = "windows")]
 9106        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9107            && let Ok(ref result) = result
 9108        {
 9109            result.window
 9110                .update(cx, move |multi_workspace, _window, cx| {
 9111                    struct OpenInWsl;
 9112                    let workspace = multi_workspace.workspace().clone();
 9113                    workspace.update(cx, |workspace, cx| {
 9114                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9115                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9116                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9117                            cx.new(move |cx| {
 9118                                MessageNotification::new(msg, cx)
 9119                                    .primary_message("Open in WSL")
 9120                                    .primary_icon(IconName::FolderOpen)
 9121                                    .primary_on_click(move |window, cx| {
 9122                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9123                                                distro: remote::WslConnectionOptions {
 9124                                                        distro_name: distro.clone(),
 9125                                                    user: None,
 9126                                                },
 9127                                                paths: vec![path.clone().into()],
 9128                                            }), cx)
 9129                                    })
 9130                            })
 9131                        });
 9132                    });
 9133                })
 9134                .unwrap();
 9135        };
 9136        result
 9137    })
 9138}
 9139
 9140pub fn open_new(
 9141    open_options: OpenOptions,
 9142    app_state: Arc<AppState>,
 9143    cx: &mut App,
 9144    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9145) -> Task<anyhow::Result<()>> {
 9146    let task = Workspace::new_local(
 9147        Vec::new(),
 9148        app_state,
 9149        open_options.replace_window,
 9150        open_options.env,
 9151        Some(Box::new(init)),
 9152        true,
 9153        cx,
 9154    );
 9155    cx.spawn(async move |cx| {
 9156        let OpenResult { window, .. } = task.await?;
 9157        window
 9158            .update(cx, |_, window, _cx| {
 9159                window.activate_window();
 9160            })
 9161            .ok();
 9162        Ok(())
 9163    })
 9164}
 9165
 9166pub fn create_and_open_local_file(
 9167    path: &'static Path,
 9168    window: &mut Window,
 9169    cx: &mut Context<Workspace>,
 9170    default_content: impl 'static + Send + FnOnce() -> Rope,
 9171) -> Task<Result<Box<dyn ItemHandle>>> {
 9172    cx.spawn_in(window, async move |workspace, cx| {
 9173        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9174        if !fs.is_file(path).await {
 9175            fs.create_file(path, Default::default()).await?;
 9176            fs.save(path, &default_content(), Default::default())
 9177                .await?;
 9178        }
 9179
 9180        workspace
 9181            .update_in(cx, |workspace, window, cx| {
 9182                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9183                    let path = workspace
 9184                        .project
 9185                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9186                    cx.spawn_in(window, async move |workspace, cx| {
 9187                        let path = path.await?;
 9188                        let mut items = workspace
 9189                            .update_in(cx, |workspace, window, cx| {
 9190                                workspace.open_paths(
 9191                                    vec![path.to_path_buf()],
 9192                                    OpenOptions {
 9193                                        visible: Some(OpenVisible::None),
 9194                                        ..Default::default()
 9195                                    },
 9196                                    None,
 9197                                    window,
 9198                                    cx,
 9199                                )
 9200                            })?
 9201                            .await;
 9202                        let item = items.pop().flatten();
 9203                        item.with_context(|| format!("path {path:?} is not a file"))?
 9204                    })
 9205                })
 9206            })?
 9207            .await?
 9208            .await
 9209    })
 9210}
 9211
 9212pub fn open_remote_project_with_new_connection(
 9213    window: WindowHandle<MultiWorkspace>,
 9214    remote_connection: Arc<dyn RemoteConnection>,
 9215    cancel_rx: oneshot::Receiver<()>,
 9216    delegate: Arc<dyn RemoteClientDelegate>,
 9217    app_state: Arc<AppState>,
 9218    paths: Vec<PathBuf>,
 9219    cx: &mut App,
 9220) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9221    cx.spawn(async move |cx| {
 9222        let (workspace_id, serialized_workspace) =
 9223            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9224                .await?;
 9225
 9226        let session = match cx
 9227            .update(|cx| {
 9228                remote::RemoteClient::new(
 9229                    ConnectionIdentifier::Workspace(workspace_id.0),
 9230                    remote_connection,
 9231                    cancel_rx,
 9232                    delegate,
 9233                    cx,
 9234                )
 9235            })
 9236            .await?
 9237        {
 9238            Some(result) => result,
 9239            None => return Ok(Vec::new()),
 9240        };
 9241
 9242        let project = cx.update(|cx| {
 9243            project::Project::remote(
 9244                session,
 9245                app_state.client.clone(),
 9246                app_state.node_runtime.clone(),
 9247                app_state.user_store.clone(),
 9248                app_state.languages.clone(),
 9249                app_state.fs.clone(),
 9250                true,
 9251                cx,
 9252            )
 9253        });
 9254
 9255        open_remote_project_inner(
 9256            project,
 9257            paths,
 9258            workspace_id,
 9259            serialized_workspace,
 9260            app_state,
 9261            window,
 9262            cx,
 9263        )
 9264        .await
 9265    })
 9266}
 9267
 9268pub fn open_remote_project_with_existing_connection(
 9269    connection_options: RemoteConnectionOptions,
 9270    project: Entity<Project>,
 9271    paths: Vec<PathBuf>,
 9272    app_state: Arc<AppState>,
 9273    window: WindowHandle<MultiWorkspace>,
 9274    cx: &mut AsyncApp,
 9275) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9276    cx.spawn(async move |cx| {
 9277        let (workspace_id, serialized_workspace) =
 9278            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9279
 9280        open_remote_project_inner(
 9281            project,
 9282            paths,
 9283            workspace_id,
 9284            serialized_workspace,
 9285            app_state,
 9286            window,
 9287            cx,
 9288        )
 9289        .await
 9290    })
 9291}
 9292
 9293async fn open_remote_project_inner(
 9294    project: Entity<Project>,
 9295    paths: Vec<PathBuf>,
 9296    workspace_id: WorkspaceId,
 9297    serialized_workspace: Option<SerializedWorkspace>,
 9298    app_state: Arc<AppState>,
 9299    window: WindowHandle<MultiWorkspace>,
 9300    cx: &mut AsyncApp,
 9301) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9302    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9303    let toolchains = db.toolchains(workspace_id).await?;
 9304    for (toolchain, worktree_path, path) in toolchains {
 9305        project
 9306            .update(cx, |this, cx| {
 9307                let Some(worktree_id) =
 9308                    this.find_worktree(&worktree_path, cx)
 9309                        .and_then(|(worktree, rel_path)| {
 9310                            if rel_path.is_empty() {
 9311                                Some(worktree.read(cx).id())
 9312                            } else {
 9313                                None
 9314                            }
 9315                        })
 9316                else {
 9317                    return Task::ready(None);
 9318                };
 9319
 9320                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9321            })
 9322            .await;
 9323    }
 9324    let mut project_paths_to_open = vec![];
 9325    let mut project_path_errors = vec![];
 9326
 9327    for path in paths {
 9328        let result = cx
 9329            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9330            .await;
 9331        match result {
 9332            Ok((_, project_path)) => {
 9333                project_paths_to_open.push((path.clone(), Some(project_path)));
 9334            }
 9335            Err(error) => {
 9336                project_path_errors.push(error);
 9337            }
 9338        };
 9339    }
 9340
 9341    if project_paths_to_open.is_empty() {
 9342        return Err(project_path_errors.pop().context("no paths given")?);
 9343    }
 9344
 9345    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9346        telemetry::event!("SSH Project Opened");
 9347
 9348        let new_workspace = cx.new(|cx| {
 9349            let mut workspace =
 9350                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9351            workspace.update_history(cx);
 9352
 9353            if let Some(ref serialized) = serialized_workspace {
 9354                workspace.centered_layout = serialized.centered_layout;
 9355            }
 9356
 9357            workspace
 9358        });
 9359
 9360        multi_workspace.activate(new_workspace.clone(), cx);
 9361        new_workspace
 9362    })?;
 9363
 9364    let items = window
 9365        .update(cx, |_, window, cx| {
 9366            window.activate_window();
 9367            workspace.update(cx, |_workspace, cx| {
 9368                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9369            })
 9370        })?
 9371        .await?;
 9372
 9373    workspace.update(cx, |workspace, cx| {
 9374        for error in project_path_errors {
 9375            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9376                if let Some(path) = error.error_tag("path") {
 9377                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9378                }
 9379            } else {
 9380                workspace.show_error(&error, cx)
 9381            }
 9382        }
 9383    });
 9384
 9385    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9386}
 9387
 9388fn deserialize_remote_project(
 9389    connection_options: RemoteConnectionOptions,
 9390    paths: Vec<PathBuf>,
 9391    cx: &AsyncApp,
 9392) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9393    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9394    cx.background_spawn(async move {
 9395        let remote_connection_id = db
 9396            .get_or_create_remote_connection(connection_options)
 9397            .await?;
 9398
 9399        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
 9400
 9401        let workspace_id = if let Some(workspace_id) =
 9402            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9403        {
 9404            workspace_id
 9405        } else {
 9406            db.next_id().await?
 9407        };
 9408
 9409        Ok((workspace_id, serialized_workspace))
 9410    })
 9411}
 9412
 9413pub fn join_in_room_project(
 9414    project_id: u64,
 9415    follow_user_id: u64,
 9416    app_state: Arc<AppState>,
 9417    cx: &mut App,
 9418) -> Task<Result<()>> {
 9419    let windows = cx.windows();
 9420    cx.spawn(async move |cx| {
 9421        let existing_window_and_workspace: Option<(
 9422            WindowHandle<MultiWorkspace>,
 9423            Entity<Workspace>,
 9424        )> = windows.into_iter().find_map(|window_handle| {
 9425            window_handle
 9426                .downcast::<MultiWorkspace>()
 9427                .and_then(|window_handle| {
 9428                    window_handle
 9429                        .update(cx, |multi_workspace, _window, cx| {
 9430                            for workspace in multi_workspace.workspaces() {
 9431                                if workspace.read(cx).project().read(cx).remote_id()
 9432                                    == Some(project_id)
 9433                                {
 9434                                    return Some((window_handle, workspace.clone()));
 9435                                }
 9436                            }
 9437                            None
 9438                        })
 9439                        .unwrap_or(None)
 9440                })
 9441        });
 9442
 9443        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9444            existing_window_and_workspace
 9445        {
 9446            existing_window
 9447                .update(cx, |multi_workspace, _, cx| {
 9448                    multi_workspace.activate(target_workspace, cx);
 9449                })
 9450                .ok();
 9451            existing_window
 9452        } else {
 9453            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9454            let project = cx
 9455                .update(|cx| {
 9456                    active_call.0.join_project(
 9457                        project_id,
 9458                        app_state.languages.clone(),
 9459                        app_state.fs.clone(),
 9460                        cx,
 9461                    )
 9462                })
 9463                .await?;
 9464
 9465            let window_bounds_override = window_bounds_env_override();
 9466            cx.update(|cx| {
 9467                let mut options = (app_state.build_window_options)(None, cx);
 9468                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9469                cx.open_window(options, |window, cx| {
 9470                    let workspace = cx.new(|cx| {
 9471                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9472                    });
 9473                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9474                })
 9475            })?
 9476        };
 9477
 9478        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9479            cx.activate(true);
 9480            window.activate_window();
 9481
 9482            // We set the active workspace above, so this is the correct workspace.
 9483            let workspace = multi_workspace.workspace().clone();
 9484            workspace.update(cx, |workspace, cx| {
 9485                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9486                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9487                    .or_else(|| {
 9488                        // If we couldn't follow the given user, follow the host instead.
 9489                        let collaborator = workspace
 9490                            .project()
 9491                            .read(cx)
 9492                            .collaborators()
 9493                            .values()
 9494                            .find(|collaborator| collaborator.is_host)?;
 9495                        Some(collaborator.peer_id)
 9496                    });
 9497
 9498                if let Some(follow_peer_id) = follow_peer_id {
 9499                    workspace.follow(follow_peer_id, window, cx);
 9500                }
 9501            });
 9502        })?;
 9503
 9504        anyhow::Ok(())
 9505    })
 9506}
 9507
 9508pub fn reload(cx: &mut App) {
 9509    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9510    let mut workspace_windows = cx
 9511        .windows()
 9512        .into_iter()
 9513        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9514        .collect::<Vec<_>>();
 9515
 9516    // If multiple windows have unsaved changes, and need a save prompt,
 9517    // prompt in the active window before switching to a different window.
 9518    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9519
 9520    let mut prompt = None;
 9521    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9522        prompt = window
 9523            .update(cx, |_, window, cx| {
 9524                window.prompt(
 9525                    PromptLevel::Info,
 9526                    "Are you sure you want to restart?",
 9527                    None,
 9528                    &["Restart", "Cancel"],
 9529                    cx,
 9530                )
 9531            })
 9532            .ok();
 9533    }
 9534
 9535    cx.spawn(async move |cx| {
 9536        if let Some(prompt) = prompt {
 9537            let answer = prompt.await?;
 9538            if answer != 0 {
 9539                return anyhow::Ok(());
 9540            }
 9541        }
 9542
 9543        // If the user cancels any save prompt, then keep the app open.
 9544        for window in workspace_windows {
 9545            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9546                let workspace = multi_workspace.workspace().clone();
 9547                workspace.update(cx, |workspace, cx| {
 9548                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9549                })
 9550            }) && !should_close.await?
 9551            {
 9552                return anyhow::Ok(());
 9553            }
 9554        }
 9555        cx.update(|cx| cx.restart());
 9556        anyhow::Ok(())
 9557    })
 9558    .detach_and_log_err(cx);
 9559}
 9560
 9561fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9562    let mut parts = value.split(',');
 9563    let x: usize = parts.next()?.parse().ok()?;
 9564    let y: usize = parts.next()?.parse().ok()?;
 9565    Some(point(px(x as f32), px(y as f32)))
 9566}
 9567
 9568fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9569    let mut parts = value.split(',');
 9570    let width: usize = parts.next()?.parse().ok()?;
 9571    let height: usize = parts.next()?.parse().ok()?;
 9572    Some(size(px(width as f32), px(height as f32)))
 9573}
 9574
 9575/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9576/// appropriate.
 9577///
 9578/// The `border_radius_tiling` parameter allows overriding which corners get
 9579/// rounded, independently of the actual window tiling state. This is used
 9580/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9581/// we want square corners on the left (so the sidebar appears flush with the
 9582/// window edge) but we still need the shadow padding for proper visual
 9583/// appearance. Unlike actual window tiling, this only affects border radius -
 9584/// not padding or shadows.
 9585pub fn client_side_decorations(
 9586    element: impl IntoElement,
 9587    window: &mut Window,
 9588    cx: &mut App,
 9589    border_radius_tiling: Tiling,
 9590) -> Stateful<Div> {
 9591    const BORDER_SIZE: Pixels = px(1.0);
 9592    let decorations = window.window_decorations();
 9593    let tiling = match decorations {
 9594        Decorations::Server => Tiling::default(),
 9595        Decorations::Client { tiling } => tiling,
 9596    };
 9597
 9598    match decorations {
 9599        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9600        Decorations::Server => window.set_client_inset(px(0.0)),
 9601    }
 9602
 9603    struct GlobalResizeEdge(ResizeEdge);
 9604    impl Global for GlobalResizeEdge {}
 9605
 9606    div()
 9607        .id("window-backdrop")
 9608        .bg(transparent_black())
 9609        .map(|div| match decorations {
 9610            Decorations::Server => div,
 9611            Decorations::Client { .. } => div
 9612                .when(
 9613                    !(tiling.top
 9614                        || tiling.right
 9615                        || border_radius_tiling.top
 9616                        || border_radius_tiling.right),
 9617                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9618                )
 9619                .when(
 9620                    !(tiling.top
 9621                        || tiling.left
 9622                        || border_radius_tiling.top
 9623                        || border_radius_tiling.left),
 9624                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9625                )
 9626                .when(
 9627                    !(tiling.bottom
 9628                        || tiling.right
 9629                        || border_radius_tiling.bottom
 9630                        || border_radius_tiling.right),
 9631                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9632                )
 9633                .when(
 9634                    !(tiling.bottom
 9635                        || tiling.left
 9636                        || border_radius_tiling.bottom
 9637                        || border_radius_tiling.left),
 9638                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9639                )
 9640                .when(!tiling.top, |div| {
 9641                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9642                })
 9643                .when(!tiling.bottom, |div| {
 9644                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9645                })
 9646                .when(!tiling.left, |div| {
 9647                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9648                })
 9649                .when(!tiling.right, |div| {
 9650                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9651                })
 9652                .on_mouse_move(move |e, window, cx| {
 9653                    let size = window.window_bounds().get_bounds().size;
 9654                    let pos = e.position;
 9655
 9656                    let new_edge =
 9657                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 9658
 9659                    let edge = cx.try_global::<GlobalResizeEdge>();
 9660                    if new_edge != edge.map(|edge| edge.0) {
 9661                        window
 9662                            .window_handle()
 9663                            .update(cx, |workspace, _, cx| {
 9664                                cx.notify(workspace.entity_id());
 9665                            })
 9666                            .ok();
 9667                    }
 9668                })
 9669                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 9670                    let size = window.window_bounds().get_bounds().size;
 9671                    let pos = e.position;
 9672
 9673                    let edge = match resize_edge(
 9674                        pos,
 9675                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 9676                        size,
 9677                        tiling,
 9678                    ) {
 9679                        Some(value) => value,
 9680                        None => return,
 9681                    };
 9682
 9683                    window.start_window_resize(edge);
 9684                }),
 9685        })
 9686        .size_full()
 9687        .child(
 9688            div()
 9689                .cursor(CursorStyle::Arrow)
 9690                .map(|div| match decorations {
 9691                    Decorations::Server => div,
 9692                    Decorations::Client { .. } => div
 9693                        .border_color(cx.theme().colors().border)
 9694                        .when(
 9695                            !(tiling.top
 9696                                || tiling.right
 9697                                || border_radius_tiling.top
 9698                                || border_radius_tiling.right),
 9699                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9700                        )
 9701                        .when(
 9702                            !(tiling.top
 9703                                || tiling.left
 9704                                || border_radius_tiling.top
 9705                                || border_radius_tiling.left),
 9706                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9707                        )
 9708                        .when(
 9709                            !(tiling.bottom
 9710                                || tiling.right
 9711                                || border_radius_tiling.bottom
 9712                                || border_radius_tiling.right),
 9713                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9714                        )
 9715                        .when(
 9716                            !(tiling.bottom
 9717                                || tiling.left
 9718                                || border_radius_tiling.bottom
 9719                                || border_radius_tiling.left),
 9720                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9721                        )
 9722                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 9723                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 9724                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 9725                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 9726                        .when(!tiling.is_tiled(), |div| {
 9727                            div.shadow(vec![gpui::BoxShadow {
 9728                                color: Hsla {
 9729                                    h: 0.,
 9730                                    s: 0.,
 9731                                    l: 0.,
 9732                                    a: 0.4,
 9733                                },
 9734                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 9735                                spread_radius: px(0.),
 9736                                offset: point(px(0.0), px(0.0)),
 9737                            }])
 9738                        }),
 9739                })
 9740                .on_mouse_move(|_e, _, cx| {
 9741                    cx.stop_propagation();
 9742                })
 9743                .size_full()
 9744                .child(element),
 9745        )
 9746        .map(|div| match decorations {
 9747            Decorations::Server => div,
 9748            Decorations::Client { tiling, .. } => div.child(
 9749                canvas(
 9750                    |_bounds, window, _| {
 9751                        window.insert_hitbox(
 9752                            Bounds::new(
 9753                                point(px(0.0), px(0.0)),
 9754                                window.window_bounds().get_bounds().size,
 9755                            ),
 9756                            HitboxBehavior::Normal,
 9757                        )
 9758                    },
 9759                    move |_bounds, hitbox, window, cx| {
 9760                        let mouse = window.mouse_position();
 9761                        let size = window.window_bounds().get_bounds().size;
 9762                        let Some(edge) =
 9763                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 9764                        else {
 9765                            return;
 9766                        };
 9767                        cx.set_global(GlobalResizeEdge(edge));
 9768                        window.set_cursor_style(
 9769                            match edge {
 9770                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 9771                                ResizeEdge::Left | ResizeEdge::Right => {
 9772                                    CursorStyle::ResizeLeftRight
 9773                                }
 9774                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 9775                                    CursorStyle::ResizeUpLeftDownRight
 9776                                }
 9777                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 9778                                    CursorStyle::ResizeUpRightDownLeft
 9779                                }
 9780                            },
 9781                            &hitbox,
 9782                        );
 9783                    },
 9784                )
 9785                .size_full()
 9786                .absolute(),
 9787            ),
 9788        })
 9789}
 9790
 9791fn resize_edge(
 9792    pos: Point<Pixels>,
 9793    shadow_size: Pixels,
 9794    window_size: Size<Pixels>,
 9795    tiling: Tiling,
 9796) -> Option<ResizeEdge> {
 9797    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 9798    if bounds.contains(&pos) {
 9799        return None;
 9800    }
 9801
 9802    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 9803    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 9804    if !tiling.top && top_left_bounds.contains(&pos) {
 9805        return Some(ResizeEdge::TopLeft);
 9806    }
 9807
 9808    let top_right_bounds = Bounds::new(
 9809        Point::new(window_size.width - corner_size.width, px(0.)),
 9810        corner_size,
 9811    );
 9812    if !tiling.top && top_right_bounds.contains(&pos) {
 9813        return Some(ResizeEdge::TopRight);
 9814    }
 9815
 9816    let bottom_left_bounds = Bounds::new(
 9817        Point::new(px(0.), window_size.height - corner_size.height),
 9818        corner_size,
 9819    );
 9820    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 9821        return Some(ResizeEdge::BottomLeft);
 9822    }
 9823
 9824    let bottom_right_bounds = Bounds::new(
 9825        Point::new(
 9826            window_size.width - corner_size.width,
 9827            window_size.height - corner_size.height,
 9828        ),
 9829        corner_size,
 9830    );
 9831    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 9832        return Some(ResizeEdge::BottomRight);
 9833    }
 9834
 9835    if !tiling.top && pos.y < shadow_size {
 9836        Some(ResizeEdge::Top)
 9837    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 9838        Some(ResizeEdge::Bottom)
 9839    } else if !tiling.left && pos.x < shadow_size {
 9840        Some(ResizeEdge::Left)
 9841    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 9842        Some(ResizeEdge::Right)
 9843    } else {
 9844        None
 9845    }
 9846}
 9847
 9848fn join_pane_into_active(
 9849    active_pane: &Entity<Pane>,
 9850    pane: &Entity<Pane>,
 9851    window: &mut Window,
 9852    cx: &mut App,
 9853) {
 9854    if pane == active_pane {
 9855    } else if pane.read(cx).items_len() == 0 {
 9856        pane.update(cx, |_, cx| {
 9857            cx.emit(pane::Event::Remove {
 9858                focus_on_pane: None,
 9859            });
 9860        })
 9861    } else {
 9862        move_all_items(pane, active_pane, window, cx);
 9863    }
 9864}
 9865
 9866fn move_all_items(
 9867    from_pane: &Entity<Pane>,
 9868    to_pane: &Entity<Pane>,
 9869    window: &mut Window,
 9870    cx: &mut App,
 9871) {
 9872    let destination_is_different = from_pane != to_pane;
 9873    let mut moved_items = 0;
 9874    for (item_ix, item_handle) in from_pane
 9875        .read(cx)
 9876        .items()
 9877        .enumerate()
 9878        .map(|(ix, item)| (ix, item.clone()))
 9879        .collect::<Vec<_>>()
 9880    {
 9881        let ix = item_ix - moved_items;
 9882        if destination_is_different {
 9883            // Close item from previous pane
 9884            from_pane.update(cx, |source, cx| {
 9885                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 9886            });
 9887            moved_items += 1;
 9888        }
 9889
 9890        // This automatically removes duplicate items in the pane
 9891        to_pane.update(cx, |destination, cx| {
 9892            destination.add_item(item_handle, true, true, None, window, cx);
 9893            window.focus(&destination.focus_handle(cx), cx)
 9894        });
 9895    }
 9896}
 9897
 9898pub fn move_item(
 9899    source: &Entity<Pane>,
 9900    destination: &Entity<Pane>,
 9901    item_id_to_move: EntityId,
 9902    destination_index: usize,
 9903    activate: bool,
 9904    window: &mut Window,
 9905    cx: &mut App,
 9906) {
 9907    let Some((item_ix, item_handle)) = source
 9908        .read(cx)
 9909        .items()
 9910        .enumerate()
 9911        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 9912        .map(|(ix, item)| (ix, item.clone()))
 9913    else {
 9914        // Tab was closed during drag
 9915        return;
 9916    };
 9917
 9918    if source != destination {
 9919        // Close item from previous pane
 9920        source.update(cx, |source, cx| {
 9921            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 9922        });
 9923    }
 9924
 9925    // This automatically removes duplicate items in the pane
 9926    destination.update(cx, |destination, cx| {
 9927        destination.add_item_inner(
 9928            item_handle,
 9929            activate,
 9930            activate,
 9931            activate,
 9932            Some(destination_index),
 9933            window,
 9934            cx,
 9935        );
 9936        if activate {
 9937            window.focus(&destination.focus_handle(cx), cx)
 9938        }
 9939    });
 9940}
 9941
 9942pub fn move_active_item(
 9943    source: &Entity<Pane>,
 9944    destination: &Entity<Pane>,
 9945    focus_destination: bool,
 9946    close_if_empty: bool,
 9947    window: &mut Window,
 9948    cx: &mut App,
 9949) {
 9950    if source == destination {
 9951        return;
 9952    }
 9953    let Some(active_item) = source.read(cx).active_item() else {
 9954        return;
 9955    };
 9956    source.update(cx, |source_pane, cx| {
 9957        let item_id = active_item.item_id();
 9958        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 9959        destination.update(cx, |target_pane, cx| {
 9960            target_pane.add_item(
 9961                active_item,
 9962                focus_destination,
 9963                focus_destination,
 9964                Some(target_pane.items_len()),
 9965                window,
 9966                cx,
 9967            );
 9968        });
 9969    });
 9970}
 9971
 9972pub fn clone_active_item(
 9973    workspace_id: Option<WorkspaceId>,
 9974    source: &Entity<Pane>,
 9975    destination: &Entity<Pane>,
 9976    focus_destination: bool,
 9977    window: &mut Window,
 9978    cx: &mut App,
 9979) {
 9980    if source == destination {
 9981        return;
 9982    }
 9983    let Some(active_item) = source.read(cx).active_item() else {
 9984        return;
 9985    };
 9986    if !active_item.can_split(cx) {
 9987        return;
 9988    }
 9989    let destination = destination.downgrade();
 9990    let task = active_item.clone_on_split(workspace_id, window, cx);
 9991    window
 9992        .spawn(cx, async move |cx| {
 9993            let Some(clone) = task.await else {
 9994                return;
 9995            };
 9996            destination
 9997                .update_in(cx, |target_pane, window, cx| {
 9998                    target_pane.add_item(
 9999                        clone,
10000                        focus_destination,
10001                        focus_destination,
10002                        Some(target_pane.items_len()),
10003                        window,
10004                        cx,
10005                    );
10006                })
10007                .log_err();
10008        })
10009        .detach();
10010}
10011
10012#[derive(Debug)]
10013pub struct WorkspacePosition {
10014    pub window_bounds: Option<WindowBounds>,
10015    pub display: Option<Uuid>,
10016    pub centered_layout: bool,
10017}
10018
10019pub fn remote_workspace_position_from_db(
10020    connection_options: RemoteConnectionOptions,
10021    paths_to_open: &[PathBuf],
10022    cx: &App,
10023) -> Task<Result<WorkspacePosition>> {
10024    let paths = paths_to_open.to_vec();
10025    let db = WorkspaceDb::global(cx);
10026    let kvp = db::kvp::KeyValueStore::global(cx);
10027
10028    cx.background_spawn(async move {
10029        let remote_connection_id = db
10030            .get_or_create_remote_connection(connection_options)
10031            .await
10032            .context("fetching serialized ssh project")?;
10033        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10034
10035        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10036            (Some(WindowBounds::Windowed(bounds)), None)
10037        } else {
10038            let restorable_bounds = serialized_workspace
10039                .as_ref()
10040                .and_then(|workspace| {
10041                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10042                })
10043                .or_else(|| persistence::read_default_window_bounds(&kvp));
10044
10045            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10046                (Some(serialized_bounds), Some(serialized_display))
10047            } else {
10048                (None, None)
10049            }
10050        };
10051
10052        let centered_layout = serialized_workspace
10053            .as_ref()
10054            .map(|w| w.centered_layout)
10055            .unwrap_or(false);
10056
10057        Ok(WorkspacePosition {
10058            window_bounds,
10059            display,
10060            centered_layout,
10061        })
10062    })
10063}
10064
10065pub fn with_active_or_new_workspace(
10066    cx: &mut App,
10067    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10068) {
10069    match cx
10070        .active_window()
10071        .and_then(|w| w.downcast::<MultiWorkspace>())
10072    {
10073        Some(multi_workspace) => {
10074            cx.defer(move |cx| {
10075                multi_workspace
10076                    .update(cx, |multi_workspace, window, cx| {
10077                        let workspace = multi_workspace.workspace().clone();
10078                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10079                    })
10080                    .log_err();
10081            });
10082        }
10083        None => {
10084            let app_state = AppState::global(cx);
10085            if let Some(app_state) = app_state.upgrade() {
10086                open_new(
10087                    OpenOptions::default(),
10088                    app_state,
10089                    cx,
10090                    move |workspace, window, cx| f(workspace, window, cx),
10091                )
10092                .detach_and_log_err(cx);
10093            }
10094        }
10095    }
10096}
10097
10098#[cfg(test)]
10099mod tests {
10100    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10101
10102    use super::*;
10103    use crate::{
10104        dock::{PanelEvent, test::TestPanel},
10105        item::{
10106            ItemBufferKind, ItemEvent,
10107            test::{TestItem, TestProjectItem},
10108        },
10109    };
10110    use fs::FakeFs;
10111    use gpui::{
10112        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10113        UpdateGlobal, VisualTestContext, px,
10114    };
10115    use project::{Project, ProjectEntryId};
10116    use serde_json::json;
10117    use settings::SettingsStore;
10118    use util::path;
10119    use util::rel_path::rel_path;
10120
10121    #[gpui::test]
10122    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10123        init_test(cx);
10124
10125        let fs = FakeFs::new(cx.executor());
10126        let project = Project::test(fs, [], cx).await;
10127        let (workspace, cx) =
10128            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10129
10130        // Adding an item with no ambiguity renders the tab without detail.
10131        let item1 = cx.new(|cx| {
10132            let mut item = TestItem::new(cx);
10133            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10134            item
10135        });
10136        workspace.update_in(cx, |workspace, window, cx| {
10137            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10138        });
10139        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10140
10141        // Adding an item that creates ambiguity increases the level of detail on
10142        // both tabs.
10143        let item2 = cx.new_window_entity(|_window, cx| {
10144            let mut item = TestItem::new(cx);
10145            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10146            item
10147        });
10148        workspace.update_in(cx, |workspace, window, cx| {
10149            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10150        });
10151        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10152        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10153
10154        // Adding an item that creates ambiguity increases the level of detail only
10155        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10156        // we stop at the highest detail available.
10157        let item3 = cx.new(|cx| {
10158            let mut item = TestItem::new(cx);
10159            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10160            item
10161        });
10162        workspace.update_in(cx, |workspace, window, cx| {
10163            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10164        });
10165        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10166        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10167        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10168    }
10169
10170    #[gpui::test]
10171    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10172        init_test(cx);
10173
10174        let fs = FakeFs::new(cx.executor());
10175        fs.insert_tree(
10176            "/root1",
10177            json!({
10178                "one.txt": "",
10179                "two.txt": "",
10180            }),
10181        )
10182        .await;
10183        fs.insert_tree(
10184            "/root2",
10185            json!({
10186                "three.txt": "",
10187            }),
10188        )
10189        .await;
10190
10191        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10192        let (workspace, cx) =
10193            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10194        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10195        let worktree_id = project.update(cx, |project, cx| {
10196            project.worktrees(cx).next().unwrap().read(cx).id()
10197        });
10198
10199        let item1 = cx.new(|cx| {
10200            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10201        });
10202        let item2 = cx.new(|cx| {
10203            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10204        });
10205
10206        // Add an item to an empty pane
10207        workspace.update_in(cx, |workspace, window, cx| {
10208            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10209        });
10210        project.update(cx, |project, cx| {
10211            assert_eq!(
10212                project.active_entry(),
10213                project
10214                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10215                    .map(|e| e.id)
10216            );
10217        });
10218        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10219
10220        // Add a second item to a non-empty pane
10221        workspace.update_in(cx, |workspace, window, cx| {
10222            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10223        });
10224        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10225        project.update(cx, |project, cx| {
10226            assert_eq!(
10227                project.active_entry(),
10228                project
10229                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10230                    .map(|e| e.id)
10231            );
10232        });
10233
10234        // Close the active item
10235        pane.update_in(cx, |pane, window, cx| {
10236            pane.close_active_item(&Default::default(), window, cx)
10237        })
10238        .await
10239        .unwrap();
10240        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10241        project.update(cx, |project, cx| {
10242            assert_eq!(
10243                project.active_entry(),
10244                project
10245                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10246                    .map(|e| e.id)
10247            );
10248        });
10249
10250        // Add a project folder
10251        project
10252            .update(cx, |project, cx| {
10253                project.find_or_create_worktree("root2", true, cx)
10254            })
10255            .await
10256            .unwrap();
10257        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10258
10259        // Remove a project folder
10260        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10261        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10262    }
10263
10264    #[gpui::test]
10265    async fn test_close_window(cx: &mut TestAppContext) {
10266        init_test(cx);
10267
10268        let fs = FakeFs::new(cx.executor());
10269        fs.insert_tree("/root", json!({ "one": "" })).await;
10270
10271        let project = Project::test(fs, ["root".as_ref()], cx).await;
10272        let (workspace, cx) =
10273            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10274
10275        // When there are no dirty items, there's nothing to do.
10276        let item1 = cx.new(TestItem::new);
10277        workspace.update_in(cx, |w, window, cx| {
10278            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10279        });
10280        let task = workspace.update_in(cx, |w, window, cx| {
10281            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10282        });
10283        assert!(task.await.unwrap());
10284
10285        // When there are dirty untitled items, prompt to save each one. If the user
10286        // cancels any prompt, then abort.
10287        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10288        let item3 = cx.new(|cx| {
10289            TestItem::new(cx)
10290                .with_dirty(true)
10291                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10292        });
10293        workspace.update_in(cx, |w, window, cx| {
10294            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10295            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10296        });
10297        let task = workspace.update_in(cx, |w, window, cx| {
10298            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10299        });
10300        cx.executor().run_until_parked();
10301        cx.simulate_prompt_answer("Cancel"); // cancel save all
10302        cx.executor().run_until_parked();
10303        assert!(!cx.has_pending_prompt());
10304        assert!(!task.await.unwrap());
10305    }
10306
10307    #[gpui::test]
10308    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10309        init_test(cx);
10310
10311        let fs = FakeFs::new(cx.executor());
10312        fs.insert_tree("/root", json!({ "one": "" })).await;
10313
10314        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10315        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10316        let multi_workspace_handle =
10317            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10318        cx.run_until_parked();
10319
10320        let workspace_a = multi_workspace_handle
10321            .read_with(cx, |mw, _| mw.workspace().clone())
10322            .unwrap();
10323
10324        let workspace_b = multi_workspace_handle
10325            .update(cx, |mw, window, cx| {
10326                mw.test_add_workspace(project_b, window, cx)
10327            })
10328            .unwrap();
10329
10330        // Activate workspace A
10331        multi_workspace_handle
10332            .update(cx, |mw, window, cx| {
10333                mw.activate_index(0, window, cx);
10334            })
10335            .unwrap();
10336
10337        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10338
10339        // Workspace A has a clean item
10340        let item_a = cx.new(TestItem::new);
10341        workspace_a.update_in(cx, |w, window, cx| {
10342            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10343        });
10344
10345        // Workspace B has a dirty item
10346        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10347        workspace_b.update_in(cx, |w, window, cx| {
10348            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10349        });
10350
10351        // Verify workspace A is active
10352        multi_workspace_handle
10353            .read_with(cx, |mw, _| {
10354                assert_eq!(mw.active_workspace_index(), 0);
10355            })
10356            .unwrap();
10357
10358        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10359        multi_workspace_handle
10360            .update(cx, |mw, window, cx| {
10361                mw.close_window(&CloseWindow, window, cx);
10362            })
10363            .unwrap();
10364        cx.run_until_parked();
10365
10366        // Workspace B should now be active since it has dirty items that need attention
10367        multi_workspace_handle
10368            .read_with(cx, |mw, _| {
10369                assert_eq!(
10370                    mw.active_workspace_index(),
10371                    1,
10372                    "workspace B should be activated when it prompts"
10373                );
10374            })
10375            .unwrap();
10376
10377        // User cancels the save prompt from workspace B
10378        cx.simulate_prompt_answer("Cancel");
10379        cx.run_until_parked();
10380
10381        // Window should still exist because workspace B's close was cancelled
10382        assert!(
10383            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10384            "window should still exist after cancelling one workspace's close"
10385        );
10386    }
10387
10388    #[gpui::test]
10389    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10390        init_test(cx);
10391
10392        // Register TestItem as a serializable item
10393        cx.update(|cx| {
10394            register_serializable_item::<TestItem>(cx);
10395        });
10396
10397        let fs = FakeFs::new(cx.executor());
10398        fs.insert_tree("/root", json!({ "one": "" })).await;
10399
10400        let project = Project::test(fs, ["root".as_ref()], cx).await;
10401        let (workspace, cx) =
10402            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10403
10404        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10405        let item1 = cx.new(|cx| {
10406            TestItem::new(cx)
10407                .with_dirty(true)
10408                .with_serialize(|| Some(Task::ready(Ok(()))))
10409        });
10410        let item2 = cx.new(|cx| {
10411            TestItem::new(cx)
10412                .with_dirty(true)
10413                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10414                .with_serialize(|| Some(Task::ready(Ok(()))))
10415        });
10416        workspace.update_in(cx, |w, window, cx| {
10417            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10418            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10419        });
10420        let task = workspace.update_in(cx, |w, window, cx| {
10421            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10422        });
10423        assert!(task.await.unwrap());
10424    }
10425
10426    #[gpui::test]
10427    async fn test_close_pane_items(cx: &mut TestAppContext) {
10428        init_test(cx);
10429
10430        let fs = FakeFs::new(cx.executor());
10431
10432        let project = Project::test(fs, None, cx).await;
10433        let (workspace, cx) =
10434            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10435
10436        let item1 = cx.new(|cx| {
10437            TestItem::new(cx)
10438                .with_dirty(true)
10439                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10440        });
10441        let item2 = cx.new(|cx| {
10442            TestItem::new(cx)
10443                .with_dirty(true)
10444                .with_conflict(true)
10445                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10446        });
10447        let item3 = cx.new(|cx| {
10448            TestItem::new(cx)
10449                .with_dirty(true)
10450                .with_conflict(true)
10451                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10452        });
10453        let item4 = cx.new(|cx| {
10454            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10455                let project_item = TestProjectItem::new_untitled(cx);
10456                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10457                project_item
10458            }])
10459        });
10460        let pane = workspace.update_in(cx, |workspace, window, cx| {
10461            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10462            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10463            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10464            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10465            workspace.active_pane().clone()
10466        });
10467
10468        let close_items = pane.update_in(cx, |pane, window, cx| {
10469            pane.activate_item(1, true, true, window, cx);
10470            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10471            let item1_id = item1.item_id();
10472            let item3_id = item3.item_id();
10473            let item4_id = item4.item_id();
10474            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10475                [item1_id, item3_id, item4_id].contains(&id)
10476            })
10477        });
10478        cx.executor().run_until_parked();
10479
10480        assert!(cx.has_pending_prompt());
10481        cx.simulate_prompt_answer("Save all");
10482
10483        cx.executor().run_until_parked();
10484
10485        // Item 1 is saved. There's a prompt to save item 3.
10486        pane.update(cx, |pane, cx| {
10487            assert_eq!(item1.read(cx).save_count, 1);
10488            assert_eq!(item1.read(cx).save_as_count, 0);
10489            assert_eq!(item1.read(cx).reload_count, 0);
10490            assert_eq!(pane.items_len(), 3);
10491            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10492        });
10493        assert!(cx.has_pending_prompt());
10494
10495        // Cancel saving item 3.
10496        cx.simulate_prompt_answer("Discard");
10497        cx.executor().run_until_parked();
10498
10499        // Item 3 is reloaded. There's a prompt to save item 4.
10500        pane.update(cx, |pane, cx| {
10501            assert_eq!(item3.read(cx).save_count, 0);
10502            assert_eq!(item3.read(cx).save_as_count, 0);
10503            assert_eq!(item3.read(cx).reload_count, 1);
10504            assert_eq!(pane.items_len(), 2);
10505            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10506        });
10507
10508        // There's a prompt for a path for item 4.
10509        cx.simulate_new_path_selection(|_| Some(Default::default()));
10510        close_items.await.unwrap();
10511
10512        // The requested items are closed.
10513        pane.update(cx, |pane, cx| {
10514            assert_eq!(item4.read(cx).save_count, 0);
10515            assert_eq!(item4.read(cx).save_as_count, 1);
10516            assert_eq!(item4.read(cx).reload_count, 0);
10517            assert_eq!(pane.items_len(), 1);
10518            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10519        });
10520    }
10521
10522    #[gpui::test]
10523    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10524        init_test(cx);
10525
10526        let fs = FakeFs::new(cx.executor());
10527        let project = Project::test(fs, [], cx).await;
10528        let (workspace, cx) =
10529            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10530
10531        // Create several workspace items with single project entries, and two
10532        // workspace items with multiple project entries.
10533        let single_entry_items = (0..=4)
10534            .map(|project_entry_id| {
10535                cx.new(|cx| {
10536                    TestItem::new(cx)
10537                        .with_dirty(true)
10538                        .with_project_items(&[dirty_project_item(
10539                            project_entry_id,
10540                            &format!("{project_entry_id}.txt"),
10541                            cx,
10542                        )])
10543                })
10544            })
10545            .collect::<Vec<_>>();
10546        let item_2_3 = cx.new(|cx| {
10547            TestItem::new(cx)
10548                .with_dirty(true)
10549                .with_buffer_kind(ItemBufferKind::Multibuffer)
10550                .with_project_items(&[
10551                    single_entry_items[2].read(cx).project_items[0].clone(),
10552                    single_entry_items[3].read(cx).project_items[0].clone(),
10553                ])
10554        });
10555        let item_3_4 = cx.new(|cx| {
10556            TestItem::new(cx)
10557                .with_dirty(true)
10558                .with_buffer_kind(ItemBufferKind::Multibuffer)
10559                .with_project_items(&[
10560                    single_entry_items[3].read(cx).project_items[0].clone(),
10561                    single_entry_items[4].read(cx).project_items[0].clone(),
10562                ])
10563        });
10564
10565        // Create two panes that contain the following project entries:
10566        //   left pane:
10567        //     multi-entry items:   (2, 3)
10568        //     single-entry items:  0, 2, 3, 4
10569        //   right pane:
10570        //     single-entry items:  4, 1
10571        //     multi-entry items:   (3, 4)
10572        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10573            let left_pane = workspace.active_pane().clone();
10574            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10575            workspace.add_item_to_active_pane(
10576                single_entry_items[0].boxed_clone(),
10577                None,
10578                true,
10579                window,
10580                cx,
10581            );
10582            workspace.add_item_to_active_pane(
10583                single_entry_items[2].boxed_clone(),
10584                None,
10585                true,
10586                window,
10587                cx,
10588            );
10589            workspace.add_item_to_active_pane(
10590                single_entry_items[3].boxed_clone(),
10591                None,
10592                true,
10593                window,
10594                cx,
10595            );
10596            workspace.add_item_to_active_pane(
10597                single_entry_items[4].boxed_clone(),
10598                None,
10599                true,
10600                window,
10601                cx,
10602            );
10603
10604            let right_pane =
10605                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10606
10607            let boxed_clone = single_entry_items[1].boxed_clone();
10608            let right_pane = window.spawn(cx, async move |cx| {
10609                right_pane.await.inspect(|right_pane| {
10610                    right_pane
10611                        .update_in(cx, |pane, window, cx| {
10612                            pane.add_item(boxed_clone, true, true, None, window, cx);
10613                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10614                        })
10615                        .unwrap();
10616                })
10617            });
10618
10619            (left_pane, right_pane)
10620        });
10621        let right_pane = right_pane.await.unwrap();
10622        cx.focus(&right_pane);
10623
10624        let close = right_pane.update_in(cx, |pane, window, cx| {
10625            pane.close_all_items(&CloseAllItems::default(), window, cx)
10626                .unwrap()
10627        });
10628        cx.executor().run_until_parked();
10629
10630        let msg = cx.pending_prompt().unwrap().0;
10631        assert!(msg.contains("1.txt"));
10632        assert!(!msg.contains("2.txt"));
10633        assert!(!msg.contains("3.txt"));
10634        assert!(!msg.contains("4.txt"));
10635
10636        // With best-effort close, cancelling item 1 keeps it open but items 4
10637        // and (3,4) still close since their entries exist in left pane.
10638        cx.simulate_prompt_answer("Cancel");
10639        close.await;
10640
10641        right_pane.read_with(cx, |pane, _| {
10642            assert_eq!(pane.items_len(), 1);
10643        });
10644
10645        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10646        left_pane
10647            .update_in(cx, |left_pane, window, cx| {
10648                left_pane.close_item_by_id(
10649                    single_entry_items[3].entity_id(),
10650                    SaveIntent::Skip,
10651                    window,
10652                    cx,
10653                )
10654            })
10655            .await
10656            .unwrap();
10657
10658        let close = left_pane.update_in(cx, |pane, window, cx| {
10659            pane.close_all_items(&CloseAllItems::default(), window, cx)
10660                .unwrap()
10661        });
10662        cx.executor().run_until_parked();
10663
10664        let details = cx.pending_prompt().unwrap().1;
10665        assert!(details.contains("0.txt"));
10666        assert!(details.contains("3.txt"));
10667        assert!(details.contains("4.txt"));
10668        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10669        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10670        // assert!(!details.contains("2.txt"));
10671
10672        cx.simulate_prompt_answer("Save all");
10673        cx.executor().run_until_parked();
10674        close.await;
10675
10676        left_pane.read_with(cx, |pane, _| {
10677            assert_eq!(pane.items_len(), 0);
10678        });
10679    }
10680
10681    #[gpui::test]
10682    async fn test_autosave(cx: &mut gpui::TestAppContext) {
10683        init_test(cx);
10684
10685        let fs = FakeFs::new(cx.executor());
10686        let project = Project::test(fs, [], cx).await;
10687        let (workspace, cx) =
10688            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10689        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10690
10691        let item = cx.new(|cx| {
10692            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10693        });
10694        let item_id = item.entity_id();
10695        workspace.update_in(cx, |workspace, window, cx| {
10696            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10697        });
10698
10699        // Autosave on window change.
10700        item.update(cx, |item, cx| {
10701            SettingsStore::update_global(cx, |settings, cx| {
10702                settings.update_user_settings(cx, |settings| {
10703                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10704                })
10705            });
10706            item.is_dirty = true;
10707        });
10708
10709        // Deactivating the window saves the file.
10710        cx.deactivate_window();
10711        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10712
10713        // Re-activating the window doesn't save the file.
10714        cx.update(|window, _| window.activate_window());
10715        cx.executor().run_until_parked();
10716        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10717
10718        // Autosave on focus change.
10719        item.update_in(cx, |item, window, cx| {
10720            cx.focus_self(window);
10721            SettingsStore::update_global(cx, |settings, cx| {
10722                settings.update_user_settings(cx, |settings| {
10723                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10724                })
10725            });
10726            item.is_dirty = true;
10727        });
10728        // Blurring the item saves the file.
10729        item.update_in(cx, |_, window, _| window.blur());
10730        cx.executor().run_until_parked();
10731        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10732
10733        // Deactivating the window still saves the file.
10734        item.update_in(cx, |item, window, cx| {
10735            cx.focus_self(window);
10736            item.is_dirty = true;
10737        });
10738        cx.deactivate_window();
10739        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10740
10741        // Autosave after delay.
10742        item.update(cx, |item, cx| {
10743            SettingsStore::update_global(cx, |settings, cx| {
10744                settings.update_user_settings(cx, |settings| {
10745                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10746                        milliseconds: 500.into(),
10747                    });
10748                })
10749            });
10750            item.is_dirty = true;
10751            cx.emit(ItemEvent::Edit);
10752        });
10753
10754        // Delay hasn't fully expired, so the file is still dirty and unsaved.
10755        cx.executor().advance_clock(Duration::from_millis(250));
10756        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10757
10758        // After delay expires, the file is saved.
10759        cx.executor().advance_clock(Duration::from_millis(250));
10760        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10761
10762        // Autosave after delay, should save earlier than delay if tab is closed
10763        item.update(cx, |item, cx| {
10764            item.is_dirty = true;
10765            cx.emit(ItemEvent::Edit);
10766        });
10767        cx.executor().advance_clock(Duration::from_millis(250));
10768        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10769
10770        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10771        pane.update_in(cx, |pane, window, cx| {
10772            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10773        })
10774        .await
10775        .unwrap();
10776        assert!(!cx.has_pending_prompt());
10777        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10778
10779        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10780        workspace.update_in(cx, |workspace, window, cx| {
10781            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10782        });
10783        item.update_in(cx, |item, _window, cx| {
10784            item.is_dirty = true;
10785            for project_item in &mut item.project_items {
10786                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10787            }
10788        });
10789        cx.run_until_parked();
10790        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10791
10792        // Autosave on focus change, ensuring closing the tab counts as such.
10793        item.update(cx, |item, cx| {
10794            SettingsStore::update_global(cx, |settings, cx| {
10795                settings.update_user_settings(cx, |settings| {
10796                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10797                })
10798            });
10799            item.is_dirty = true;
10800            for project_item in &mut item.project_items {
10801                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10802            }
10803        });
10804
10805        pane.update_in(cx, |pane, window, cx| {
10806            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10807        })
10808        .await
10809        .unwrap();
10810        assert!(!cx.has_pending_prompt());
10811        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10812
10813        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10814        workspace.update_in(cx, |workspace, window, cx| {
10815            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10816        });
10817        item.update_in(cx, |item, window, cx| {
10818            item.project_items[0].update(cx, |item, _| {
10819                item.entry_id = None;
10820            });
10821            item.is_dirty = true;
10822            window.blur();
10823        });
10824        cx.run_until_parked();
10825        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10826
10827        // Ensure autosave is prevented for deleted files also when closing the buffer.
10828        let _close_items = pane.update_in(cx, |pane, window, cx| {
10829            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10830        });
10831        cx.run_until_parked();
10832        assert!(cx.has_pending_prompt());
10833        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10834    }
10835
10836    #[gpui::test]
10837    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
10838        init_test(cx);
10839
10840        let fs = FakeFs::new(cx.executor());
10841        let project = Project::test(fs, [], cx).await;
10842        let (workspace, cx) =
10843            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10844
10845        // Create a multibuffer-like item with two child focus handles,
10846        // simulating individual buffer editors within a multibuffer.
10847        let item = cx.new(|cx| {
10848            TestItem::new(cx)
10849                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10850                .with_child_focus_handles(2, cx)
10851        });
10852        workspace.update_in(cx, |workspace, window, cx| {
10853            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10854        });
10855
10856        // Set autosave to OnFocusChange and focus the first child handle,
10857        // simulating the user's cursor being inside one of the multibuffer's excerpts.
10858        item.update_in(cx, |item, window, cx| {
10859            SettingsStore::update_global(cx, |settings, cx| {
10860                settings.update_user_settings(cx, |settings| {
10861                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10862                })
10863            });
10864            item.is_dirty = true;
10865            window.focus(&item.child_focus_handles[0], cx);
10866        });
10867        cx.executor().run_until_parked();
10868        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
10869
10870        // Moving focus from one child to another within the same item should
10871        // NOT trigger autosave — focus is still within the item's focus hierarchy.
10872        item.update_in(cx, |item, window, cx| {
10873            window.focus(&item.child_focus_handles[1], cx);
10874        });
10875        cx.executor().run_until_parked();
10876        item.read_with(cx, |item, _| {
10877            assert_eq!(
10878                item.save_count, 0,
10879                "Switching focus between children within the same item should not autosave"
10880            );
10881        });
10882
10883        // Blurring the item saves the file. This is the core regression scenario:
10884        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
10885        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
10886        // the leaf is always a child focus handle, so `on_blur` never detected
10887        // focus leaving the item.
10888        item.update_in(cx, |_, window, _| window.blur());
10889        cx.executor().run_until_parked();
10890        item.read_with(cx, |item, _| {
10891            assert_eq!(
10892                item.save_count, 1,
10893                "Blurring should trigger autosave when focus was on a child of the item"
10894            );
10895        });
10896
10897        // Deactivating the window should also trigger autosave when a child of
10898        // the multibuffer item currently owns focus.
10899        item.update_in(cx, |item, window, cx| {
10900            item.is_dirty = true;
10901            window.focus(&item.child_focus_handles[0], cx);
10902        });
10903        cx.executor().run_until_parked();
10904        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10905
10906        cx.deactivate_window();
10907        item.read_with(cx, |item, _| {
10908            assert_eq!(
10909                item.save_count, 2,
10910                "Deactivating window should trigger autosave when focus was on a child"
10911            );
10912        });
10913    }
10914
10915    #[gpui::test]
10916    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10917        init_test(cx);
10918
10919        let fs = FakeFs::new(cx.executor());
10920
10921        let project = Project::test(fs, [], cx).await;
10922        let (workspace, cx) =
10923            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10924
10925        let item = cx.new(|cx| {
10926            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10927        });
10928        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10929        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10930        let toolbar_notify_count = Rc::new(RefCell::new(0));
10931
10932        workspace.update_in(cx, |workspace, window, cx| {
10933            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10934            let toolbar_notification_count = toolbar_notify_count.clone();
10935            cx.observe_in(&toolbar, window, move |_, _, _, _| {
10936                *toolbar_notification_count.borrow_mut() += 1
10937            })
10938            .detach();
10939        });
10940
10941        pane.read_with(cx, |pane, _| {
10942            assert!(!pane.can_navigate_backward());
10943            assert!(!pane.can_navigate_forward());
10944        });
10945
10946        item.update_in(cx, |item, _, cx| {
10947            item.set_state("one".to_string(), cx);
10948        });
10949
10950        // Toolbar must be notified to re-render the navigation buttons
10951        assert_eq!(*toolbar_notify_count.borrow(), 1);
10952
10953        pane.read_with(cx, |pane, _| {
10954            assert!(pane.can_navigate_backward());
10955            assert!(!pane.can_navigate_forward());
10956        });
10957
10958        workspace
10959            .update_in(cx, |workspace, window, cx| {
10960                workspace.go_back(pane.downgrade(), window, cx)
10961            })
10962            .await
10963            .unwrap();
10964
10965        assert_eq!(*toolbar_notify_count.borrow(), 2);
10966        pane.read_with(cx, |pane, _| {
10967            assert!(!pane.can_navigate_backward());
10968            assert!(pane.can_navigate_forward());
10969        });
10970    }
10971
10972    #[gpui::test]
10973    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
10974        init_test(cx);
10975        let fs = FakeFs::new(cx.executor());
10976        let project = Project::test(fs, [], cx).await;
10977        let (multi_workspace, cx) =
10978            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
10979        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
10980
10981        workspace.update_in(cx, |workspace, window, cx| {
10982            let first_item = cx.new(|cx| {
10983                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10984            });
10985            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
10986            workspace.split_pane(
10987                workspace.active_pane().clone(),
10988                SplitDirection::Right,
10989                window,
10990                cx,
10991            );
10992            workspace.split_pane(
10993                workspace.active_pane().clone(),
10994                SplitDirection::Right,
10995                window,
10996                cx,
10997            );
10998        });
10999
11000        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11001            let panes = workspace.center.panes();
11002            assert!(panes.len() >= 2);
11003            (
11004                panes.first().expect("at least one pane").entity_id(),
11005                panes.last().expect("at least one pane").entity_id(),
11006            )
11007        });
11008
11009        workspace.update_in(cx, |workspace, window, cx| {
11010            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11011        });
11012        workspace.update(cx, |workspace, _| {
11013            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11014            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11015        });
11016
11017        cx.dispatch_action(ActivateLastPane);
11018
11019        workspace.update(cx, |workspace, _| {
11020            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11021        });
11022    }
11023
11024    #[gpui::test]
11025    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11026        init_test(cx);
11027        let fs = FakeFs::new(cx.executor());
11028
11029        let project = Project::test(fs, [], cx).await;
11030        let (workspace, cx) =
11031            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11032
11033        let panel = workspace.update_in(cx, |workspace, window, cx| {
11034            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11035            workspace.add_panel(panel.clone(), window, cx);
11036
11037            workspace
11038                .right_dock()
11039                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11040
11041            panel
11042        });
11043
11044        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11045        pane.update_in(cx, |pane, window, cx| {
11046            let item = cx.new(TestItem::new);
11047            pane.add_item(Box::new(item), true, true, None, window, cx);
11048        });
11049
11050        // Transfer focus from center to panel
11051        workspace.update_in(cx, |workspace, window, cx| {
11052            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11053        });
11054
11055        workspace.update_in(cx, |workspace, window, cx| {
11056            assert!(workspace.right_dock().read(cx).is_open());
11057            assert!(!panel.is_zoomed(window, cx));
11058            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11059        });
11060
11061        // Transfer focus from panel to center
11062        workspace.update_in(cx, |workspace, window, cx| {
11063            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11064        });
11065
11066        workspace.update_in(cx, |workspace, window, cx| {
11067            assert!(workspace.right_dock().read(cx).is_open());
11068            assert!(!panel.is_zoomed(window, cx));
11069            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11070        });
11071
11072        // Close the dock
11073        workspace.update_in(cx, |workspace, window, cx| {
11074            workspace.toggle_dock(DockPosition::Right, window, cx);
11075        });
11076
11077        workspace.update_in(cx, |workspace, window, cx| {
11078            assert!(!workspace.right_dock().read(cx).is_open());
11079            assert!(!panel.is_zoomed(window, cx));
11080            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11081        });
11082
11083        // Open the dock
11084        workspace.update_in(cx, |workspace, window, cx| {
11085            workspace.toggle_dock(DockPosition::Right, window, cx);
11086        });
11087
11088        workspace.update_in(cx, |workspace, window, cx| {
11089            assert!(workspace.right_dock().read(cx).is_open());
11090            assert!(!panel.is_zoomed(window, cx));
11091            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11092        });
11093
11094        // Focus and zoom panel
11095        panel.update_in(cx, |panel, window, cx| {
11096            cx.focus_self(window);
11097            panel.set_zoomed(true, window, cx)
11098        });
11099
11100        workspace.update_in(cx, |workspace, window, cx| {
11101            assert!(workspace.right_dock().read(cx).is_open());
11102            assert!(panel.is_zoomed(window, cx));
11103            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11104        });
11105
11106        // Transfer focus to the center closes the dock
11107        workspace.update_in(cx, |workspace, window, cx| {
11108            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11109        });
11110
11111        workspace.update_in(cx, |workspace, window, cx| {
11112            assert!(!workspace.right_dock().read(cx).is_open());
11113            assert!(panel.is_zoomed(window, cx));
11114            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11115        });
11116
11117        // Transferring focus back to the panel keeps it zoomed
11118        workspace.update_in(cx, |workspace, window, cx| {
11119            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11120        });
11121
11122        workspace.update_in(cx, |workspace, window, cx| {
11123            assert!(workspace.right_dock().read(cx).is_open());
11124            assert!(panel.is_zoomed(window, cx));
11125            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11126        });
11127
11128        // Close the dock while it is zoomed
11129        workspace.update_in(cx, |workspace, window, cx| {
11130            workspace.toggle_dock(DockPosition::Right, window, cx)
11131        });
11132
11133        workspace.update_in(cx, |workspace, window, cx| {
11134            assert!(!workspace.right_dock().read(cx).is_open());
11135            assert!(panel.is_zoomed(window, cx));
11136            assert!(workspace.zoomed.is_none());
11137            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11138        });
11139
11140        // Opening the dock, when it's zoomed, retains focus
11141        workspace.update_in(cx, |workspace, window, cx| {
11142            workspace.toggle_dock(DockPosition::Right, window, cx)
11143        });
11144
11145        workspace.update_in(cx, |workspace, window, cx| {
11146            assert!(workspace.right_dock().read(cx).is_open());
11147            assert!(panel.is_zoomed(window, cx));
11148            assert!(workspace.zoomed.is_some());
11149            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11150        });
11151
11152        // Unzoom and close the panel, zoom the active pane.
11153        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11154        workspace.update_in(cx, |workspace, window, cx| {
11155            workspace.toggle_dock(DockPosition::Right, window, cx)
11156        });
11157        pane.update_in(cx, |pane, window, cx| {
11158            pane.toggle_zoom(&Default::default(), window, cx)
11159        });
11160
11161        // Opening a dock unzooms the pane.
11162        workspace.update_in(cx, |workspace, window, cx| {
11163            workspace.toggle_dock(DockPosition::Right, window, cx)
11164        });
11165        workspace.update_in(cx, |workspace, window, cx| {
11166            let pane = pane.read(cx);
11167            assert!(!pane.is_zoomed());
11168            assert!(!pane.focus_handle(cx).is_focused(window));
11169            assert!(workspace.right_dock().read(cx).is_open());
11170            assert!(workspace.zoomed.is_none());
11171        });
11172    }
11173
11174    #[gpui::test]
11175    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11176        init_test(cx);
11177        let fs = FakeFs::new(cx.executor());
11178
11179        let project = Project::test(fs, [], cx).await;
11180        let (workspace, cx) =
11181            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11182
11183        let panel = workspace.update_in(cx, |workspace, window, cx| {
11184            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11185            workspace.add_panel(panel.clone(), window, cx);
11186            panel
11187        });
11188
11189        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11190        pane.update_in(cx, |pane, window, cx| {
11191            let item = cx.new(TestItem::new);
11192            pane.add_item(Box::new(item), true, true, None, window, cx);
11193        });
11194
11195        // Enable close_panel_on_toggle
11196        cx.update_global(|store: &mut SettingsStore, cx| {
11197            store.update_user_settings(cx, |settings| {
11198                settings.workspace.close_panel_on_toggle = Some(true);
11199            });
11200        });
11201
11202        // Panel starts closed. Toggling should open and focus it.
11203        workspace.update_in(cx, |workspace, window, cx| {
11204            assert!(!workspace.right_dock().read(cx).is_open());
11205            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11206        });
11207
11208        workspace.update_in(cx, |workspace, window, cx| {
11209            assert!(
11210                workspace.right_dock().read(cx).is_open(),
11211                "Dock should be open after toggling from center"
11212            );
11213            assert!(
11214                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11215                "Panel should be focused after toggling from center"
11216            );
11217        });
11218
11219        // Panel is open and focused. Toggling should close the panel and
11220        // return focus to the center.
11221        workspace.update_in(cx, |workspace, window, cx| {
11222            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11223        });
11224
11225        workspace.update_in(cx, |workspace, window, cx| {
11226            assert!(
11227                !workspace.right_dock().read(cx).is_open(),
11228                "Dock should be closed after toggling from focused panel"
11229            );
11230            assert!(
11231                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11232                "Panel should not be focused after toggling from focused panel"
11233            );
11234        });
11235
11236        // Open the dock and focus something else so the panel is open but not
11237        // focused. Toggling should focus the panel (not close it).
11238        workspace.update_in(cx, |workspace, window, cx| {
11239            workspace
11240                .right_dock()
11241                .update(cx, |dock, cx| dock.set_open(true, window, cx));
11242            window.focus(&pane.read(cx).focus_handle(cx), cx);
11243        });
11244
11245        workspace.update_in(cx, |workspace, window, cx| {
11246            assert!(workspace.right_dock().read(cx).is_open());
11247            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11248            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11249        });
11250
11251        workspace.update_in(cx, |workspace, window, cx| {
11252            assert!(
11253                workspace.right_dock().read(cx).is_open(),
11254                "Dock should remain open when toggling focuses an open-but-unfocused panel"
11255            );
11256            assert!(
11257                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11258                "Panel should be focused after toggling an open-but-unfocused panel"
11259            );
11260        });
11261
11262        // Now disable the setting and verify the original behavior: toggling
11263        // from a focused panel moves focus to center but leaves the dock open.
11264        cx.update_global(|store: &mut SettingsStore, cx| {
11265            store.update_user_settings(cx, |settings| {
11266                settings.workspace.close_panel_on_toggle = Some(false);
11267            });
11268        });
11269
11270        workspace.update_in(cx, |workspace, window, cx| {
11271            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11272        });
11273
11274        workspace.update_in(cx, |workspace, window, cx| {
11275            assert!(
11276                workspace.right_dock().read(cx).is_open(),
11277                "Dock should remain open when setting is disabled"
11278            );
11279            assert!(
11280                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11281                "Panel should not be focused after toggling with setting disabled"
11282            );
11283        });
11284    }
11285
11286    #[gpui::test]
11287    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11288        init_test(cx);
11289        let fs = FakeFs::new(cx.executor());
11290
11291        let project = Project::test(fs, [], cx).await;
11292        let (workspace, cx) =
11293            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11294
11295        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11296            workspace.active_pane().clone()
11297        });
11298
11299        // Add an item to the pane so it can be zoomed
11300        workspace.update_in(cx, |workspace, window, cx| {
11301            let item = cx.new(TestItem::new);
11302            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11303        });
11304
11305        // Initially not zoomed
11306        workspace.update_in(cx, |workspace, _window, cx| {
11307            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11308            assert!(
11309                workspace.zoomed.is_none(),
11310                "Workspace should track no zoomed pane"
11311            );
11312            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11313        });
11314
11315        // Zoom In
11316        pane.update_in(cx, |pane, window, cx| {
11317            pane.zoom_in(&crate::ZoomIn, window, cx);
11318        });
11319
11320        workspace.update_in(cx, |workspace, window, cx| {
11321            assert!(
11322                pane.read(cx).is_zoomed(),
11323                "Pane should be zoomed after ZoomIn"
11324            );
11325            assert!(
11326                workspace.zoomed.is_some(),
11327                "Workspace should track the zoomed pane"
11328            );
11329            assert!(
11330                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11331                "ZoomIn should focus the pane"
11332            );
11333        });
11334
11335        // Zoom In again is a no-op
11336        pane.update_in(cx, |pane, window, cx| {
11337            pane.zoom_in(&crate::ZoomIn, window, cx);
11338        });
11339
11340        workspace.update_in(cx, |workspace, window, cx| {
11341            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11342            assert!(
11343                workspace.zoomed.is_some(),
11344                "Workspace still tracks zoomed pane"
11345            );
11346            assert!(
11347                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11348                "Pane remains focused after repeated ZoomIn"
11349            );
11350        });
11351
11352        // Zoom Out
11353        pane.update_in(cx, |pane, window, cx| {
11354            pane.zoom_out(&crate::ZoomOut, window, cx);
11355        });
11356
11357        workspace.update_in(cx, |workspace, _window, cx| {
11358            assert!(
11359                !pane.read(cx).is_zoomed(),
11360                "Pane should unzoom after ZoomOut"
11361            );
11362            assert!(
11363                workspace.zoomed.is_none(),
11364                "Workspace clears zoom tracking after ZoomOut"
11365            );
11366        });
11367
11368        // Zoom Out again is a no-op
11369        pane.update_in(cx, |pane, window, cx| {
11370            pane.zoom_out(&crate::ZoomOut, window, cx);
11371        });
11372
11373        workspace.update_in(cx, |workspace, _window, cx| {
11374            assert!(
11375                !pane.read(cx).is_zoomed(),
11376                "Second ZoomOut keeps pane unzoomed"
11377            );
11378            assert!(
11379                workspace.zoomed.is_none(),
11380                "Workspace remains without zoomed pane"
11381            );
11382        });
11383    }
11384
11385    #[gpui::test]
11386    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11387        init_test(cx);
11388        let fs = FakeFs::new(cx.executor());
11389
11390        let project = Project::test(fs, [], cx).await;
11391        let (workspace, cx) =
11392            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11393        workspace.update_in(cx, |workspace, window, cx| {
11394            // Open two docks
11395            let left_dock = workspace.dock_at_position(DockPosition::Left);
11396            let right_dock = workspace.dock_at_position(DockPosition::Right);
11397
11398            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11399            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11400
11401            assert!(left_dock.read(cx).is_open());
11402            assert!(right_dock.read(cx).is_open());
11403        });
11404
11405        workspace.update_in(cx, |workspace, window, cx| {
11406            // Toggle all docks - should close both
11407            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11408
11409            let left_dock = workspace.dock_at_position(DockPosition::Left);
11410            let right_dock = workspace.dock_at_position(DockPosition::Right);
11411            assert!(!left_dock.read(cx).is_open());
11412            assert!(!right_dock.read(cx).is_open());
11413        });
11414
11415        workspace.update_in(cx, |workspace, window, cx| {
11416            // Toggle again - should reopen both
11417            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11418
11419            let left_dock = workspace.dock_at_position(DockPosition::Left);
11420            let right_dock = workspace.dock_at_position(DockPosition::Right);
11421            assert!(left_dock.read(cx).is_open());
11422            assert!(right_dock.read(cx).is_open());
11423        });
11424    }
11425
11426    #[gpui::test]
11427    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11428        init_test(cx);
11429        let fs = FakeFs::new(cx.executor());
11430
11431        let project = Project::test(fs, [], cx).await;
11432        let (workspace, cx) =
11433            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11434        workspace.update_in(cx, |workspace, window, cx| {
11435            // Open two docks
11436            let left_dock = workspace.dock_at_position(DockPosition::Left);
11437            let right_dock = workspace.dock_at_position(DockPosition::Right);
11438
11439            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11440            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11441
11442            assert!(left_dock.read(cx).is_open());
11443            assert!(right_dock.read(cx).is_open());
11444        });
11445
11446        workspace.update_in(cx, |workspace, window, cx| {
11447            // Close them manually
11448            workspace.toggle_dock(DockPosition::Left, window, cx);
11449            workspace.toggle_dock(DockPosition::Right, window, cx);
11450
11451            let left_dock = workspace.dock_at_position(DockPosition::Left);
11452            let right_dock = workspace.dock_at_position(DockPosition::Right);
11453            assert!(!left_dock.read(cx).is_open());
11454            assert!(!right_dock.read(cx).is_open());
11455        });
11456
11457        workspace.update_in(cx, |workspace, window, cx| {
11458            // Toggle all docks - only last closed (right dock) should reopen
11459            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11460
11461            let left_dock = workspace.dock_at_position(DockPosition::Left);
11462            let right_dock = workspace.dock_at_position(DockPosition::Right);
11463            assert!(!left_dock.read(cx).is_open());
11464            assert!(right_dock.read(cx).is_open());
11465        });
11466    }
11467
11468    #[gpui::test]
11469    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11470        init_test(cx);
11471        let fs = FakeFs::new(cx.executor());
11472        let project = Project::test(fs, [], cx).await;
11473        let (multi_workspace, cx) =
11474            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11475        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11476
11477        // Open two docks (left and right) with one panel each
11478        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11479            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11480            workspace.add_panel(left_panel.clone(), window, cx);
11481
11482            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11483            workspace.add_panel(right_panel.clone(), window, cx);
11484
11485            workspace.toggle_dock(DockPosition::Left, window, cx);
11486            workspace.toggle_dock(DockPosition::Right, window, cx);
11487
11488            // Verify initial state
11489            assert!(
11490                workspace.left_dock().read(cx).is_open(),
11491                "Left dock should be open"
11492            );
11493            assert_eq!(
11494                workspace
11495                    .left_dock()
11496                    .read(cx)
11497                    .visible_panel()
11498                    .unwrap()
11499                    .panel_id(),
11500                left_panel.panel_id(),
11501                "Left panel should be visible in left dock"
11502            );
11503            assert!(
11504                workspace.right_dock().read(cx).is_open(),
11505                "Right dock should be open"
11506            );
11507            assert_eq!(
11508                workspace
11509                    .right_dock()
11510                    .read(cx)
11511                    .visible_panel()
11512                    .unwrap()
11513                    .panel_id(),
11514                right_panel.panel_id(),
11515                "Right panel should be visible in right dock"
11516            );
11517            assert!(
11518                !workspace.bottom_dock().read(cx).is_open(),
11519                "Bottom dock should be closed"
11520            );
11521
11522            (left_panel, right_panel)
11523        });
11524
11525        // Focus the left panel and move it to the next position (bottom dock)
11526        workspace.update_in(cx, |workspace, window, cx| {
11527            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11528            assert!(
11529                left_panel.read(cx).focus_handle(cx).is_focused(window),
11530                "Left panel should be focused"
11531            );
11532        });
11533
11534        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11535
11536        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11537        workspace.update(cx, |workspace, cx| {
11538            assert!(
11539                !workspace.left_dock().read(cx).is_open(),
11540                "Left dock should be closed"
11541            );
11542            assert!(
11543                workspace.bottom_dock().read(cx).is_open(),
11544                "Bottom dock should now be open"
11545            );
11546            assert_eq!(
11547                left_panel.read(cx).position,
11548                DockPosition::Bottom,
11549                "Left panel should now be in the bottom dock"
11550            );
11551            assert_eq!(
11552                workspace
11553                    .bottom_dock()
11554                    .read(cx)
11555                    .visible_panel()
11556                    .unwrap()
11557                    .panel_id(),
11558                left_panel.panel_id(),
11559                "Left panel should be the visible panel in the bottom dock"
11560            );
11561        });
11562
11563        // Toggle all docks off
11564        workspace.update_in(cx, |workspace, window, cx| {
11565            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11566            assert!(
11567                !workspace.left_dock().read(cx).is_open(),
11568                "Left dock should be closed"
11569            );
11570            assert!(
11571                !workspace.right_dock().read(cx).is_open(),
11572                "Right dock should be closed"
11573            );
11574            assert!(
11575                !workspace.bottom_dock().read(cx).is_open(),
11576                "Bottom dock should be closed"
11577            );
11578        });
11579
11580        // Toggle all docks back on and verify positions are restored
11581        workspace.update_in(cx, |workspace, window, cx| {
11582            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11583            assert!(
11584                !workspace.left_dock().read(cx).is_open(),
11585                "Left dock should remain closed"
11586            );
11587            assert!(
11588                workspace.right_dock().read(cx).is_open(),
11589                "Right dock should remain open"
11590            );
11591            assert!(
11592                workspace.bottom_dock().read(cx).is_open(),
11593                "Bottom dock should remain open"
11594            );
11595            assert_eq!(
11596                left_panel.read(cx).position,
11597                DockPosition::Bottom,
11598                "Left panel should remain in the bottom dock"
11599            );
11600            assert_eq!(
11601                right_panel.read(cx).position,
11602                DockPosition::Right,
11603                "Right panel should remain in the right dock"
11604            );
11605            assert_eq!(
11606                workspace
11607                    .bottom_dock()
11608                    .read(cx)
11609                    .visible_panel()
11610                    .unwrap()
11611                    .panel_id(),
11612                left_panel.panel_id(),
11613                "Left panel should be the visible panel in the right dock"
11614            );
11615        });
11616    }
11617
11618    #[gpui::test]
11619    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11620        init_test(cx);
11621
11622        let fs = FakeFs::new(cx.executor());
11623
11624        let project = Project::test(fs, None, cx).await;
11625        let (workspace, cx) =
11626            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11627
11628        // Let's arrange the panes like this:
11629        //
11630        // +-----------------------+
11631        // |         top           |
11632        // +------+--------+-------+
11633        // | left | center | right |
11634        // +------+--------+-------+
11635        // |        bottom         |
11636        // +-----------------------+
11637
11638        let top_item = cx.new(|cx| {
11639            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11640        });
11641        let bottom_item = cx.new(|cx| {
11642            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11643        });
11644        let left_item = cx.new(|cx| {
11645            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11646        });
11647        let right_item = cx.new(|cx| {
11648            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11649        });
11650        let center_item = cx.new(|cx| {
11651            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11652        });
11653
11654        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11655            let top_pane_id = workspace.active_pane().entity_id();
11656            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11657            workspace.split_pane(
11658                workspace.active_pane().clone(),
11659                SplitDirection::Down,
11660                window,
11661                cx,
11662            );
11663            top_pane_id
11664        });
11665        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11666            let bottom_pane_id = workspace.active_pane().entity_id();
11667            workspace.add_item_to_active_pane(
11668                Box::new(bottom_item.clone()),
11669                None,
11670                false,
11671                window,
11672                cx,
11673            );
11674            workspace.split_pane(
11675                workspace.active_pane().clone(),
11676                SplitDirection::Up,
11677                window,
11678                cx,
11679            );
11680            bottom_pane_id
11681        });
11682        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11683            let left_pane_id = workspace.active_pane().entity_id();
11684            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11685            workspace.split_pane(
11686                workspace.active_pane().clone(),
11687                SplitDirection::Right,
11688                window,
11689                cx,
11690            );
11691            left_pane_id
11692        });
11693        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11694            let right_pane_id = workspace.active_pane().entity_id();
11695            workspace.add_item_to_active_pane(
11696                Box::new(right_item.clone()),
11697                None,
11698                false,
11699                window,
11700                cx,
11701            );
11702            workspace.split_pane(
11703                workspace.active_pane().clone(),
11704                SplitDirection::Left,
11705                window,
11706                cx,
11707            );
11708            right_pane_id
11709        });
11710        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11711            let center_pane_id = workspace.active_pane().entity_id();
11712            workspace.add_item_to_active_pane(
11713                Box::new(center_item.clone()),
11714                None,
11715                false,
11716                window,
11717                cx,
11718            );
11719            center_pane_id
11720        });
11721        cx.executor().run_until_parked();
11722
11723        workspace.update_in(cx, |workspace, window, cx| {
11724            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11725
11726            // Join into next from center pane into right
11727            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11728        });
11729
11730        workspace.update_in(cx, |workspace, window, cx| {
11731            let active_pane = workspace.active_pane();
11732            assert_eq!(right_pane_id, active_pane.entity_id());
11733            assert_eq!(2, active_pane.read(cx).items_len());
11734            let item_ids_in_pane =
11735                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11736            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11737            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11738
11739            // Join into next from right pane into bottom
11740            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11741        });
11742
11743        workspace.update_in(cx, |workspace, window, cx| {
11744            let active_pane = workspace.active_pane();
11745            assert_eq!(bottom_pane_id, active_pane.entity_id());
11746            assert_eq!(3, active_pane.read(cx).items_len());
11747            let item_ids_in_pane =
11748                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11749            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11750            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11751            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11752
11753            // Join into next from bottom pane into left
11754            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11755        });
11756
11757        workspace.update_in(cx, |workspace, window, cx| {
11758            let active_pane = workspace.active_pane();
11759            assert_eq!(left_pane_id, active_pane.entity_id());
11760            assert_eq!(4, active_pane.read(cx).items_len());
11761            let item_ids_in_pane =
11762                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11763            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11764            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11765            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11766            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11767
11768            // Join into next from left pane into top
11769            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11770        });
11771
11772        workspace.update_in(cx, |workspace, window, cx| {
11773            let active_pane = workspace.active_pane();
11774            assert_eq!(top_pane_id, active_pane.entity_id());
11775            assert_eq!(5, active_pane.read(cx).items_len());
11776            let item_ids_in_pane =
11777                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11778            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11779            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11780            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11781            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11782            assert!(item_ids_in_pane.contains(&top_item.item_id()));
11783
11784            // Single pane left: no-op
11785            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11786        });
11787
11788        workspace.update(cx, |workspace, _cx| {
11789            let active_pane = workspace.active_pane();
11790            assert_eq!(top_pane_id, active_pane.entity_id());
11791        });
11792    }
11793
11794    fn add_an_item_to_active_pane(
11795        cx: &mut VisualTestContext,
11796        workspace: &Entity<Workspace>,
11797        item_id: u64,
11798    ) -> Entity<TestItem> {
11799        let item = cx.new(|cx| {
11800            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11801                item_id,
11802                "item{item_id}.txt",
11803                cx,
11804            )])
11805        });
11806        workspace.update_in(cx, |workspace, window, cx| {
11807            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11808        });
11809        item
11810    }
11811
11812    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11813        workspace.update_in(cx, |workspace, window, cx| {
11814            workspace.split_pane(
11815                workspace.active_pane().clone(),
11816                SplitDirection::Right,
11817                window,
11818                cx,
11819            )
11820        })
11821    }
11822
11823    #[gpui::test]
11824    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11825        init_test(cx);
11826        let fs = FakeFs::new(cx.executor());
11827        let project = Project::test(fs, None, cx).await;
11828        let (workspace, cx) =
11829            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11830
11831        add_an_item_to_active_pane(cx, &workspace, 1);
11832        split_pane(cx, &workspace);
11833        add_an_item_to_active_pane(cx, &workspace, 2);
11834        split_pane(cx, &workspace); // empty pane
11835        split_pane(cx, &workspace);
11836        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11837
11838        cx.executor().run_until_parked();
11839
11840        workspace.update(cx, |workspace, cx| {
11841            let num_panes = workspace.panes().len();
11842            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11843            let active_item = workspace
11844                .active_pane()
11845                .read(cx)
11846                .active_item()
11847                .expect("item is in focus");
11848
11849            assert_eq!(num_panes, 4);
11850            assert_eq!(num_items_in_current_pane, 1);
11851            assert_eq!(active_item.item_id(), last_item.item_id());
11852        });
11853
11854        workspace.update_in(cx, |workspace, window, cx| {
11855            workspace.join_all_panes(window, cx);
11856        });
11857
11858        workspace.update(cx, |workspace, cx| {
11859            let num_panes = workspace.panes().len();
11860            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11861            let active_item = workspace
11862                .active_pane()
11863                .read(cx)
11864                .active_item()
11865                .expect("item is in focus");
11866
11867            assert_eq!(num_panes, 1);
11868            assert_eq!(num_items_in_current_pane, 3);
11869            assert_eq!(active_item.item_id(), last_item.item_id());
11870        });
11871    }
11872    struct TestModal(FocusHandle);
11873
11874    impl TestModal {
11875        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11876            Self(cx.focus_handle())
11877        }
11878    }
11879
11880    impl EventEmitter<DismissEvent> for TestModal {}
11881
11882    impl Focusable for TestModal {
11883        fn focus_handle(&self, _cx: &App) -> FocusHandle {
11884            self.0.clone()
11885        }
11886    }
11887
11888    impl ModalView for TestModal {}
11889
11890    impl Render for TestModal {
11891        fn render(
11892            &mut self,
11893            _window: &mut Window,
11894            _cx: &mut Context<TestModal>,
11895        ) -> impl IntoElement {
11896            div().track_focus(&self.0)
11897        }
11898    }
11899
11900    #[gpui::test]
11901    async fn test_panels(cx: &mut gpui::TestAppContext) {
11902        init_test(cx);
11903        let fs = FakeFs::new(cx.executor());
11904
11905        let project = Project::test(fs, [], cx).await;
11906        let (multi_workspace, cx) =
11907            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11908        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11909
11910        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11911            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11912            workspace.add_panel(panel_1.clone(), window, cx);
11913            workspace.toggle_dock(DockPosition::Left, window, cx);
11914            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11915            workspace.add_panel(panel_2.clone(), window, cx);
11916            workspace.toggle_dock(DockPosition::Right, window, cx);
11917
11918            let left_dock = workspace.left_dock();
11919            assert_eq!(
11920                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11921                panel_1.panel_id()
11922            );
11923            assert_eq!(
11924                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11925                panel_1.size(window, cx)
11926            );
11927
11928            left_dock.update(cx, |left_dock, cx| {
11929                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11930            });
11931            assert_eq!(
11932                workspace
11933                    .right_dock()
11934                    .read(cx)
11935                    .visible_panel()
11936                    .unwrap()
11937                    .panel_id(),
11938                panel_2.panel_id(),
11939            );
11940
11941            (panel_1, panel_2)
11942        });
11943
11944        // Move panel_1 to the right
11945        panel_1.update_in(cx, |panel_1, window, cx| {
11946            panel_1.set_position(DockPosition::Right, window, cx)
11947        });
11948
11949        workspace.update_in(cx, |workspace, window, cx| {
11950            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11951            // Since it was the only panel on the left, the left dock should now be closed.
11952            assert!(!workspace.left_dock().read(cx).is_open());
11953            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11954            let right_dock = workspace.right_dock();
11955            assert_eq!(
11956                right_dock.read(cx).visible_panel().unwrap().panel_id(),
11957                panel_1.panel_id()
11958            );
11959            assert_eq!(
11960                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11961                px(1337.)
11962            );
11963
11964            // Now we move panel_2 to the left
11965            panel_2.set_position(DockPosition::Left, window, cx);
11966        });
11967
11968        workspace.update(cx, |workspace, cx| {
11969            // Since panel_2 was not visible on the right, we don't open the left dock.
11970            assert!(!workspace.left_dock().read(cx).is_open());
11971            // And the right dock is unaffected in its displaying of panel_1
11972            assert!(workspace.right_dock().read(cx).is_open());
11973            assert_eq!(
11974                workspace
11975                    .right_dock()
11976                    .read(cx)
11977                    .visible_panel()
11978                    .unwrap()
11979                    .panel_id(),
11980                panel_1.panel_id(),
11981            );
11982        });
11983
11984        // Move panel_1 back to the left
11985        panel_1.update_in(cx, |panel_1, window, cx| {
11986            panel_1.set_position(DockPosition::Left, window, cx)
11987        });
11988
11989        workspace.update_in(cx, |workspace, window, cx| {
11990            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11991            let left_dock = workspace.left_dock();
11992            assert!(left_dock.read(cx).is_open());
11993            assert_eq!(
11994                left_dock.read(cx).visible_panel().unwrap().panel_id(),
11995                panel_1.panel_id()
11996            );
11997            assert_eq!(
11998                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11999                px(1337.)
12000            );
12001            // And the right dock should be closed as it no longer has any panels.
12002            assert!(!workspace.right_dock().read(cx).is_open());
12003
12004            // Now we move panel_1 to the bottom
12005            panel_1.set_position(DockPosition::Bottom, window, cx);
12006        });
12007
12008        workspace.update_in(cx, |workspace, window, cx| {
12009            // Since panel_1 was visible on the left, we close the left dock.
12010            assert!(!workspace.left_dock().read(cx).is_open());
12011            // The bottom dock is sized based on the panel's default size,
12012            // since the panel orientation changed from vertical to horizontal.
12013            let bottom_dock = workspace.bottom_dock();
12014            assert_eq!(
12015                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
12016                panel_1.size(window, cx),
12017            );
12018            // Close bottom dock and move panel_1 back to the left.
12019            bottom_dock.update(cx, |bottom_dock, cx| {
12020                bottom_dock.set_open(false, window, cx)
12021            });
12022            panel_1.set_position(DockPosition::Left, window, cx);
12023        });
12024
12025        // Emit activated event on panel 1
12026        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12027
12028        // Now the left dock is open and panel_1 is active and focused.
12029        workspace.update_in(cx, |workspace, window, cx| {
12030            let left_dock = workspace.left_dock();
12031            assert!(left_dock.read(cx).is_open());
12032            assert_eq!(
12033                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12034                panel_1.panel_id(),
12035            );
12036            assert!(panel_1.focus_handle(cx).is_focused(window));
12037        });
12038
12039        // Emit closed event on panel 2, which is not active
12040        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12041
12042        // Wo don't close the left dock, because panel_2 wasn't the active panel
12043        workspace.update(cx, |workspace, cx| {
12044            let left_dock = workspace.left_dock();
12045            assert!(left_dock.read(cx).is_open());
12046            assert_eq!(
12047                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12048                panel_1.panel_id(),
12049            );
12050        });
12051
12052        // Emitting a ZoomIn event shows the panel as zoomed.
12053        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12054        workspace.read_with(cx, |workspace, _| {
12055            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12056            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12057        });
12058
12059        // Move panel to another dock while it is zoomed
12060        panel_1.update_in(cx, |panel, window, cx| {
12061            panel.set_position(DockPosition::Right, window, cx)
12062        });
12063        workspace.read_with(cx, |workspace, _| {
12064            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12065
12066            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12067        });
12068
12069        // This is a helper for getting a:
12070        // - valid focus on an element,
12071        // - that isn't a part of the panes and panels system of the Workspace,
12072        // - and doesn't trigger the 'on_focus_lost' API.
12073        let focus_other_view = {
12074            let workspace = workspace.clone();
12075            move |cx: &mut VisualTestContext| {
12076                workspace.update_in(cx, |workspace, window, cx| {
12077                    if workspace.active_modal::<TestModal>(cx).is_some() {
12078                        workspace.toggle_modal(window, cx, TestModal::new);
12079                        workspace.toggle_modal(window, cx, TestModal::new);
12080                    } else {
12081                        workspace.toggle_modal(window, cx, TestModal::new);
12082                    }
12083                })
12084            }
12085        };
12086
12087        // If focus is transferred to another view that's not a panel or another pane, we still show
12088        // the panel as zoomed.
12089        focus_other_view(cx);
12090        workspace.read_with(cx, |workspace, _| {
12091            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12092            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12093        });
12094
12095        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12096        workspace.update_in(cx, |_workspace, window, cx| {
12097            cx.focus_self(window);
12098        });
12099        workspace.read_with(cx, |workspace, _| {
12100            assert_eq!(workspace.zoomed, None);
12101            assert_eq!(workspace.zoomed_position, None);
12102        });
12103
12104        // If focus is transferred again to another view that's not a panel or a pane, we won't
12105        // show the panel as zoomed because it wasn't zoomed before.
12106        focus_other_view(cx);
12107        workspace.read_with(cx, |workspace, _| {
12108            assert_eq!(workspace.zoomed, None);
12109            assert_eq!(workspace.zoomed_position, None);
12110        });
12111
12112        // When the panel is activated, it is zoomed again.
12113        cx.dispatch_action(ToggleRightDock);
12114        workspace.read_with(cx, |workspace, _| {
12115            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12116            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12117        });
12118
12119        // Emitting a ZoomOut event unzooms the panel.
12120        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12121        workspace.read_with(cx, |workspace, _| {
12122            assert_eq!(workspace.zoomed, None);
12123            assert_eq!(workspace.zoomed_position, None);
12124        });
12125
12126        // Emit closed event on panel 1, which is active
12127        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12128
12129        // Now the left dock is closed, because panel_1 was the active panel
12130        workspace.update(cx, |workspace, cx| {
12131            let right_dock = workspace.right_dock();
12132            assert!(!right_dock.read(cx).is_open());
12133        });
12134    }
12135
12136    #[gpui::test]
12137    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12138        init_test(cx);
12139
12140        let fs = FakeFs::new(cx.background_executor.clone());
12141        let project = Project::test(fs, [], cx).await;
12142        let (workspace, cx) =
12143            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12144        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12145
12146        let dirty_regular_buffer = cx.new(|cx| {
12147            TestItem::new(cx)
12148                .with_dirty(true)
12149                .with_label("1.txt")
12150                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12151        });
12152        let dirty_regular_buffer_2 = cx.new(|cx| {
12153            TestItem::new(cx)
12154                .with_dirty(true)
12155                .with_label("2.txt")
12156                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12157        });
12158        let dirty_multi_buffer_with_both = cx.new(|cx| {
12159            TestItem::new(cx)
12160                .with_dirty(true)
12161                .with_buffer_kind(ItemBufferKind::Multibuffer)
12162                .with_label("Fake Project Search")
12163                .with_project_items(&[
12164                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12165                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12166                ])
12167        });
12168        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12169        workspace.update_in(cx, |workspace, window, cx| {
12170            workspace.add_item(
12171                pane.clone(),
12172                Box::new(dirty_regular_buffer.clone()),
12173                None,
12174                false,
12175                false,
12176                window,
12177                cx,
12178            );
12179            workspace.add_item(
12180                pane.clone(),
12181                Box::new(dirty_regular_buffer_2.clone()),
12182                None,
12183                false,
12184                false,
12185                window,
12186                cx,
12187            );
12188            workspace.add_item(
12189                pane.clone(),
12190                Box::new(dirty_multi_buffer_with_both.clone()),
12191                None,
12192                false,
12193                false,
12194                window,
12195                cx,
12196            );
12197        });
12198
12199        pane.update_in(cx, |pane, window, cx| {
12200            pane.activate_item(2, true, true, window, cx);
12201            assert_eq!(
12202                pane.active_item().unwrap().item_id(),
12203                multi_buffer_with_both_files_id,
12204                "Should select the multi buffer in the pane"
12205            );
12206        });
12207        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12208            pane.close_other_items(
12209                &CloseOtherItems {
12210                    save_intent: Some(SaveIntent::Save),
12211                    close_pinned: true,
12212                },
12213                None,
12214                window,
12215                cx,
12216            )
12217        });
12218        cx.background_executor.run_until_parked();
12219        assert!(!cx.has_pending_prompt());
12220        close_all_but_multi_buffer_task
12221            .await
12222            .expect("Closing all buffers but the multi buffer failed");
12223        pane.update(cx, |pane, cx| {
12224            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12225            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12226            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12227            assert_eq!(pane.items_len(), 1);
12228            assert_eq!(
12229                pane.active_item().unwrap().item_id(),
12230                multi_buffer_with_both_files_id,
12231                "Should have only the multi buffer left in the pane"
12232            );
12233            assert!(
12234                dirty_multi_buffer_with_both.read(cx).is_dirty,
12235                "The multi buffer containing the unsaved buffer should still be dirty"
12236            );
12237        });
12238
12239        dirty_regular_buffer.update(cx, |buffer, cx| {
12240            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12241        });
12242
12243        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12244            pane.close_active_item(
12245                &CloseActiveItem {
12246                    save_intent: Some(SaveIntent::Close),
12247                    close_pinned: false,
12248                },
12249                window,
12250                cx,
12251            )
12252        });
12253        cx.background_executor.run_until_parked();
12254        assert!(
12255            cx.has_pending_prompt(),
12256            "Dirty multi buffer should prompt a save dialog"
12257        );
12258        cx.simulate_prompt_answer("Save");
12259        cx.background_executor.run_until_parked();
12260        close_multi_buffer_task
12261            .await
12262            .expect("Closing the multi buffer failed");
12263        pane.update(cx, |pane, cx| {
12264            assert_eq!(
12265                dirty_multi_buffer_with_both.read(cx).save_count,
12266                1,
12267                "Multi buffer item should get be saved"
12268            );
12269            // Test impl does not save inner items, so we do not assert them
12270            assert_eq!(
12271                pane.items_len(),
12272                0,
12273                "No more items should be left in the pane"
12274            );
12275            assert!(pane.active_item().is_none());
12276        });
12277    }
12278
12279    #[gpui::test]
12280    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12281        cx: &mut TestAppContext,
12282    ) {
12283        init_test(cx);
12284
12285        let fs = FakeFs::new(cx.background_executor.clone());
12286        let project = Project::test(fs, [], cx).await;
12287        let (workspace, cx) =
12288            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12289        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12290
12291        let dirty_regular_buffer = cx.new(|cx| {
12292            TestItem::new(cx)
12293                .with_dirty(true)
12294                .with_label("1.txt")
12295                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12296        });
12297        let dirty_regular_buffer_2 = cx.new(|cx| {
12298            TestItem::new(cx)
12299                .with_dirty(true)
12300                .with_label("2.txt")
12301                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12302        });
12303        let clear_regular_buffer = cx.new(|cx| {
12304            TestItem::new(cx)
12305                .with_label("3.txt")
12306                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12307        });
12308
12309        let dirty_multi_buffer_with_both = cx.new(|cx| {
12310            TestItem::new(cx)
12311                .with_dirty(true)
12312                .with_buffer_kind(ItemBufferKind::Multibuffer)
12313                .with_label("Fake Project Search")
12314                .with_project_items(&[
12315                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12316                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12317                    clear_regular_buffer.read(cx).project_items[0].clone(),
12318                ])
12319        });
12320        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12321        workspace.update_in(cx, |workspace, window, cx| {
12322            workspace.add_item(
12323                pane.clone(),
12324                Box::new(dirty_regular_buffer.clone()),
12325                None,
12326                false,
12327                false,
12328                window,
12329                cx,
12330            );
12331            workspace.add_item(
12332                pane.clone(),
12333                Box::new(dirty_multi_buffer_with_both.clone()),
12334                None,
12335                false,
12336                false,
12337                window,
12338                cx,
12339            );
12340        });
12341
12342        pane.update_in(cx, |pane, window, cx| {
12343            pane.activate_item(1, true, true, window, cx);
12344            assert_eq!(
12345                pane.active_item().unwrap().item_id(),
12346                multi_buffer_with_both_files_id,
12347                "Should select the multi buffer in the pane"
12348            );
12349        });
12350        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12351            pane.close_active_item(
12352                &CloseActiveItem {
12353                    save_intent: None,
12354                    close_pinned: false,
12355                },
12356                window,
12357                cx,
12358            )
12359        });
12360        cx.background_executor.run_until_parked();
12361        assert!(
12362            cx.has_pending_prompt(),
12363            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12364        );
12365    }
12366
12367    /// Tests that when `close_on_file_delete` is enabled, files are automatically
12368    /// closed when they are deleted from disk.
12369    #[gpui::test]
12370    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12371        init_test(cx);
12372
12373        // Enable the close_on_disk_deletion setting
12374        cx.update_global(|store: &mut SettingsStore, cx| {
12375            store.update_user_settings(cx, |settings| {
12376                settings.workspace.close_on_file_delete = Some(true);
12377            });
12378        });
12379
12380        let fs = FakeFs::new(cx.background_executor.clone());
12381        let project = Project::test(fs, [], cx).await;
12382        let (workspace, cx) =
12383            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12384        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12385
12386        // Create a test item that simulates a file
12387        let item = cx.new(|cx| {
12388            TestItem::new(cx)
12389                .with_label("test.txt")
12390                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12391        });
12392
12393        // Add item to workspace
12394        workspace.update_in(cx, |workspace, window, cx| {
12395            workspace.add_item(
12396                pane.clone(),
12397                Box::new(item.clone()),
12398                None,
12399                false,
12400                false,
12401                window,
12402                cx,
12403            );
12404        });
12405
12406        // Verify the item is in the pane
12407        pane.read_with(cx, |pane, _| {
12408            assert_eq!(pane.items().count(), 1);
12409        });
12410
12411        // Simulate file deletion by setting the item's deleted state
12412        item.update(cx, |item, _| {
12413            item.set_has_deleted_file(true);
12414        });
12415
12416        // Emit UpdateTab event to trigger the close behavior
12417        cx.run_until_parked();
12418        item.update(cx, |_, cx| {
12419            cx.emit(ItemEvent::UpdateTab);
12420        });
12421
12422        // Allow the close operation to complete
12423        cx.run_until_parked();
12424
12425        // Verify the item was automatically closed
12426        pane.read_with(cx, |pane, _| {
12427            assert_eq!(
12428                pane.items().count(),
12429                0,
12430                "Item should be automatically closed when file is deleted"
12431            );
12432        });
12433    }
12434
12435    /// Tests that when `close_on_file_delete` is disabled (default), files remain
12436    /// open with a strikethrough when they are deleted from disk.
12437    #[gpui::test]
12438    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12439        init_test(cx);
12440
12441        // Ensure close_on_disk_deletion is disabled (default)
12442        cx.update_global(|store: &mut SettingsStore, cx| {
12443            store.update_user_settings(cx, |settings| {
12444                settings.workspace.close_on_file_delete = Some(false);
12445            });
12446        });
12447
12448        let fs = FakeFs::new(cx.background_executor.clone());
12449        let project = Project::test(fs, [], cx).await;
12450        let (workspace, cx) =
12451            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12452        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12453
12454        // Create a test item that simulates a file
12455        let item = cx.new(|cx| {
12456            TestItem::new(cx)
12457                .with_label("test.txt")
12458                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12459        });
12460
12461        // Add item to workspace
12462        workspace.update_in(cx, |workspace, window, cx| {
12463            workspace.add_item(
12464                pane.clone(),
12465                Box::new(item.clone()),
12466                None,
12467                false,
12468                false,
12469                window,
12470                cx,
12471            );
12472        });
12473
12474        // Verify the item is in the pane
12475        pane.read_with(cx, |pane, _| {
12476            assert_eq!(pane.items().count(), 1);
12477        });
12478
12479        // Simulate file deletion
12480        item.update(cx, |item, _| {
12481            item.set_has_deleted_file(true);
12482        });
12483
12484        // Emit UpdateTab event
12485        cx.run_until_parked();
12486        item.update(cx, |_, cx| {
12487            cx.emit(ItemEvent::UpdateTab);
12488        });
12489
12490        // Allow any potential close operation to complete
12491        cx.run_until_parked();
12492
12493        // Verify the item remains open (with strikethrough)
12494        pane.read_with(cx, |pane, _| {
12495            assert_eq!(
12496                pane.items().count(),
12497                1,
12498                "Item should remain open when close_on_disk_deletion is disabled"
12499            );
12500        });
12501
12502        // Verify the item shows as deleted
12503        item.read_with(cx, |item, _| {
12504            assert!(
12505                item.has_deleted_file,
12506                "Item should be marked as having deleted file"
12507            );
12508        });
12509    }
12510
12511    /// Tests that dirty files are not automatically closed when deleted from disk,
12512    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12513    /// unsaved changes without being prompted.
12514    #[gpui::test]
12515    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12516        init_test(cx);
12517
12518        // Enable the close_on_file_delete setting
12519        cx.update_global(|store: &mut SettingsStore, cx| {
12520            store.update_user_settings(cx, |settings| {
12521                settings.workspace.close_on_file_delete = Some(true);
12522            });
12523        });
12524
12525        let fs = FakeFs::new(cx.background_executor.clone());
12526        let project = Project::test(fs, [], cx).await;
12527        let (workspace, cx) =
12528            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12529        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12530
12531        // Create a dirty test item
12532        let item = cx.new(|cx| {
12533            TestItem::new(cx)
12534                .with_dirty(true)
12535                .with_label("test.txt")
12536                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12537        });
12538
12539        // Add item to workspace
12540        workspace.update_in(cx, |workspace, window, cx| {
12541            workspace.add_item(
12542                pane.clone(),
12543                Box::new(item.clone()),
12544                None,
12545                false,
12546                false,
12547                window,
12548                cx,
12549            );
12550        });
12551
12552        // Simulate file deletion
12553        item.update(cx, |item, _| {
12554            item.set_has_deleted_file(true);
12555        });
12556
12557        // Emit UpdateTab event to trigger the close behavior
12558        cx.run_until_parked();
12559        item.update(cx, |_, cx| {
12560            cx.emit(ItemEvent::UpdateTab);
12561        });
12562
12563        // Allow any potential close operation to complete
12564        cx.run_until_parked();
12565
12566        // Verify the item remains open (dirty files are not auto-closed)
12567        pane.read_with(cx, |pane, _| {
12568            assert_eq!(
12569                pane.items().count(),
12570                1,
12571                "Dirty items should not be automatically closed even when file is deleted"
12572            );
12573        });
12574
12575        // Verify the item is marked as deleted and still dirty
12576        item.read_with(cx, |item, _| {
12577            assert!(
12578                item.has_deleted_file,
12579                "Item should be marked as having deleted file"
12580            );
12581            assert!(item.is_dirty, "Item should still be dirty");
12582        });
12583    }
12584
12585    /// Tests that navigation history is cleaned up when files are auto-closed
12586    /// due to deletion from disk.
12587    #[gpui::test]
12588    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12589        init_test(cx);
12590
12591        // Enable the close_on_file_delete setting
12592        cx.update_global(|store: &mut SettingsStore, cx| {
12593            store.update_user_settings(cx, |settings| {
12594                settings.workspace.close_on_file_delete = Some(true);
12595            });
12596        });
12597
12598        let fs = FakeFs::new(cx.background_executor.clone());
12599        let project = Project::test(fs, [], cx).await;
12600        let (workspace, cx) =
12601            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12602        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12603
12604        // Create test items
12605        let item1 = cx.new(|cx| {
12606            TestItem::new(cx)
12607                .with_label("test1.txt")
12608                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12609        });
12610        let item1_id = item1.item_id();
12611
12612        let item2 = cx.new(|cx| {
12613            TestItem::new(cx)
12614                .with_label("test2.txt")
12615                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12616        });
12617
12618        // Add items to workspace
12619        workspace.update_in(cx, |workspace, window, cx| {
12620            workspace.add_item(
12621                pane.clone(),
12622                Box::new(item1.clone()),
12623                None,
12624                false,
12625                false,
12626                window,
12627                cx,
12628            );
12629            workspace.add_item(
12630                pane.clone(),
12631                Box::new(item2.clone()),
12632                None,
12633                false,
12634                false,
12635                window,
12636                cx,
12637            );
12638        });
12639
12640        // Activate item1 to ensure it gets navigation entries
12641        pane.update_in(cx, |pane, window, cx| {
12642            pane.activate_item(0, true, true, window, cx);
12643        });
12644
12645        // Switch to item2 and back to create navigation history
12646        pane.update_in(cx, |pane, window, cx| {
12647            pane.activate_item(1, true, true, window, cx);
12648        });
12649        cx.run_until_parked();
12650
12651        pane.update_in(cx, |pane, window, cx| {
12652            pane.activate_item(0, true, true, window, cx);
12653        });
12654        cx.run_until_parked();
12655
12656        // Simulate file deletion for item1
12657        item1.update(cx, |item, _| {
12658            item.set_has_deleted_file(true);
12659        });
12660
12661        // Emit UpdateTab event to trigger the close behavior
12662        item1.update(cx, |_, cx| {
12663            cx.emit(ItemEvent::UpdateTab);
12664        });
12665        cx.run_until_parked();
12666
12667        // Verify item1 was closed
12668        pane.read_with(cx, |pane, _| {
12669            assert_eq!(
12670                pane.items().count(),
12671                1,
12672                "Should have 1 item remaining after auto-close"
12673            );
12674        });
12675
12676        // Check navigation history after close
12677        let has_item = pane.read_with(cx, |pane, cx| {
12678            let mut has_item = false;
12679            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12680                if entry.item.id() == item1_id {
12681                    has_item = true;
12682                }
12683            });
12684            has_item
12685        });
12686
12687        assert!(
12688            !has_item,
12689            "Navigation history should not contain closed item entries"
12690        );
12691    }
12692
12693    #[gpui::test]
12694    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12695        cx: &mut TestAppContext,
12696    ) {
12697        init_test(cx);
12698
12699        let fs = FakeFs::new(cx.background_executor.clone());
12700        let project = Project::test(fs, [], cx).await;
12701        let (workspace, cx) =
12702            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12703        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12704
12705        let dirty_regular_buffer = cx.new(|cx| {
12706            TestItem::new(cx)
12707                .with_dirty(true)
12708                .with_label("1.txt")
12709                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12710        });
12711        let dirty_regular_buffer_2 = cx.new(|cx| {
12712            TestItem::new(cx)
12713                .with_dirty(true)
12714                .with_label("2.txt")
12715                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12716        });
12717        let clear_regular_buffer = cx.new(|cx| {
12718            TestItem::new(cx)
12719                .with_label("3.txt")
12720                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12721        });
12722
12723        let dirty_multi_buffer = cx.new(|cx| {
12724            TestItem::new(cx)
12725                .with_dirty(true)
12726                .with_buffer_kind(ItemBufferKind::Multibuffer)
12727                .with_label("Fake Project Search")
12728                .with_project_items(&[
12729                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12730                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12731                    clear_regular_buffer.read(cx).project_items[0].clone(),
12732                ])
12733        });
12734        workspace.update_in(cx, |workspace, window, cx| {
12735            workspace.add_item(
12736                pane.clone(),
12737                Box::new(dirty_regular_buffer.clone()),
12738                None,
12739                false,
12740                false,
12741                window,
12742                cx,
12743            );
12744            workspace.add_item(
12745                pane.clone(),
12746                Box::new(dirty_regular_buffer_2.clone()),
12747                None,
12748                false,
12749                false,
12750                window,
12751                cx,
12752            );
12753            workspace.add_item(
12754                pane.clone(),
12755                Box::new(dirty_multi_buffer.clone()),
12756                None,
12757                false,
12758                false,
12759                window,
12760                cx,
12761            );
12762        });
12763
12764        pane.update_in(cx, |pane, window, cx| {
12765            pane.activate_item(2, true, true, window, cx);
12766            assert_eq!(
12767                pane.active_item().unwrap().item_id(),
12768                dirty_multi_buffer.item_id(),
12769                "Should select the multi buffer in the pane"
12770            );
12771        });
12772        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12773            pane.close_active_item(
12774                &CloseActiveItem {
12775                    save_intent: None,
12776                    close_pinned: false,
12777                },
12778                window,
12779                cx,
12780            )
12781        });
12782        cx.background_executor.run_until_parked();
12783        assert!(
12784            !cx.has_pending_prompt(),
12785            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12786        );
12787        close_multi_buffer_task
12788            .await
12789            .expect("Closing multi buffer failed");
12790        pane.update(cx, |pane, cx| {
12791            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12792            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12793            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12794            assert_eq!(
12795                pane.items()
12796                    .map(|item| item.item_id())
12797                    .sorted()
12798                    .collect::<Vec<_>>(),
12799                vec![
12800                    dirty_regular_buffer.item_id(),
12801                    dirty_regular_buffer_2.item_id(),
12802                ],
12803                "Should have no multi buffer left in the pane"
12804            );
12805            assert!(dirty_regular_buffer.read(cx).is_dirty);
12806            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12807        });
12808    }
12809
12810    #[gpui::test]
12811    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12812        init_test(cx);
12813        let fs = FakeFs::new(cx.executor());
12814        let project = Project::test(fs, [], cx).await;
12815        let (multi_workspace, cx) =
12816            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12817        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12818
12819        // Add a new panel to the right dock, opening the dock and setting the
12820        // focus to the new panel.
12821        let panel = workspace.update_in(cx, |workspace, window, cx| {
12822            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12823            workspace.add_panel(panel.clone(), window, cx);
12824
12825            workspace
12826                .right_dock()
12827                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12828
12829            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12830
12831            panel
12832        });
12833
12834        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12835        // panel to the next valid position which, in this case, is the left
12836        // dock.
12837        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12838        workspace.update(cx, |workspace, cx| {
12839            assert!(workspace.left_dock().read(cx).is_open());
12840            assert_eq!(panel.read(cx).position, DockPosition::Left);
12841        });
12842
12843        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12844        // panel to the next valid position which, in this case, is the bottom
12845        // dock.
12846        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12847        workspace.update(cx, |workspace, cx| {
12848            assert!(workspace.bottom_dock().read(cx).is_open());
12849            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12850        });
12851
12852        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12853        // around moving the panel to its initial position, the right dock.
12854        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12855        workspace.update(cx, |workspace, cx| {
12856            assert!(workspace.right_dock().read(cx).is_open());
12857            assert_eq!(panel.read(cx).position, DockPosition::Right);
12858        });
12859
12860        // Remove focus from the panel, ensuring that, if the panel is not
12861        // focused, the `MoveFocusedPanelToNextPosition` action does not update
12862        // the panel's position, so the panel is still in the right dock.
12863        workspace.update_in(cx, |workspace, window, cx| {
12864            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12865        });
12866
12867        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12868        workspace.update(cx, |workspace, cx| {
12869            assert!(workspace.right_dock().read(cx).is_open());
12870            assert_eq!(panel.read(cx).position, DockPosition::Right);
12871        });
12872    }
12873
12874    #[gpui::test]
12875    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12876        init_test(cx);
12877
12878        let fs = FakeFs::new(cx.executor());
12879        let project = Project::test(fs, [], cx).await;
12880        let (workspace, cx) =
12881            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12882
12883        let item_1 = cx.new(|cx| {
12884            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12885        });
12886        workspace.update_in(cx, |workspace, window, cx| {
12887            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12888            workspace.move_item_to_pane_in_direction(
12889                &MoveItemToPaneInDirection {
12890                    direction: SplitDirection::Right,
12891                    focus: true,
12892                    clone: false,
12893                },
12894                window,
12895                cx,
12896            );
12897            workspace.move_item_to_pane_at_index(
12898                &MoveItemToPane {
12899                    destination: 3,
12900                    focus: true,
12901                    clone: false,
12902                },
12903                window,
12904                cx,
12905            );
12906
12907            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12908            assert_eq!(
12909                pane_items_paths(&workspace.active_pane, cx),
12910                vec!["first.txt".to_string()],
12911                "Single item was not moved anywhere"
12912            );
12913        });
12914
12915        let item_2 = cx.new(|cx| {
12916            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12917        });
12918        workspace.update_in(cx, |workspace, window, cx| {
12919            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12920            assert_eq!(
12921                pane_items_paths(&workspace.panes[0], cx),
12922                vec!["first.txt".to_string(), "second.txt".to_string()],
12923            );
12924            workspace.move_item_to_pane_in_direction(
12925                &MoveItemToPaneInDirection {
12926                    direction: SplitDirection::Right,
12927                    focus: true,
12928                    clone: false,
12929                },
12930                window,
12931                cx,
12932            );
12933
12934            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12935            assert_eq!(
12936                pane_items_paths(&workspace.panes[0], cx),
12937                vec!["first.txt".to_string()],
12938                "After moving, one item should be left in the original pane"
12939            );
12940            assert_eq!(
12941                pane_items_paths(&workspace.panes[1], cx),
12942                vec!["second.txt".to_string()],
12943                "New item should have been moved to the new pane"
12944            );
12945        });
12946
12947        let item_3 = cx.new(|cx| {
12948            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12949        });
12950        workspace.update_in(cx, |workspace, window, cx| {
12951            let original_pane = workspace.panes[0].clone();
12952            workspace.set_active_pane(&original_pane, window, cx);
12953            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12954            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12955            assert_eq!(
12956                pane_items_paths(&workspace.active_pane, cx),
12957                vec!["first.txt".to_string(), "third.txt".to_string()],
12958                "New pane should be ready to move one item out"
12959            );
12960
12961            workspace.move_item_to_pane_at_index(
12962                &MoveItemToPane {
12963                    destination: 3,
12964                    focus: true,
12965                    clone: false,
12966                },
12967                window,
12968                cx,
12969            );
12970            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12971            assert_eq!(
12972                pane_items_paths(&workspace.active_pane, cx),
12973                vec!["first.txt".to_string()],
12974                "After moving, one item should be left in the original pane"
12975            );
12976            assert_eq!(
12977                pane_items_paths(&workspace.panes[1], cx),
12978                vec!["second.txt".to_string()],
12979                "Previously created pane should be unchanged"
12980            );
12981            assert_eq!(
12982                pane_items_paths(&workspace.panes[2], cx),
12983                vec!["third.txt".to_string()],
12984                "New item should have been moved to the new pane"
12985            );
12986        });
12987    }
12988
12989    #[gpui::test]
12990    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12991        init_test(cx);
12992
12993        let fs = FakeFs::new(cx.executor());
12994        let project = Project::test(fs, [], cx).await;
12995        let (workspace, cx) =
12996            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12997
12998        let item_1 = cx.new(|cx| {
12999            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13000        });
13001        workspace.update_in(cx, |workspace, window, cx| {
13002            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13003            workspace.move_item_to_pane_in_direction(
13004                &MoveItemToPaneInDirection {
13005                    direction: SplitDirection::Right,
13006                    focus: true,
13007                    clone: true,
13008                },
13009                window,
13010                cx,
13011            );
13012        });
13013        cx.run_until_parked();
13014        workspace.update_in(cx, |workspace, window, cx| {
13015            workspace.move_item_to_pane_at_index(
13016                &MoveItemToPane {
13017                    destination: 3,
13018                    focus: true,
13019                    clone: true,
13020                },
13021                window,
13022                cx,
13023            );
13024        });
13025        cx.run_until_parked();
13026
13027        workspace.update(cx, |workspace, cx| {
13028            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13029            for pane in workspace.panes() {
13030                assert_eq!(
13031                    pane_items_paths(pane, cx),
13032                    vec!["first.txt".to_string()],
13033                    "Single item exists in all panes"
13034                );
13035            }
13036        });
13037
13038        // verify that the active pane has been updated after waiting for the
13039        // pane focus event to fire and resolve
13040        workspace.read_with(cx, |workspace, _app| {
13041            assert_eq!(
13042                workspace.active_pane(),
13043                &workspace.panes[2],
13044                "The third pane should be the active one: {:?}",
13045                workspace.panes
13046            );
13047        })
13048    }
13049
13050    #[gpui::test]
13051    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13052        init_test(cx);
13053
13054        let fs = FakeFs::new(cx.executor());
13055        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13056
13057        let project = Project::test(fs, ["root".as_ref()], cx).await;
13058        let (workspace, cx) =
13059            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13060
13061        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13062        // Add item to pane A with project path
13063        let item_a = cx.new(|cx| {
13064            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13065        });
13066        workspace.update_in(cx, |workspace, window, cx| {
13067            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13068        });
13069
13070        // Split to create pane B
13071        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13072            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13073        });
13074
13075        // Add item with SAME project path to pane B, and pin it
13076        let item_b = cx.new(|cx| {
13077            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13078        });
13079        pane_b.update_in(cx, |pane, window, cx| {
13080            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13081            pane.set_pinned_count(1);
13082        });
13083
13084        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13085        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13086
13087        // close_pinned: false should only close the unpinned copy
13088        workspace.update_in(cx, |workspace, window, cx| {
13089            workspace.close_item_in_all_panes(
13090                &CloseItemInAllPanes {
13091                    save_intent: Some(SaveIntent::Close),
13092                    close_pinned: false,
13093                },
13094                window,
13095                cx,
13096            )
13097        });
13098        cx.executor().run_until_parked();
13099
13100        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13101        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13102        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13103        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13104
13105        // Split again, seeing as closing the previous item also closed its
13106        // pane, so only pane remains, which does not allow us to properly test
13107        // that both items close when `close_pinned: true`.
13108        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13109            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13110        });
13111
13112        // Add an item with the same project path to pane C so that
13113        // close_item_in_all_panes can determine what to close across all panes
13114        // (it reads the active item from the active pane, and split_pane
13115        // creates an empty pane).
13116        let item_c = cx.new(|cx| {
13117            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13118        });
13119        pane_c.update_in(cx, |pane, window, cx| {
13120            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13121        });
13122
13123        // close_pinned: true should close the pinned copy too
13124        workspace.update_in(cx, |workspace, window, cx| {
13125            let panes_count = workspace.panes().len();
13126            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13127
13128            workspace.close_item_in_all_panes(
13129                &CloseItemInAllPanes {
13130                    save_intent: Some(SaveIntent::Close),
13131                    close_pinned: true,
13132                },
13133                window,
13134                cx,
13135            )
13136        });
13137        cx.executor().run_until_parked();
13138
13139        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13140        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13141        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13142        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13143    }
13144
13145    mod register_project_item_tests {
13146
13147        use super::*;
13148
13149        // View
13150        struct TestPngItemView {
13151            focus_handle: FocusHandle,
13152        }
13153        // Model
13154        struct TestPngItem {}
13155
13156        impl project::ProjectItem for TestPngItem {
13157            fn try_open(
13158                _project: &Entity<Project>,
13159                path: &ProjectPath,
13160                cx: &mut App,
13161            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13162                if path.path.extension().unwrap() == "png" {
13163                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13164                } else {
13165                    None
13166                }
13167            }
13168
13169            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13170                None
13171            }
13172
13173            fn project_path(&self, _: &App) -> Option<ProjectPath> {
13174                None
13175            }
13176
13177            fn is_dirty(&self) -> bool {
13178                false
13179            }
13180        }
13181
13182        impl Item for TestPngItemView {
13183            type Event = ();
13184            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13185                "".into()
13186            }
13187        }
13188        impl EventEmitter<()> for TestPngItemView {}
13189        impl Focusable for TestPngItemView {
13190            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13191                self.focus_handle.clone()
13192            }
13193        }
13194
13195        impl Render for TestPngItemView {
13196            fn render(
13197                &mut self,
13198                _window: &mut Window,
13199                _cx: &mut Context<Self>,
13200            ) -> impl IntoElement {
13201                Empty
13202            }
13203        }
13204
13205        impl ProjectItem for TestPngItemView {
13206            type Item = TestPngItem;
13207
13208            fn for_project_item(
13209                _project: Entity<Project>,
13210                _pane: Option<&Pane>,
13211                _item: Entity<Self::Item>,
13212                _: &mut Window,
13213                cx: &mut Context<Self>,
13214            ) -> Self
13215            where
13216                Self: Sized,
13217            {
13218                Self {
13219                    focus_handle: cx.focus_handle(),
13220                }
13221            }
13222        }
13223
13224        // View
13225        struct TestIpynbItemView {
13226            focus_handle: FocusHandle,
13227        }
13228        // Model
13229        struct TestIpynbItem {}
13230
13231        impl project::ProjectItem for TestIpynbItem {
13232            fn try_open(
13233                _project: &Entity<Project>,
13234                path: &ProjectPath,
13235                cx: &mut App,
13236            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13237                if path.path.extension().unwrap() == "ipynb" {
13238                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13239                } else {
13240                    None
13241                }
13242            }
13243
13244            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13245                None
13246            }
13247
13248            fn project_path(&self, _: &App) -> Option<ProjectPath> {
13249                None
13250            }
13251
13252            fn is_dirty(&self) -> bool {
13253                false
13254            }
13255        }
13256
13257        impl Item for TestIpynbItemView {
13258            type Event = ();
13259            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13260                "".into()
13261            }
13262        }
13263        impl EventEmitter<()> for TestIpynbItemView {}
13264        impl Focusable for TestIpynbItemView {
13265            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13266                self.focus_handle.clone()
13267            }
13268        }
13269
13270        impl Render for TestIpynbItemView {
13271            fn render(
13272                &mut self,
13273                _window: &mut Window,
13274                _cx: &mut Context<Self>,
13275            ) -> impl IntoElement {
13276                Empty
13277            }
13278        }
13279
13280        impl ProjectItem for TestIpynbItemView {
13281            type Item = TestIpynbItem;
13282
13283            fn for_project_item(
13284                _project: Entity<Project>,
13285                _pane: Option<&Pane>,
13286                _item: Entity<Self::Item>,
13287                _: &mut Window,
13288                cx: &mut Context<Self>,
13289            ) -> Self
13290            where
13291                Self: Sized,
13292            {
13293                Self {
13294                    focus_handle: cx.focus_handle(),
13295                }
13296            }
13297        }
13298
13299        struct TestAlternatePngItemView {
13300            focus_handle: FocusHandle,
13301        }
13302
13303        impl Item for TestAlternatePngItemView {
13304            type Event = ();
13305            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13306                "".into()
13307            }
13308        }
13309
13310        impl EventEmitter<()> for TestAlternatePngItemView {}
13311        impl Focusable for TestAlternatePngItemView {
13312            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13313                self.focus_handle.clone()
13314            }
13315        }
13316
13317        impl Render for TestAlternatePngItemView {
13318            fn render(
13319                &mut self,
13320                _window: &mut Window,
13321                _cx: &mut Context<Self>,
13322            ) -> impl IntoElement {
13323                Empty
13324            }
13325        }
13326
13327        impl ProjectItem for TestAlternatePngItemView {
13328            type Item = TestPngItem;
13329
13330            fn for_project_item(
13331                _project: Entity<Project>,
13332                _pane: Option<&Pane>,
13333                _item: Entity<Self::Item>,
13334                _: &mut Window,
13335                cx: &mut Context<Self>,
13336            ) -> Self
13337            where
13338                Self: Sized,
13339            {
13340                Self {
13341                    focus_handle: cx.focus_handle(),
13342                }
13343            }
13344        }
13345
13346        #[gpui::test]
13347        async fn test_register_project_item(cx: &mut TestAppContext) {
13348            init_test(cx);
13349
13350            cx.update(|cx| {
13351                register_project_item::<TestPngItemView>(cx);
13352                register_project_item::<TestIpynbItemView>(cx);
13353            });
13354
13355            let fs = FakeFs::new(cx.executor());
13356            fs.insert_tree(
13357                "/root1",
13358                json!({
13359                    "one.png": "BINARYDATAHERE",
13360                    "two.ipynb": "{ totally a notebook }",
13361                    "three.txt": "editing text, sure why not?"
13362                }),
13363            )
13364            .await;
13365
13366            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13367            let (workspace, cx) =
13368                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13369
13370            let worktree_id = project.update(cx, |project, cx| {
13371                project.worktrees(cx).next().unwrap().read(cx).id()
13372            });
13373
13374            let handle = workspace
13375                .update_in(cx, |workspace, window, cx| {
13376                    let project_path = (worktree_id, rel_path("one.png"));
13377                    workspace.open_path(project_path, None, true, window, cx)
13378                })
13379                .await
13380                .unwrap();
13381
13382            // Now we can check if the handle we got back errored or not
13383            assert_eq!(
13384                handle.to_any_view().entity_type(),
13385                TypeId::of::<TestPngItemView>()
13386            );
13387
13388            let handle = workspace
13389                .update_in(cx, |workspace, window, cx| {
13390                    let project_path = (worktree_id, rel_path("two.ipynb"));
13391                    workspace.open_path(project_path, None, true, window, cx)
13392                })
13393                .await
13394                .unwrap();
13395
13396            assert_eq!(
13397                handle.to_any_view().entity_type(),
13398                TypeId::of::<TestIpynbItemView>()
13399            );
13400
13401            let handle = workspace
13402                .update_in(cx, |workspace, window, cx| {
13403                    let project_path = (worktree_id, rel_path("three.txt"));
13404                    workspace.open_path(project_path, None, true, window, cx)
13405                })
13406                .await;
13407            assert!(handle.is_err());
13408        }
13409
13410        #[gpui::test]
13411        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13412            init_test(cx);
13413
13414            cx.update(|cx| {
13415                register_project_item::<TestPngItemView>(cx);
13416                register_project_item::<TestAlternatePngItemView>(cx);
13417            });
13418
13419            let fs = FakeFs::new(cx.executor());
13420            fs.insert_tree(
13421                "/root1",
13422                json!({
13423                    "one.png": "BINARYDATAHERE",
13424                    "two.ipynb": "{ totally a notebook }",
13425                    "three.txt": "editing text, sure why not?"
13426                }),
13427            )
13428            .await;
13429            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13430            let (workspace, cx) =
13431                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13432            let worktree_id = project.update(cx, |project, cx| {
13433                project.worktrees(cx).next().unwrap().read(cx).id()
13434            });
13435
13436            let handle = workspace
13437                .update_in(cx, |workspace, window, cx| {
13438                    let project_path = (worktree_id, rel_path("one.png"));
13439                    workspace.open_path(project_path, None, true, window, cx)
13440                })
13441                .await
13442                .unwrap();
13443
13444            // This _must_ be the second item registered
13445            assert_eq!(
13446                handle.to_any_view().entity_type(),
13447                TypeId::of::<TestAlternatePngItemView>()
13448            );
13449
13450            let handle = workspace
13451                .update_in(cx, |workspace, window, cx| {
13452                    let project_path = (worktree_id, rel_path("three.txt"));
13453                    workspace.open_path(project_path, None, true, window, cx)
13454                })
13455                .await;
13456            assert!(handle.is_err());
13457        }
13458    }
13459
13460    #[gpui::test]
13461    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13462        init_test(cx);
13463
13464        let fs = FakeFs::new(cx.executor());
13465        let project = Project::test(fs, [], cx).await;
13466        let (workspace, _cx) =
13467            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13468
13469        // Test with status bar shown (default)
13470        workspace.read_with(cx, |workspace, cx| {
13471            let visible = workspace.status_bar_visible(cx);
13472            assert!(visible, "Status bar should be visible by default");
13473        });
13474
13475        // Test with status bar hidden
13476        cx.update_global(|store: &mut SettingsStore, cx| {
13477            store.update_user_settings(cx, |settings| {
13478                settings.status_bar.get_or_insert_default().show = Some(false);
13479            });
13480        });
13481
13482        workspace.read_with(cx, |workspace, cx| {
13483            let visible = workspace.status_bar_visible(cx);
13484            assert!(!visible, "Status bar should be hidden when show is false");
13485        });
13486
13487        // Test with status bar shown explicitly
13488        cx.update_global(|store: &mut SettingsStore, cx| {
13489            store.update_user_settings(cx, |settings| {
13490                settings.status_bar.get_or_insert_default().show = Some(true);
13491            });
13492        });
13493
13494        workspace.read_with(cx, |workspace, cx| {
13495            let visible = workspace.status_bar_visible(cx);
13496            assert!(visible, "Status bar should be visible when show is true");
13497        });
13498    }
13499
13500    #[gpui::test]
13501    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13502        init_test(cx);
13503
13504        let fs = FakeFs::new(cx.executor());
13505        let project = Project::test(fs, [], cx).await;
13506        let (multi_workspace, cx) =
13507            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13508        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13509        let panel = workspace.update_in(cx, |workspace, window, cx| {
13510            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13511            workspace.add_panel(panel.clone(), window, cx);
13512
13513            workspace
13514                .right_dock()
13515                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13516
13517            panel
13518        });
13519
13520        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13521        let item_a = cx.new(TestItem::new);
13522        let item_b = cx.new(TestItem::new);
13523        let item_a_id = item_a.entity_id();
13524        let item_b_id = item_b.entity_id();
13525
13526        pane.update_in(cx, |pane, window, cx| {
13527            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13528            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13529        });
13530
13531        pane.read_with(cx, |pane, _| {
13532            assert_eq!(pane.items_len(), 2);
13533            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13534        });
13535
13536        workspace.update_in(cx, |workspace, window, cx| {
13537            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13538        });
13539
13540        workspace.update_in(cx, |_, window, cx| {
13541            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13542        });
13543
13544        // Assert that the `pane::CloseActiveItem` action is handled at the
13545        // workspace level when one of the dock panels is focused and, in that
13546        // case, the center pane's active item is closed but the focus is not
13547        // moved.
13548        cx.dispatch_action(pane::CloseActiveItem::default());
13549        cx.run_until_parked();
13550
13551        pane.read_with(cx, |pane, _| {
13552            assert_eq!(pane.items_len(), 1);
13553            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13554        });
13555
13556        workspace.update_in(cx, |workspace, window, cx| {
13557            assert!(workspace.right_dock().read(cx).is_open());
13558            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13559        });
13560    }
13561
13562    #[gpui::test]
13563    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13564        init_test(cx);
13565        let fs = FakeFs::new(cx.executor());
13566
13567        let project_a = Project::test(fs.clone(), [], cx).await;
13568        let project_b = Project::test(fs, [], cx).await;
13569
13570        let multi_workspace_handle =
13571            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13572        cx.run_until_parked();
13573
13574        let workspace_a = multi_workspace_handle
13575            .read_with(cx, |mw, _| mw.workspace().clone())
13576            .unwrap();
13577
13578        let _workspace_b = multi_workspace_handle
13579            .update(cx, |mw, window, cx| {
13580                mw.test_add_workspace(project_b, window, cx)
13581            })
13582            .unwrap();
13583
13584        // Switch to workspace A
13585        multi_workspace_handle
13586            .update(cx, |mw, window, cx| {
13587                mw.activate_index(0, window, cx);
13588            })
13589            .unwrap();
13590
13591        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13592
13593        // Add a panel to workspace A's right dock and open the dock
13594        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13595            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13596            workspace.add_panel(panel.clone(), window, cx);
13597            workspace
13598                .right_dock()
13599                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13600            panel
13601        });
13602
13603        // Focus the panel through the workspace (matching existing test pattern)
13604        workspace_a.update_in(cx, |workspace, window, cx| {
13605            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13606        });
13607
13608        // Zoom the panel
13609        panel.update_in(cx, |panel, window, cx| {
13610            panel.set_zoomed(true, window, cx);
13611        });
13612
13613        // Verify the panel is zoomed and the dock is open
13614        workspace_a.update_in(cx, |workspace, window, cx| {
13615            assert!(
13616                workspace.right_dock().read(cx).is_open(),
13617                "dock should be open before switch"
13618            );
13619            assert!(
13620                panel.is_zoomed(window, cx),
13621                "panel should be zoomed before switch"
13622            );
13623            assert!(
13624                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13625                "panel should be focused before switch"
13626            );
13627        });
13628
13629        // Switch to workspace B
13630        multi_workspace_handle
13631            .update(cx, |mw, window, cx| {
13632                mw.activate_index(1, window, cx);
13633            })
13634            .unwrap();
13635        cx.run_until_parked();
13636
13637        // Switch back to workspace A
13638        multi_workspace_handle
13639            .update(cx, |mw, window, cx| {
13640                mw.activate_index(0, window, cx);
13641            })
13642            .unwrap();
13643        cx.run_until_parked();
13644
13645        // Verify the panel is still zoomed and the dock is still open
13646        workspace_a.update_in(cx, |workspace, window, cx| {
13647            assert!(
13648                workspace.right_dock().read(cx).is_open(),
13649                "dock should still be open after switching back"
13650            );
13651            assert!(
13652                panel.is_zoomed(window, cx),
13653                "panel should still be zoomed after switching back"
13654            );
13655        });
13656    }
13657
13658    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13659        pane.read(cx)
13660            .items()
13661            .flat_map(|item| {
13662                item.project_paths(cx)
13663                    .into_iter()
13664                    .map(|path| path.path.display(PathStyle::local()).into_owned())
13665            })
13666            .collect()
13667    }
13668
13669    pub fn init_test(cx: &mut TestAppContext) {
13670        cx.update(|cx| {
13671            let settings_store = SettingsStore::test(cx);
13672            cx.set_global(settings_store);
13673            cx.set_global(db::AppDatabase::test_new());
13674            theme::init(theme::LoadThemes::JustBase, cx);
13675        });
13676    }
13677
13678    #[gpui::test]
13679    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
13680        use settings::{ThemeName, ThemeSelection};
13681        use theme::SystemAppearance;
13682        use zed_actions::theme::ToggleMode;
13683
13684        init_test(cx);
13685
13686        let fs = FakeFs::new(cx.executor());
13687        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
13688
13689        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
13690            .await;
13691
13692        // Build a test project and workspace view so the test can invoke
13693        // the workspace action handler the same way the UI would.
13694        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
13695        let (workspace, cx) =
13696            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13697
13698        // Seed the settings file with a plain static light theme so the
13699        // first toggle always starts from a known persisted state.
13700        workspace.update_in(cx, |_workspace, _window, cx| {
13701            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
13702            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
13703                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
13704            });
13705        });
13706        cx.executor().advance_clock(Duration::from_millis(200));
13707        cx.run_until_parked();
13708
13709        // Confirm the initial persisted settings contain the static theme
13710        // we just wrote before any toggling happens.
13711        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13712        assert!(settings_text.contains(r#""theme": "One Light""#));
13713
13714        // Toggle once. This should migrate the persisted theme settings
13715        // into light/dark slots and enable system mode.
13716        workspace.update_in(cx, |workspace, window, cx| {
13717            workspace.toggle_theme_mode(&ToggleMode, window, cx);
13718        });
13719        cx.executor().advance_clock(Duration::from_millis(200));
13720        cx.run_until_parked();
13721
13722        // 1. Static -> Dynamic
13723        // this assertion checks theme changed from static to dynamic.
13724        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13725        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
13726        assert_eq!(
13727            parsed["theme"],
13728            serde_json::json!({
13729                "mode": "system",
13730                "light": "One Light",
13731                "dark": "One Dark"
13732            })
13733        );
13734
13735        // 2. Toggle again, suppose it will change the mode to light
13736        workspace.update_in(cx, |workspace, window, cx| {
13737            workspace.toggle_theme_mode(&ToggleMode, window, cx);
13738        });
13739        cx.executor().advance_clock(Duration::from_millis(200));
13740        cx.run_until_parked();
13741
13742        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13743        assert!(settings_text.contains(r#""mode": "light""#));
13744    }
13745
13746    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13747        let item = TestProjectItem::new(id, path, cx);
13748        item.update(cx, |item, _| {
13749            item.is_dirty = true;
13750        });
13751        item
13752    }
13753
13754    #[gpui::test]
13755    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13756        cx: &mut gpui::TestAppContext,
13757    ) {
13758        init_test(cx);
13759        let fs = FakeFs::new(cx.executor());
13760
13761        let project = Project::test(fs, [], cx).await;
13762        let (workspace, cx) =
13763            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13764
13765        let panel = workspace.update_in(cx, |workspace, window, cx| {
13766            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13767            workspace.add_panel(panel.clone(), window, cx);
13768            workspace
13769                .right_dock()
13770                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13771            panel
13772        });
13773
13774        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13775        pane.update_in(cx, |pane, window, cx| {
13776            let item = cx.new(TestItem::new);
13777            pane.add_item(Box::new(item), true, true, None, window, cx);
13778        });
13779
13780        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13781        // mirrors the real-world flow and avoids side effects from directly
13782        // focusing the panel while the center pane is active.
13783        workspace.update_in(cx, |workspace, window, cx| {
13784            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13785        });
13786
13787        panel.update_in(cx, |panel, window, cx| {
13788            panel.set_zoomed(true, window, cx);
13789        });
13790
13791        workspace.update_in(cx, |workspace, window, cx| {
13792            assert!(workspace.right_dock().read(cx).is_open());
13793            assert!(panel.is_zoomed(window, cx));
13794            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13795        });
13796
13797        // Simulate a spurious pane::Event::Focus on the center pane while the
13798        // panel still has focus. This mirrors what happens during macOS window
13799        // activation: the center pane fires a focus event even though actual
13800        // focus remains on the dock panel.
13801        pane.update_in(cx, |_, _, cx| {
13802            cx.emit(pane::Event::Focus);
13803        });
13804
13805        // The dock must remain open because the panel had focus at the time the
13806        // event was processed. Before the fix, dock_to_preserve was None for
13807        // panels that don't implement pane(), causing the dock to close.
13808        workspace.update_in(cx, |workspace, window, cx| {
13809            assert!(
13810                workspace.right_dock().read(cx).is_open(),
13811                "Dock should stay open when its zoomed panel (without pane()) still has focus"
13812            );
13813            assert!(panel.is_zoomed(window, cx));
13814        });
13815    }
13816}