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        let location = self
 3141            .project
 3142            .read(cx)
 3143            .remote_connection_options(cx)
 3144            .map(SerializedWorkspaceLocation::Remote)
 3145            .unwrap_or(SerializedWorkspaceLocation::Local);
 3146
 3147        let window_to_replace = if replace_current_window {
 3148            window_handle
 3149        } else if is_remote || has_worktree || has_dirty_items {
 3150            None
 3151        } else {
 3152            window_handle
 3153        };
 3154        let app_state = self.app_state.clone();
 3155        let fs = app_state.fs.clone();
 3156
 3157        cx.spawn(async move |_, cx| {
 3158            let all_paths_are_directories = if replace_current_window {
 3159                let metadata =
 3160                    futures::future::join_all(paths.iter().map(|path| fs.metadata(path))).await;
 3161                metadata
 3162                    .into_iter()
 3163                    .all(|entry| entry.ok().flatten().is_some_and(|entry| entry.is_dir))
 3164            } else {
 3165                false
 3166            };
 3167
 3168            if all_paths_are_directories {
 3169                let mut normalized_paths = Vec::with_capacity(paths.len());
 3170                for path in &paths {
 3171                    if let Some(canonical) = fs.canonicalize(path).await.ok() {
 3172                        normalized_paths.push(canonical);
 3173                    } else {
 3174                        normalized_paths.push(path.clone());
 3175                    }
 3176                }
 3177
 3178                if let Some((target_window, workspace)) =
 3179                    cx.update(|cx| find_exact_existing_workspace(&normalized_paths, &location, cx))
 3180                {
 3181                    target_window.update(cx, |multi_workspace, window, cx| {
 3182                        window.activate_window();
 3183                        multi_workspace.activate(workspace.clone(), cx);
 3184                    })?;
 3185                    return Ok(workspace);
 3186                }
 3187
 3188                let OpenResult { workspace, .. } = cx
 3189                    .update(|cx| {
 3190                        open_paths(
 3191                            &normalized_paths,
 3192                            app_state,
 3193                            OpenOptions {
 3194                                open_new_workspace: Some(true),
 3195                                replace_window: window_to_replace,
 3196                                ..Default::default()
 3197                            },
 3198                            cx,
 3199                        )
 3200                    })
 3201                    .await?;
 3202                return Ok(workspace);
 3203            }
 3204
 3205            let OpenResult { workspace, .. } = cx
 3206                .update(|cx| {
 3207                    open_paths(
 3208                        &paths,
 3209                        app_state,
 3210                        OpenOptions {
 3211                            replace_window: window_to_replace,
 3212                            ..Default::default()
 3213                        },
 3214                        cx,
 3215                    )
 3216                })
 3217                .await?;
 3218            Ok(workspace)
 3219        })
 3220    }
 3221
 3222    #[allow(clippy::type_complexity)]
 3223    pub fn open_paths(
 3224        &mut self,
 3225        mut abs_paths: Vec<PathBuf>,
 3226        options: OpenOptions,
 3227        pane: Option<WeakEntity<Pane>>,
 3228        window: &mut Window,
 3229        cx: &mut Context<Self>,
 3230    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3231        let fs = self.app_state.fs.clone();
 3232
 3233        let caller_ordered_abs_paths = abs_paths.clone();
 3234
 3235        // Sort the paths to ensure we add worktrees for parents before their children.
 3236        abs_paths.sort_unstable();
 3237        cx.spawn_in(window, async move |this, cx| {
 3238            let mut tasks = Vec::with_capacity(abs_paths.len());
 3239
 3240            for abs_path in &abs_paths {
 3241                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3242                    OpenVisible::All => Some(true),
 3243                    OpenVisible::None => Some(false),
 3244                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3245                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3246                        Some(None) => Some(true),
 3247                        None => None,
 3248                    },
 3249                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3250                        Some(Some(metadata)) => Some(metadata.is_dir),
 3251                        Some(None) => Some(false),
 3252                        None => None,
 3253                    },
 3254                };
 3255                let project_path = match visible {
 3256                    Some(visible) => match this
 3257                        .update(cx, |this, cx| {
 3258                            Workspace::project_path_for_path(
 3259                                this.project.clone(),
 3260                                abs_path,
 3261                                visible,
 3262                                cx,
 3263                            )
 3264                        })
 3265                        .log_err()
 3266                    {
 3267                        Some(project_path) => project_path.await.log_err(),
 3268                        None => None,
 3269                    },
 3270                    None => None,
 3271                };
 3272
 3273                let this = this.clone();
 3274                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3275                let fs = fs.clone();
 3276                let pane = pane.clone();
 3277                let task = cx.spawn(async move |cx| {
 3278                    let (_worktree, project_path) = project_path?;
 3279                    if fs.is_dir(&abs_path).await {
 3280                        // Opening a directory should not race to update the active entry.
 3281                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3282                        None
 3283                    } else {
 3284                        Some(
 3285                            this.update_in(cx, |this, window, cx| {
 3286                                this.open_path(
 3287                                    project_path,
 3288                                    pane,
 3289                                    options.focus.unwrap_or(true),
 3290                                    window,
 3291                                    cx,
 3292                                )
 3293                            })
 3294                            .ok()?
 3295                            .await,
 3296                        )
 3297                    }
 3298                });
 3299                tasks.push(task);
 3300            }
 3301
 3302            let results = futures::future::join_all(tasks).await;
 3303
 3304            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3305            let mut winner: Option<(PathBuf, bool)> = None;
 3306            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3307                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3308                    if !metadata.is_dir {
 3309                        winner = Some((abs_path, false));
 3310                        break;
 3311                    }
 3312                    if winner.is_none() {
 3313                        winner = Some((abs_path, true));
 3314                    }
 3315                } else if winner.is_none() {
 3316                    winner = Some((abs_path, false));
 3317                }
 3318            }
 3319
 3320            // Compute the winner entry id on the foreground thread and emit once, after all
 3321            // paths finish opening. This avoids races between concurrently-opening paths
 3322            // (directories in particular) and makes the resulting project panel selection
 3323            // deterministic.
 3324            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3325                'emit_winner: {
 3326                    let winner_abs_path: Arc<Path> =
 3327                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3328
 3329                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3330                        OpenVisible::All => true,
 3331                        OpenVisible::None => false,
 3332                        OpenVisible::OnlyFiles => !winner_is_dir,
 3333                        OpenVisible::OnlyDirectories => winner_is_dir,
 3334                    };
 3335
 3336                    let Some(worktree_task) = this
 3337                        .update(cx, |workspace, cx| {
 3338                            workspace.project.update(cx, |project, cx| {
 3339                                project.find_or_create_worktree(
 3340                                    winner_abs_path.as_ref(),
 3341                                    visible,
 3342                                    cx,
 3343                                )
 3344                            })
 3345                        })
 3346                        .ok()
 3347                    else {
 3348                        break 'emit_winner;
 3349                    };
 3350
 3351                    let Ok((worktree, _)) = worktree_task.await else {
 3352                        break 'emit_winner;
 3353                    };
 3354
 3355                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3356                        let worktree = worktree.read(cx);
 3357                        let worktree_abs_path = worktree.abs_path();
 3358                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3359                            worktree.root_entry()
 3360                        } else {
 3361                            winner_abs_path
 3362                                .strip_prefix(worktree_abs_path.as_ref())
 3363                                .ok()
 3364                                .and_then(|relative_path| {
 3365                                    let relative_path =
 3366                                        RelPath::new(relative_path, PathStyle::local())
 3367                                            .log_err()?;
 3368                                    worktree.entry_for_path(&relative_path)
 3369                                })
 3370                        }?;
 3371                        Some(entry.id)
 3372                    }) else {
 3373                        break 'emit_winner;
 3374                    };
 3375
 3376                    this.update(cx, |workspace, cx| {
 3377                        workspace.project.update(cx, |_, cx| {
 3378                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3379                        });
 3380                    })
 3381                    .ok();
 3382                }
 3383            }
 3384
 3385            results
 3386        })
 3387    }
 3388
 3389    pub fn open_resolved_path(
 3390        &mut self,
 3391        path: ResolvedPath,
 3392        window: &mut Window,
 3393        cx: &mut Context<Self>,
 3394    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3395        match path {
 3396            ResolvedPath::ProjectPath { project_path, .. } => {
 3397                self.open_path(project_path, None, true, window, cx)
 3398            }
 3399            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3400                PathBuf::from(path),
 3401                OpenOptions {
 3402                    visible: Some(OpenVisible::None),
 3403                    ..Default::default()
 3404                },
 3405                window,
 3406                cx,
 3407            ),
 3408        }
 3409    }
 3410
 3411    pub fn absolute_path_of_worktree(
 3412        &self,
 3413        worktree_id: WorktreeId,
 3414        cx: &mut Context<Self>,
 3415    ) -> Option<PathBuf> {
 3416        self.project
 3417            .read(cx)
 3418            .worktree_for_id(worktree_id, cx)
 3419            // TODO: use `abs_path` or `root_dir`
 3420            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3421    }
 3422
 3423    fn add_folder_to_project(
 3424        &mut self,
 3425        _: &AddFolderToProject,
 3426        window: &mut Window,
 3427        cx: &mut Context<Self>,
 3428    ) {
 3429        let project = self.project.read(cx);
 3430        if project.is_via_collab() {
 3431            self.show_error(
 3432                &anyhow!("You cannot add folders to someone else's project"),
 3433                cx,
 3434            );
 3435            return;
 3436        }
 3437        let paths = self.prompt_for_open_path(
 3438            PathPromptOptions {
 3439                files: false,
 3440                directories: true,
 3441                multiple: true,
 3442                prompt: None,
 3443            },
 3444            DirectoryLister::Project(self.project.clone()),
 3445            window,
 3446            cx,
 3447        );
 3448        cx.spawn_in(window, async move |this, cx| {
 3449            if let Some(paths) = paths.await.log_err().flatten() {
 3450                let results = this
 3451                    .update_in(cx, |this, window, cx| {
 3452                        this.open_paths(
 3453                            paths,
 3454                            OpenOptions {
 3455                                visible: Some(OpenVisible::All),
 3456                                ..Default::default()
 3457                            },
 3458                            None,
 3459                            window,
 3460                            cx,
 3461                        )
 3462                    })?
 3463                    .await;
 3464                for result in results.into_iter().flatten() {
 3465                    result.log_err();
 3466                }
 3467            }
 3468            anyhow::Ok(())
 3469        })
 3470        .detach_and_log_err(cx);
 3471    }
 3472
 3473    pub fn project_path_for_path(
 3474        project: Entity<Project>,
 3475        abs_path: &Path,
 3476        visible: bool,
 3477        cx: &mut App,
 3478    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3479        let entry = project.update(cx, |project, cx| {
 3480            project.find_or_create_worktree(abs_path, visible, cx)
 3481        });
 3482        cx.spawn(async move |cx| {
 3483            let (worktree, path) = entry.await?;
 3484            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3485            Ok((worktree, ProjectPath { worktree_id, path }))
 3486        })
 3487    }
 3488
 3489    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3490        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3491    }
 3492
 3493    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3494        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3495    }
 3496
 3497    pub fn items_of_type<'a, T: Item>(
 3498        &'a self,
 3499        cx: &'a App,
 3500    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3501        self.panes
 3502            .iter()
 3503            .flat_map(|pane| pane.read(cx).items_of_type())
 3504    }
 3505
 3506    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3507        self.active_pane().read(cx).active_item()
 3508    }
 3509
 3510    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3511        let item = self.active_item(cx)?;
 3512        item.to_any_view().downcast::<I>().ok()
 3513    }
 3514
 3515    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3516        self.active_item(cx).and_then(|item| item.project_path(cx))
 3517    }
 3518
 3519    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3520        self.recent_navigation_history_iter(cx)
 3521            .filter_map(|(path, abs_path)| {
 3522                let worktree = self
 3523                    .project
 3524                    .read(cx)
 3525                    .worktree_for_id(path.worktree_id, cx)?;
 3526                if worktree.read(cx).is_visible() {
 3527                    abs_path
 3528                } else {
 3529                    None
 3530                }
 3531            })
 3532            .next()
 3533    }
 3534
 3535    pub fn save_active_item(
 3536        &mut self,
 3537        save_intent: SaveIntent,
 3538        window: &mut Window,
 3539        cx: &mut App,
 3540    ) -> Task<Result<()>> {
 3541        let project = self.project.clone();
 3542        let pane = self.active_pane();
 3543        let item = pane.read(cx).active_item();
 3544        let pane = pane.downgrade();
 3545
 3546        window.spawn(cx, async move |cx| {
 3547            if let Some(item) = item {
 3548                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3549                    .await
 3550                    .map(|_| ())
 3551            } else {
 3552                Ok(())
 3553            }
 3554        })
 3555    }
 3556
 3557    pub fn close_inactive_items_and_panes(
 3558        &mut self,
 3559        action: &CloseInactiveTabsAndPanes,
 3560        window: &mut Window,
 3561        cx: &mut Context<Self>,
 3562    ) {
 3563        if let Some(task) = self.close_all_internal(
 3564            true,
 3565            action.save_intent.unwrap_or(SaveIntent::Close),
 3566            window,
 3567            cx,
 3568        ) {
 3569            task.detach_and_log_err(cx)
 3570        }
 3571    }
 3572
 3573    pub fn close_all_items_and_panes(
 3574        &mut self,
 3575        action: &CloseAllItemsAndPanes,
 3576        window: &mut Window,
 3577        cx: &mut Context<Self>,
 3578    ) {
 3579        if let Some(task) = self.close_all_internal(
 3580            false,
 3581            action.save_intent.unwrap_or(SaveIntent::Close),
 3582            window,
 3583            cx,
 3584        ) {
 3585            task.detach_and_log_err(cx)
 3586        }
 3587    }
 3588
 3589    /// Closes the active item across all panes.
 3590    pub fn close_item_in_all_panes(
 3591        &mut self,
 3592        action: &CloseItemInAllPanes,
 3593        window: &mut Window,
 3594        cx: &mut Context<Self>,
 3595    ) {
 3596        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3597            return;
 3598        };
 3599
 3600        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3601        let close_pinned = action.close_pinned;
 3602
 3603        if let Some(project_path) = active_item.project_path(cx) {
 3604            self.close_items_with_project_path(
 3605                &project_path,
 3606                save_intent,
 3607                close_pinned,
 3608                window,
 3609                cx,
 3610            );
 3611        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3612            let item_id = active_item.item_id();
 3613            self.active_pane().update(cx, |pane, cx| {
 3614                pane.close_item_by_id(item_id, save_intent, window, cx)
 3615                    .detach_and_log_err(cx);
 3616            });
 3617        }
 3618    }
 3619
 3620    /// Closes all items with the given project path across all panes.
 3621    pub fn close_items_with_project_path(
 3622        &mut self,
 3623        project_path: &ProjectPath,
 3624        save_intent: SaveIntent,
 3625        close_pinned: bool,
 3626        window: &mut Window,
 3627        cx: &mut Context<Self>,
 3628    ) {
 3629        let panes = self.panes().to_vec();
 3630        for pane in panes {
 3631            pane.update(cx, |pane, cx| {
 3632                pane.close_items_for_project_path(
 3633                    project_path,
 3634                    save_intent,
 3635                    close_pinned,
 3636                    window,
 3637                    cx,
 3638                )
 3639                .detach_and_log_err(cx);
 3640            });
 3641        }
 3642    }
 3643
 3644    fn close_all_internal(
 3645        &mut self,
 3646        retain_active_pane: bool,
 3647        save_intent: SaveIntent,
 3648        window: &mut Window,
 3649        cx: &mut Context<Self>,
 3650    ) -> Option<Task<Result<()>>> {
 3651        let current_pane = self.active_pane();
 3652
 3653        let mut tasks = Vec::new();
 3654
 3655        if retain_active_pane {
 3656            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3657                pane.close_other_items(
 3658                    &CloseOtherItems {
 3659                        save_intent: None,
 3660                        close_pinned: false,
 3661                    },
 3662                    None,
 3663                    window,
 3664                    cx,
 3665                )
 3666            });
 3667
 3668            tasks.push(current_pane_close);
 3669        }
 3670
 3671        for pane in self.panes() {
 3672            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3673                continue;
 3674            }
 3675
 3676            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3677                pane.close_all_items(
 3678                    &CloseAllItems {
 3679                        save_intent: Some(save_intent),
 3680                        close_pinned: false,
 3681                    },
 3682                    window,
 3683                    cx,
 3684                )
 3685            });
 3686
 3687            tasks.push(close_pane_items)
 3688        }
 3689
 3690        if tasks.is_empty() {
 3691            None
 3692        } else {
 3693            Some(cx.spawn_in(window, async move |_, _| {
 3694                for task in tasks {
 3695                    task.await?
 3696                }
 3697                Ok(())
 3698            }))
 3699        }
 3700    }
 3701
 3702    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3703        self.dock_at_position(position).read(cx).is_open()
 3704    }
 3705
 3706    pub fn toggle_dock(
 3707        &mut self,
 3708        dock_side: DockPosition,
 3709        window: &mut Window,
 3710        cx: &mut Context<Self>,
 3711    ) {
 3712        let mut focus_center = false;
 3713        let mut reveal_dock = false;
 3714
 3715        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3716        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3717
 3718        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3719            telemetry::event!(
 3720                "Panel Button Clicked",
 3721                name = panel.persistent_name(),
 3722                toggle_state = !was_visible
 3723            );
 3724        }
 3725        if was_visible {
 3726            self.save_open_dock_positions(cx);
 3727        }
 3728
 3729        let dock = self.dock_at_position(dock_side);
 3730        dock.update(cx, |dock, cx| {
 3731            dock.set_open(!was_visible, window, cx);
 3732
 3733            if dock.active_panel().is_none() {
 3734                let Some(panel_ix) = dock
 3735                    .first_enabled_panel_idx(cx)
 3736                    .log_with_level(log::Level::Info)
 3737                else {
 3738                    return;
 3739                };
 3740                dock.activate_panel(panel_ix, window, cx);
 3741            }
 3742
 3743            if let Some(active_panel) = dock.active_panel() {
 3744                if was_visible {
 3745                    if active_panel
 3746                        .panel_focus_handle(cx)
 3747                        .contains_focused(window, cx)
 3748                    {
 3749                        focus_center = true;
 3750                    }
 3751                } else {
 3752                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3753                    window.focus(focus_handle, cx);
 3754                    reveal_dock = true;
 3755                }
 3756            }
 3757        });
 3758
 3759        if reveal_dock {
 3760            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3761        }
 3762
 3763        if focus_center {
 3764            self.active_pane
 3765                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3766        }
 3767
 3768        cx.notify();
 3769        self.serialize_workspace(window, cx);
 3770    }
 3771
 3772    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3773        self.all_docks().into_iter().find(|&dock| {
 3774            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3775        })
 3776    }
 3777
 3778    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3779        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3780            self.save_open_dock_positions(cx);
 3781            dock.update(cx, |dock, cx| {
 3782                dock.set_open(false, window, cx);
 3783            });
 3784            return true;
 3785        }
 3786        false
 3787    }
 3788
 3789    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3790        self.save_open_dock_positions(cx);
 3791        for dock in self.all_docks() {
 3792            dock.update(cx, |dock, cx| {
 3793                dock.set_open(false, window, cx);
 3794            });
 3795        }
 3796
 3797        cx.focus_self(window);
 3798        cx.notify();
 3799        self.serialize_workspace(window, cx);
 3800    }
 3801
 3802    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 3803        self.all_docks()
 3804            .into_iter()
 3805            .filter_map(|dock| {
 3806                let dock_ref = dock.read(cx);
 3807                if dock_ref.is_open() {
 3808                    Some(dock_ref.position())
 3809                } else {
 3810                    None
 3811                }
 3812            })
 3813            .collect()
 3814    }
 3815
 3816    /// Saves the positions of currently open docks.
 3817    ///
 3818    /// Updates `last_open_dock_positions` with positions of all currently open
 3819    /// docks, to later be restored by the 'Toggle All Docks' action.
 3820    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 3821        let open_dock_positions = self.get_open_dock_positions(cx);
 3822        if !open_dock_positions.is_empty() {
 3823            self.last_open_dock_positions = open_dock_positions;
 3824        }
 3825    }
 3826
 3827    /// Toggles all docks between open and closed states.
 3828    ///
 3829    /// If any docks are open, closes all and remembers their positions. If all
 3830    /// docks are closed, restores the last remembered dock configuration.
 3831    fn toggle_all_docks(
 3832        &mut self,
 3833        _: &ToggleAllDocks,
 3834        window: &mut Window,
 3835        cx: &mut Context<Self>,
 3836    ) {
 3837        let open_dock_positions = self.get_open_dock_positions(cx);
 3838
 3839        if !open_dock_positions.is_empty() {
 3840            self.close_all_docks(window, cx);
 3841        } else if !self.last_open_dock_positions.is_empty() {
 3842            self.restore_last_open_docks(window, cx);
 3843        }
 3844    }
 3845
 3846    /// Reopens docks from the most recently remembered configuration.
 3847    ///
 3848    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 3849    /// and clears the stored positions.
 3850    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3851        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 3852
 3853        for position in positions_to_open {
 3854            let dock = self.dock_at_position(position);
 3855            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 3856        }
 3857
 3858        cx.focus_self(window);
 3859        cx.notify();
 3860        self.serialize_workspace(window, cx);
 3861    }
 3862
 3863    /// Transfer focus to the panel of the given type.
 3864    pub fn focus_panel<T: Panel>(
 3865        &mut self,
 3866        window: &mut Window,
 3867        cx: &mut Context<Self>,
 3868    ) -> Option<Entity<T>> {
 3869        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 3870        panel.to_any().downcast().ok()
 3871    }
 3872
 3873    /// Focus the panel of the given type if it isn't already focused. If it is
 3874    /// already focused, then transfer focus back to the workspace center.
 3875    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 3876    /// panel when transferring focus back to the center.
 3877    pub fn toggle_panel_focus<T: Panel>(
 3878        &mut self,
 3879        window: &mut Window,
 3880        cx: &mut Context<Self>,
 3881    ) -> bool {
 3882        let mut did_focus_panel = false;
 3883        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 3884            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 3885            did_focus_panel
 3886        });
 3887
 3888        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 3889            self.close_panel::<T>(window, cx);
 3890        }
 3891
 3892        telemetry::event!(
 3893            "Panel Button Clicked",
 3894            name = T::persistent_name(),
 3895            toggle_state = did_focus_panel
 3896        );
 3897
 3898        did_focus_panel
 3899    }
 3900
 3901    pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3902        if let Some(item) = self.active_item(cx) {
 3903            item.item_focus_handle(cx).focus(window, cx);
 3904        } else {
 3905            log::error!("Could not find a focus target when switching focus to the center panes",);
 3906        }
 3907    }
 3908
 3909    pub fn activate_panel_for_proto_id(
 3910        &mut self,
 3911        panel_id: PanelId,
 3912        window: &mut Window,
 3913        cx: &mut Context<Self>,
 3914    ) -> Option<Arc<dyn PanelHandle>> {
 3915        let mut panel = None;
 3916        for dock in self.all_docks() {
 3917            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 3918                panel = dock.update(cx, |dock, cx| {
 3919                    dock.activate_panel(panel_index, window, cx);
 3920                    dock.set_open(true, window, cx);
 3921                    dock.active_panel().cloned()
 3922                });
 3923                break;
 3924            }
 3925        }
 3926
 3927        if panel.is_some() {
 3928            cx.notify();
 3929            self.serialize_workspace(window, cx);
 3930        }
 3931
 3932        panel
 3933    }
 3934
 3935    /// Focus or unfocus the given panel type, depending on the given callback.
 3936    fn focus_or_unfocus_panel<T: Panel>(
 3937        &mut self,
 3938        window: &mut Window,
 3939        cx: &mut Context<Self>,
 3940        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 3941    ) -> Option<Arc<dyn PanelHandle>> {
 3942        let mut result_panel = None;
 3943        let mut serialize = false;
 3944        for dock in self.all_docks() {
 3945            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3946                let mut focus_center = false;
 3947                let panel = dock.update(cx, |dock, cx| {
 3948                    dock.activate_panel(panel_index, window, cx);
 3949
 3950                    let panel = dock.active_panel().cloned();
 3951                    if let Some(panel) = panel.as_ref() {
 3952                        if should_focus(&**panel, window, cx) {
 3953                            dock.set_open(true, window, cx);
 3954                            panel.panel_focus_handle(cx).focus(window, cx);
 3955                        } else {
 3956                            focus_center = true;
 3957                        }
 3958                    }
 3959                    panel
 3960                });
 3961
 3962                if focus_center {
 3963                    self.active_pane
 3964                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3965                }
 3966
 3967                result_panel = panel;
 3968                serialize = true;
 3969                break;
 3970            }
 3971        }
 3972
 3973        if serialize {
 3974            self.serialize_workspace(window, cx);
 3975        }
 3976
 3977        cx.notify();
 3978        result_panel
 3979    }
 3980
 3981    /// Open the panel of the given type
 3982    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3983        for dock in self.all_docks() {
 3984            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3985                dock.update(cx, |dock, cx| {
 3986                    dock.activate_panel(panel_index, window, cx);
 3987                    dock.set_open(true, window, cx);
 3988                });
 3989            }
 3990        }
 3991    }
 3992
 3993    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 3994        for dock in self.all_docks().iter() {
 3995            dock.update(cx, |dock, cx| {
 3996                if dock.panel::<T>().is_some() {
 3997                    dock.set_open(false, window, cx)
 3998                }
 3999            })
 4000        }
 4001    }
 4002
 4003    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 4004        self.all_docks()
 4005            .iter()
 4006            .find_map(|dock| dock.read(cx).panel::<T>())
 4007    }
 4008
 4009    fn dismiss_zoomed_items_to_reveal(
 4010        &mut self,
 4011        dock_to_reveal: Option<DockPosition>,
 4012        window: &mut Window,
 4013        cx: &mut Context<Self>,
 4014    ) {
 4015        // If a center pane is zoomed, unzoom it.
 4016        for pane in &self.panes {
 4017            if pane != &self.active_pane || dock_to_reveal.is_some() {
 4018                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4019            }
 4020        }
 4021
 4022        // If another dock is zoomed, hide it.
 4023        let mut focus_center = false;
 4024        for dock in self.all_docks() {
 4025            dock.update(cx, |dock, cx| {
 4026                if Some(dock.position()) != dock_to_reveal
 4027                    && let Some(panel) = dock.active_panel()
 4028                    && panel.is_zoomed(window, cx)
 4029                {
 4030                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 4031                    dock.set_open(false, window, cx);
 4032                }
 4033            });
 4034        }
 4035
 4036        if focus_center {
 4037            self.active_pane
 4038                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4039        }
 4040
 4041        if self.zoomed_position != dock_to_reveal {
 4042            self.zoomed = None;
 4043            self.zoomed_position = None;
 4044            cx.emit(Event::ZoomChanged);
 4045        }
 4046
 4047        cx.notify();
 4048    }
 4049
 4050    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4051        let pane = cx.new(|cx| {
 4052            let mut pane = Pane::new(
 4053                self.weak_handle(),
 4054                self.project.clone(),
 4055                self.pane_history_timestamp.clone(),
 4056                None,
 4057                NewFile.boxed_clone(),
 4058                true,
 4059                window,
 4060                cx,
 4061            );
 4062            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4063            pane
 4064        });
 4065        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4066            .detach();
 4067        self.panes.push(pane.clone());
 4068
 4069        window.focus(&pane.focus_handle(cx), cx);
 4070
 4071        cx.emit(Event::PaneAdded(pane.clone()));
 4072        pane
 4073    }
 4074
 4075    pub fn add_item_to_center(
 4076        &mut self,
 4077        item: Box<dyn ItemHandle>,
 4078        window: &mut Window,
 4079        cx: &mut Context<Self>,
 4080    ) -> bool {
 4081        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4082            if let Some(center_pane) = center_pane.upgrade() {
 4083                center_pane.update(cx, |pane, cx| {
 4084                    pane.add_item(item, true, true, None, window, cx)
 4085                });
 4086                true
 4087            } else {
 4088                false
 4089            }
 4090        } else {
 4091            false
 4092        }
 4093    }
 4094
 4095    pub fn add_item_to_active_pane(
 4096        &mut self,
 4097        item: Box<dyn ItemHandle>,
 4098        destination_index: Option<usize>,
 4099        focus_item: bool,
 4100        window: &mut Window,
 4101        cx: &mut App,
 4102    ) {
 4103        self.add_item(
 4104            self.active_pane.clone(),
 4105            item,
 4106            destination_index,
 4107            false,
 4108            focus_item,
 4109            window,
 4110            cx,
 4111        )
 4112    }
 4113
 4114    pub fn add_item(
 4115        &mut self,
 4116        pane: Entity<Pane>,
 4117        item: Box<dyn ItemHandle>,
 4118        destination_index: Option<usize>,
 4119        activate_pane: bool,
 4120        focus_item: bool,
 4121        window: &mut Window,
 4122        cx: &mut App,
 4123    ) {
 4124        pane.update(cx, |pane, cx| {
 4125            pane.add_item(
 4126                item,
 4127                activate_pane,
 4128                focus_item,
 4129                destination_index,
 4130                window,
 4131                cx,
 4132            )
 4133        });
 4134    }
 4135
 4136    pub fn split_item(
 4137        &mut self,
 4138        split_direction: SplitDirection,
 4139        item: Box<dyn ItemHandle>,
 4140        window: &mut Window,
 4141        cx: &mut Context<Self>,
 4142    ) {
 4143        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4144        self.add_item(new_pane, item, None, true, true, window, cx);
 4145    }
 4146
 4147    pub fn open_abs_path(
 4148        &mut self,
 4149        abs_path: PathBuf,
 4150        options: OpenOptions,
 4151        window: &mut Window,
 4152        cx: &mut Context<Self>,
 4153    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4154        cx.spawn_in(window, async move |workspace, cx| {
 4155            let open_paths_task_result = workspace
 4156                .update_in(cx, |workspace, window, cx| {
 4157                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4158                })
 4159                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4160                .await;
 4161            anyhow::ensure!(
 4162                open_paths_task_result.len() == 1,
 4163                "open abs path {abs_path:?} task returned incorrect number of results"
 4164            );
 4165            match open_paths_task_result
 4166                .into_iter()
 4167                .next()
 4168                .expect("ensured single task result")
 4169            {
 4170                Some(open_result) => {
 4171                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4172                }
 4173                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4174            }
 4175        })
 4176    }
 4177
 4178    pub fn split_abs_path(
 4179        &mut self,
 4180        abs_path: PathBuf,
 4181        visible: bool,
 4182        window: &mut Window,
 4183        cx: &mut Context<Self>,
 4184    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4185        let project_path_task =
 4186            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4187        cx.spawn_in(window, async move |this, cx| {
 4188            let (_, path) = project_path_task.await?;
 4189            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4190                .await
 4191        })
 4192    }
 4193
 4194    pub fn open_path(
 4195        &mut self,
 4196        path: impl Into<ProjectPath>,
 4197        pane: Option<WeakEntity<Pane>>,
 4198        focus_item: bool,
 4199        window: &mut Window,
 4200        cx: &mut App,
 4201    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4202        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4203    }
 4204
 4205    pub fn open_path_preview(
 4206        &mut self,
 4207        path: impl Into<ProjectPath>,
 4208        pane: Option<WeakEntity<Pane>>,
 4209        focus_item: bool,
 4210        allow_preview: bool,
 4211        activate: bool,
 4212        window: &mut Window,
 4213        cx: &mut App,
 4214    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4215        let pane = pane.unwrap_or_else(|| {
 4216            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4217                self.panes
 4218                    .first()
 4219                    .expect("There must be an active pane")
 4220                    .downgrade()
 4221            })
 4222        });
 4223
 4224        let project_path = path.into();
 4225        let task = self.load_path(project_path.clone(), window, cx);
 4226        window.spawn(cx, async move |cx| {
 4227            let (project_entry_id, build_item) = task.await?;
 4228
 4229            pane.update_in(cx, |pane, window, cx| {
 4230                pane.open_item(
 4231                    project_entry_id,
 4232                    project_path,
 4233                    focus_item,
 4234                    allow_preview,
 4235                    activate,
 4236                    None,
 4237                    window,
 4238                    cx,
 4239                    build_item,
 4240                )
 4241            })
 4242        })
 4243    }
 4244
 4245    pub fn split_path(
 4246        &mut self,
 4247        path: impl Into<ProjectPath>,
 4248        window: &mut Window,
 4249        cx: &mut Context<Self>,
 4250    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4251        self.split_path_preview(path, false, None, window, cx)
 4252    }
 4253
 4254    pub fn split_path_preview(
 4255        &mut self,
 4256        path: impl Into<ProjectPath>,
 4257        allow_preview: bool,
 4258        split_direction: Option<SplitDirection>,
 4259        window: &mut Window,
 4260        cx: &mut Context<Self>,
 4261    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4262        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4263            self.panes
 4264                .first()
 4265                .expect("There must be an active pane")
 4266                .downgrade()
 4267        });
 4268
 4269        if let Member::Pane(center_pane) = &self.center.root
 4270            && center_pane.read(cx).items_len() == 0
 4271        {
 4272            return self.open_path(path, Some(pane), true, window, cx);
 4273        }
 4274
 4275        let project_path = path.into();
 4276        let task = self.load_path(project_path.clone(), window, cx);
 4277        cx.spawn_in(window, async move |this, cx| {
 4278            let (project_entry_id, build_item) = task.await?;
 4279            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4280                let pane = pane.upgrade()?;
 4281                let new_pane = this.split_pane(
 4282                    pane,
 4283                    split_direction.unwrap_or(SplitDirection::Right),
 4284                    window,
 4285                    cx,
 4286                );
 4287                new_pane.update(cx, |new_pane, cx| {
 4288                    Some(new_pane.open_item(
 4289                        project_entry_id,
 4290                        project_path,
 4291                        true,
 4292                        allow_preview,
 4293                        true,
 4294                        None,
 4295                        window,
 4296                        cx,
 4297                        build_item,
 4298                    ))
 4299                })
 4300            })
 4301            .map(|option| option.context("pane was dropped"))?
 4302        })
 4303    }
 4304
 4305    fn load_path(
 4306        &mut self,
 4307        path: ProjectPath,
 4308        window: &mut Window,
 4309        cx: &mut App,
 4310    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4311        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4312        registry.open_path(self.project(), &path, window, cx)
 4313    }
 4314
 4315    pub fn find_project_item<T>(
 4316        &self,
 4317        pane: &Entity<Pane>,
 4318        project_item: &Entity<T::Item>,
 4319        cx: &App,
 4320    ) -> Option<Entity<T>>
 4321    where
 4322        T: ProjectItem,
 4323    {
 4324        use project::ProjectItem as _;
 4325        let project_item = project_item.read(cx);
 4326        let entry_id = project_item.entry_id(cx);
 4327        let project_path = project_item.project_path(cx);
 4328
 4329        let mut item = None;
 4330        if let Some(entry_id) = entry_id {
 4331            item = pane.read(cx).item_for_entry(entry_id, cx);
 4332        }
 4333        if item.is_none()
 4334            && let Some(project_path) = project_path
 4335        {
 4336            item = pane.read(cx).item_for_path(project_path, cx);
 4337        }
 4338
 4339        item.and_then(|item| item.downcast::<T>())
 4340    }
 4341
 4342    pub fn is_project_item_open<T>(
 4343        &self,
 4344        pane: &Entity<Pane>,
 4345        project_item: &Entity<T::Item>,
 4346        cx: &App,
 4347    ) -> bool
 4348    where
 4349        T: ProjectItem,
 4350    {
 4351        self.find_project_item::<T>(pane, project_item, cx)
 4352            .is_some()
 4353    }
 4354
 4355    pub fn open_project_item<T>(
 4356        &mut self,
 4357        pane: Entity<Pane>,
 4358        project_item: Entity<T::Item>,
 4359        activate_pane: bool,
 4360        focus_item: bool,
 4361        keep_old_preview: bool,
 4362        allow_new_preview: bool,
 4363        window: &mut Window,
 4364        cx: &mut Context<Self>,
 4365    ) -> Entity<T>
 4366    where
 4367        T: ProjectItem,
 4368    {
 4369        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4370
 4371        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4372            if !keep_old_preview
 4373                && let Some(old_id) = old_item_id
 4374                && old_id != item.item_id()
 4375            {
 4376                // switching to a different item, so unpreview old active item
 4377                pane.update(cx, |pane, _| {
 4378                    pane.unpreview_item_if_preview(old_id);
 4379                });
 4380            }
 4381
 4382            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4383            if !allow_new_preview {
 4384                pane.update(cx, |pane, _| {
 4385                    pane.unpreview_item_if_preview(item.item_id());
 4386                });
 4387            }
 4388            return item;
 4389        }
 4390
 4391        let item = pane.update(cx, |pane, cx| {
 4392            cx.new(|cx| {
 4393                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4394            })
 4395        });
 4396        let mut destination_index = None;
 4397        pane.update(cx, |pane, cx| {
 4398            if !keep_old_preview && let Some(old_id) = old_item_id {
 4399                pane.unpreview_item_if_preview(old_id);
 4400            }
 4401            if allow_new_preview {
 4402                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4403            }
 4404        });
 4405
 4406        self.add_item(
 4407            pane,
 4408            Box::new(item.clone()),
 4409            destination_index,
 4410            activate_pane,
 4411            focus_item,
 4412            window,
 4413            cx,
 4414        );
 4415        item
 4416    }
 4417
 4418    pub fn open_shared_screen(
 4419        &mut self,
 4420        peer_id: PeerId,
 4421        window: &mut Window,
 4422        cx: &mut Context<Self>,
 4423    ) {
 4424        if let Some(shared_screen) =
 4425            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4426        {
 4427            self.active_pane.update(cx, |pane, cx| {
 4428                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4429            });
 4430        }
 4431    }
 4432
 4433    pub fn activate_item(
 4434        &mut self,
 4435        item: &dyn ItemHandle,
 4436        activate_pane: bool,
 4437        focus_item: bool,
 4438        window: &mut Window,
 4439        cx: &mut App,
 4440    ) -> bool {
 4441        let result = self.panes.iter().find_map(|pane| {
 4442            pane.read(cx)
 4443                .index_for_item(item)
 4444                .map(|ix| (pane.clone(), ix))
 4445        });
 4446        if let Some((pane, ix)) = result {
 4447            pane.update(cx, |pane, cx| {
 4448                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4449            });
 4450            true
 4451        } else {
 4452            false
 4453        }
 4454    }
 4455
 4456    fn activate_pane_at_index(
 4457        &mut self,
 4458        action: &ActivatePane,
 4459        window: &mut Window,
 4460        cx: &mut Context<Self>,
 4461    ) {
 4462        let panes = self.center.panes();
 4463        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4464            window.focus(&pane.focus_handle(cx), cx);
 4465        } else {
 4466            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4467                .detach();
 4468        }
 4469    }
 4470
 4471    fn move_item_to_pane_at_index(
 4472        &mut self,
 4473        action: &MoveItemToPane,
 4474        window: &mut Window,
 4475        cx: &mut Context<Self>,
 4476    ) {
 4477        let panes = self.center.panes();
 4478        let destination = match panes.get(action.destination) {
 4479            Some(&destination) => destination.clone(),
 4480            None => {
 4481                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4482                    return;
 4483                }
 4484                let direction = SplitDirection::Right;
 4485                let split_off_pane = self
 4486                    .find_pane_in_direction(direction, cx)
 4487                    .unwrap_or_else(|| self.active_pane.clone());
 4488                let new_pane = self.add_pane(window, cx);
 4489                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4490                new_pane
 4491            }
 4492        };
 4493
 4494        if action.clone {
 4495            if self
 4496                .active_pane
 4497                .read(cx)
 4498                .active_item()
 4499                .is_some_and(|item| item.can_split(cx))
 4500            {
 4501                clone_active_item(
 4502                    self.database_id(),
 4503                    &self.active_pane,
 4504                    &destination,
 4505                    action.focus,
 4506                    window,
 4507                    cx,
 4508                );
 4509                return;
 4510            }
 4511        }
 4512        move_active_item(
 4513            &self.active_pane,
 4514            &destination,
 4515            action.focus,
 4516            true,
 4517            window,
 4518            cx,
 4519        )
 4520    }
 4521
 4522    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4523        let panes = self.center.panes();
 4524        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4525            let next_ix = (ix + 1) % panes.len();
 4526            let next_pane = panes[next_ix].clone();
 4527            window.focus(&next_pane.focus_handle(cx), cx);
 4528        }
 4529    }
 4530
 4531    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4532        let panes = self.center.panes();
 4533        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4534            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4535            let prev_pane = panes[prev_ix].clone();
 4536            window.focus(&prev_pane.focus_handle(cx), cx);
 4537        }
 4538    }
 4539
 4540    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4541        let last_pane = self.center.last_pane();
 4542        window.focus(&last_pane.focus_handle(cx), cx);
 4543    }
 4544
 4545    pub fn activate_pane_in_direction(
 4546        &mut self,
 4547        direction: SplitDirection,
 4548        window: &mut Window,
 4549        cx: &mut App,
 4550    ) {
 4551        use ActivateInDirectionTarget as Target;
 4552        enum Origin {
 4553            Sidebar,
 4554            LeftDock,
 4555            RightDock,
 4556            BottomDock,
 4557            Center,
 4558        }
 4559
 4560        let origin: Origin = if self
 4561            .sidebar_focus_handle
 4562            .as_ref()
 4563            .is_some_and(|h| h.contains_focused(window, cx))
 4564        {
 4565            Origin::Sidebar
 4566        } else {
 4567            [
 4568                (&self.left_dock, Origin::LeftDock),
 4569                (&self.right_dock, Origin::RightDock),
 4570                (&self.bottom_dock, Origin::BottomDock),
 4571            ]
 4572            .into_iter()
 4573            .find_map(|(dock, origin)| {
 4574                if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4575                    Some(origin)
 4576                } else {
 4577                    None
 4578                }
 4579            })
 4580            .unwrap_or(Origin::Center)
 4581        };
 4582
 4583        let get_last_active_pane = || {
 4584            let pane = self
 4585                .last_active_center_pane
 4586                .clone()
 4587                .unwrap_or_else(|| {
 4588                    self.panes
 4589                        .first()
 4590                        .expect("There must be an active pane")
 4591                        .downgrade()
 4592                })
 4593                .upgrade()?;
 4594            (pane.read(cx).items_len() != 0).then_some(pane)
 4595        };
 4596
 4597        let try_dock =
 4598            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4599
 4600        let sidebar_target = self
 4601            .sidebar_focus_handle
 4602            .as_ref()
 4603            .map(|h| Target::Sidebar(h.clone()));
 4604
 4605        let target = match (origin, direction) {
 4606            // From the sidebar, only Right navigates into the workspace.
 4607            (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
 4608                .or_else(|| get_last_active_pane().map(Target::Pane))
 4609                .or_else(|| try_dock(&self.bottom_dock))
 4610                .or_else(|| try_dock(&self.right_dock)),
 4611
 4612            (Origin::Sidebar, _) => None,
 4613
 4614            // We're in the center, so we first try to go to a different pane,
 4615            // otherwise try to go to a dock.
 4616            (Origin::Center, direction) => {
 4617                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4618                    Some(Target::Pane(pane))
 4619                } else {
 4620                    match direction {
 4621                        SplitDirection::Up => None,
 4622                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4623                        SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
 4624                        SplitDirection::Right => try_dock(&self.right_dock),
 4625                    }
 4626                }
 4627            }
 4628
 4629            (Origin::LeftDock, SplitDirection::Right) => {
 4630                if let Some(last_active_pane) = get_last_active_pane() {
 4631                    Some(Target::Pane(last_active_pane))
 4632                } else {
 4633                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4634                }
 4635            }
 4636
 4637            (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
 4638
 4639            (Origin::LeftDock, SplitDirection::Down)
 4640            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4641
 4642            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4643            (Origin::BottomDock, SplitDirection::Left) => {
 4644                try_dock(&self.left_dock).or(sidebar_target)
 4645            }
 4646            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4647
 4648            (Origin::RightDock, SplitDirection::Left) => {
 4649                if let Some(last_active_pane) = get_last_active_pane() {
 4650                    Some(Target::Pane(last_active_pane))
 4651                } else {
 4652                    try_dock(&self.bottom_dock)
 4653                        .or_else(|| try_dock(&self.left_dock))
 4654                        .or(sidebar_target)
 4655                }
 4656            }
 4657
 4658            _ => None,
 4659        };
 4660
 4661        match target {
 4662            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4663                let pane = pane.read(cx);
 4664                if let Some(item) = pane.active_item() {
 4665                    item.item_focus_handle(cx).focus(window, cx);
 4666                } else {
 4667                    log::error!(
 4668                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4669                    );
 4670                }
 4671            }
 4672            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4673                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4674                window.defer(cx, move |window, cx| {
 4675                    let dock = dock.read(cx);
 4676                    if let Some(panel) = dock.active_panel() {
 4677                        panel.panel_focus_handle(cx).focus(window, cx);
 4678                    } else {
 4679                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4680                    }
 4681                })
 4682            }
 4683            Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
 4684                focus_handle.focus(window, cx);
 4685            }
 4686            None => {}
 4687        }
 4688    }
 4689
 4690    pub fn move_item_to_pane_in_direction(
 4691        &mut self,
 4692        action: &MoveItemToPaneInDirection,
 4693        window: &mut Window,
 4694        cx: &mut Context<Self>,
 4695    ) {
 4696        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4697            Some(destination) => destination,
 4698            None => {
 4699                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4700                    return;
 4701                }
 4702                let new_pane = self.add_pane(window, cx);
 4703                self.center
 4704                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4705                new_pane
 4706            }
 4707        };
 4708
 4709        if action.clone {
 4710            if self
 4711                .active_pane
 4712                .read(cx)
 4713                .active_item()
 4714                .is_some_and(|item| item.can_split(cx))
 4715            {
 4716                clone_active_item(
 4717                    self.database_id(),
 4718                    &self.active_pane,
 4719                    &destination,
 4720                    action.focus,
 4721                    window,
 4722                    cx,
 4723                );
 4724                return;
 4725            }
 4726        }
 4727        move_active_item(
 4728            &self.active_pane,
 4729            &destination,
 4730            action.focus,
 4731            true,
 4732            window,
 4733            cx,
 4734        );
 4735    }
 4736
 4737    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4738        self.center.bounding_box_for_pane(pane)
 4739    }
 4740
 4741    pub fn find_pane_in_direction(
 4742        &mut self,
 4743        direction: SplitDirection,
 4744        cx: &App,
 4745    ) -> Option<Entity<Pane>> {
 4746        self.center
 4747            .find_pane_in_direction(&self.active_pane, direction, cx)
 4748            .cloned()
 4749    }
 4750
 4751    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4752        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4753            self.center.swap(&self.active_pane, &to, cx);
 4754            cx.notify();
 4755        }
 4756    }
 4757
 4758    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4759        if self
 4760            .center
 4761            .move_to_border(&self.active_pane, direction, cx)
 4762            .unwrap()
 4763        {
 4764            cx.notify();
 4765        }
 4766    }
 4767
 4768    pub fn resize_pane(
 4769        &mut self,
 4770        axis: gpui::Axis,
 4771        amount: Pixels,
 4772        window: &mut Window,
 4773        cx: &mut Context<Self>,
 4774    ) {
 4775        let docks = self.all_docks();
 4776        let active_dock = docks
 4777            .into_iter()
 4778            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4779
 4780        if let Some(dock) = active_dock {
 4781            let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
 4782                return;
 4783            };
 4784            match dock.read(cx).position() {
 4785                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4786                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4787                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4788            }
 4789        } else {
 4790            self.center
 4791                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 4792        }
 4793        cx.notify();
 4794    }
 4795
 4796    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 4797        self.center.reset_pane_sizes(cx);
 4798        cx.notify();
 4799    }
 4800
 4801    fn handle_pane_focused(
 4802        &mut self,
 4803        pane: Entity<Pane>,
 4804        window: &mut Window,
 4805        cx: &mut Context<Self>,
 4806    ) {
 4807        // This is explicitly hoisted out of the following check for pane identity as
 4808        // terminal panel panes are not registered as a center panes.
 4809        self.status_bar.update(cx, |status_bar, cx| {
 4810            status_bar.set_active_pane(&pane, window, cx);
 4811        });
 4812        if self.active_pane != pane {
 4813            self.set_active_pane(&pane, window, cx);
 4814        }
 4815
 4816        if self.last_active_center_pane.is_none() {
 4817            self.last_active_center_pane = Some(pane.downgrade());
 4818        }
 4819
 4820        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 4821        // This prevents the dock from closing when focus events fire during window activation.
 4822        // We also preserve any dock whose active panel itself has focus — this covers
 4823        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 4824        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 4825            let dock_read = dock.read(cx);
 4826            if let Some(panel) = dock_read.active_panel() {
 4827                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 4828                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 4829                {
 4830                    return Some(dock_read.position());
 4831                }
 4832            }
 4833            None
 4834        });
 4835
 4836        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 4837        if pane.read(cx).is_zoomed() {
 4838            self.zoomed = Some(pane.downgrade().into());
 4839        } else {
 4840            self.zoomed = None;
 4841        }
 4842        self.zoomed_position = None;
 4843        cx.emit(Event::ZoomChanged);
 4844        self.update_active_view_for_followers(window, cx);
 4845        pane.update(cx, |pane, _| {
 4846            pane.track_alternate_file_items();
 4847        });
 4848
 4849        cx.notify();
 4850    }
 4851
 4852    fn set_active_pane(
 4853        &mut self,
 4854        pane: &Entity<Pane>,
 4855        window: &mut Window,
 4856        cx: &mut Context<Self>,
 4857    ) {
 4858        self.active_pane = pane.clone();
 4859        self.active_item_path_changed(true, window, cx);
 4860        self.last_active_center_pane = Some(pane.downgrade());
 4861    }
 4862
 4863    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4864        self.update_active_view_for_followers(window, cx);
 4865    }
 4866
 4867    fn handle_pane_event(
 4868        &mut self,
 4869        pane: &Entity<Pane>,
 4870        event: &pane::Event,
 4871        window: &mut Window,
 4872        cx: &mut Context<Self>,
 4873    ) {
 4874        let mut serialize_workspace = true;
 4875        match event {
 4876            pane::Event::AddItem { item } => {
 4877                item.added_to_pane(self, pane.clone(), window, cx);
 4878                cx.emit(Event::ItemAdded {
 4879                    item: item.boxed_clone(),
 4880                });
 4881            }
 4882            pane::Event::Split { direction, mode } => {
 4883                match mode {
 4884                    SplitMode::ClonePane => {
 4885                        self.split_and_clone(pane.clone(), *direction, window, cx)
 4886                            .detach();
 4887                    }
 4888                    SplitMode::EmptyPane => {
 4889                        self.split_pane(pane.clone(), *direction, window, cx);
 4890                    }
 4891                    SplitMode::MovePane => {
 4892                        self.split_and_move(pane.clone(), *direction, window, cx);
 4893                    }
 4894                };
 4895            }
 4896            pane::Event::JoinIntoNext => {
 4897                self.join_pane_into_next(pane.clone(), window, cx);
 4898            }
 4899            pane::Event::JoinAll => {
 4900                self.join_all_panes(window, cx);
 4901            }
 4902            pane::Event::Remove { focus_on_pane } => {
 4903                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 4904            }
 4905            pane::Event::ActivateItem {
 4906                local,
 4907                focus_changed,
 4908            } => {
 4909                window.invalidate_character_coordinates();
 4910
 4911                pane.update(cx, |pane, _| {
 4912                    pane.track_alternate_file_items();
 4913                });
 4914                if *local {
 4915                    self.unfollow_in_pane(pane, window, cx);
 4916                }
 4917                serialize_workspace = *focus_changed || pane != self.active_pane();
 4918                if pane == self.active_pane() {
 4919                    self.active_item_path_changed(*focus_changed, window, cx);
 4920                    self.update_active_view_for_followers(window, cx);
 4921                } else if *local {
 4922                    self.set_active_pane(pane, window, cx);
 4923                }
 4924            }
 4925            pane::Event::UserSavedItem { item, save_intent } => {
 4926                cx.emit(Event::UserSavedItem {
 4927                    pane: pane.downgrade(),
 4928                    item: item.boxed_clone(),
 4929                    save_intent: *save_intent,
 4930                });
 4931                serialize_workspace = false;
 4932            }
 4933            pane::Event::ChangeItemTitle => {
 4934                if *pane == self.active_pane {
 4935                    self.active_item_path_changed(false, window, cx);
 4936                }
 4937                serialize_workspace = false;
 4938            }
 4939            pane::Event::RemovedItem { item } => {
 4940                cx.emit(Event::ActiveItemChanged);
 4941                self.update_window_edited(window, cx);
 4942                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 4943                    && entry.get().entity_id() == pane.entity_id()
 4944                {
 4945                    entry.remove();
 4946                }
 4947                cx.emit(Event::ItemRemoved {
 4948                    item_id: item.item_id(),
 4949                });
 4950            }
 4951            pane::Event::Focus => {
 4952                window.invalidate_character_coordinates();
 4953                self.handle_pane_focused(pane.clone(), window, cx);
 4954            }
 4955            pane::Event::ZoomIn => {
 4956                if *pane == self.active_pane {
 4957                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 4958                    if pane.read(cx).has_focus(window, cx) {
 4959                        self.zoomed = Some(pane.downgrade().into());
 4960                        self.zoomed_position = None;
 4961                        cx.emit(Event::ZoomChanged);
 4962                    }
 4963                    cx.notify();
 4964                }
 4965            }
 4966            pane::Event::ZoomOut => {
 4967                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4968                if self.zoomed_position.is_none() {
 4969                    self.zoomed = None;
 4970                    cx.emit(Event::ZoomChanged);
 4971                }
 4972                cx.notify();
 4973            }
 4974            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 4975        }
 4976
 4977        if serialize_workspace {
 4978            self.serialize_workspace(window, cx);
 4979        }
 4980    }
 4981
 4982    pub fn unfollow_in_pane(
 4983        &mut self,
 4984        pane: &Entity<Pane>,
 4985        window: &mut Window,
 4986        cx: &mut Context<Workspace>,
 4987    ) -> Option<CollaboratorId> {
 4988        let leader_id = self.leader_for_pane(pane)?;
 4989        self.unfollow(leader_id, window, cx);
 4990        Some(leader_id)
 4991    }
 4992
 4993    pub fn split_pane(
 4994        &mut self,
 4995        pane_to_split: Entity<Pane>,
 4996        split_direction: SplitDirection,
 4997        window: &mut Window,
 4998        cx: &mut Context<Self>,
 4999    ) -> Entity<Pane> {
 5000        let new_pane = self.add_pane(window, cx);
 5001        self.center
 5002            .split(&pane_to_split, &new_pane, split_direction, cx);
 5003        cx.notify();
 5004        new_pane
 5005    }
 5006
 5007    pub fn split_and_move(
 5008        &mut self,
 5009        pane: Entity<Pane>,
 5010        direction: SplitDirection,
 5011        window: &mut Window,
 5012        cx: &mut Context<Self>,
 5013    ) {
 5014        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 5015            return;
 5016        };
 5017        let new_pane = self.add_pane(window, cx);
 5018        new_pane.update(cx, |pane, cx| {
 5019            pane.add_item(item, true, true, None, window, cx)
 5020        });
 5021        self.center.split(&pane, &new_pane, direction, cx);
 5022        cx.notify();
 5023    }
 5024
 5025    pub fn split_and_clone(
 5026        &mut self,
 5027        pane: Entity<Pane>,
 5028        direction: SplitDirection,
 5029        window: &mut Window,
 5030        cx: &mut Context<Self>,
 5031    ) -> Task<Option<Entity<Pane>>> {
 5032        let Some(item) = pane.read(cx).active_item() else {
 5033            return Task::ready(None);
 5034        };
 5035        if !item.can_split(cx) {
 5036            return Task::ready(None);
 5037        }
 5038        let task = item.clone_on_split(self.database_id(), window, cx);
 5039        cx.spawn_in(window, async move |this, cx| {
 5040            if let Some(clone) = task.await {
 5041                this.update_in(cx, |this, window, cx| {
 5042                    let new_pane = this.add_pane(window, cx);
 5043                    let nav_history = pane.read(cx).fork_nav_history();
 5044                    new_pane.update(cx, |pane, cx| {
 5045                        pane.set_nav_history(nav_history, cx);
 5046                        pane.add_item(clone, true, true, None, window, cx)
 5047                    });
 5048                    this.center.split(&pane, &new_pane, direction, cx);
 5049                    cx.notify();
 5050                    new_pane
 5051                })
 5052                .ok()
 5053            } else {
 5054                None
 5055            }
 5056        })
 5057    }
 5058
 5059    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5060        let active_item = self.active_pane.read(cx).active_item();
 5061        for pane in &self.panes {
 5062            join_pane_into_active(&self.active_pane, pane, window, cx);
 5063        }
 5064        if let Some(active_item) = active_item {
 5065            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5066        }
 5067        cx.notify();
 5068    }
 5069
 5070    pub fn join_pane_into_next(
 5071        &mut self,
 5072        pane: Entity<Pane>,
 5073        window: &mut Window,
 5074        cx: &mut Context<Self>,
 5075    ) {
 5076        let next_pane = self
 5077            .find_pane_in_direction(SplitDirection::Right, cx)
 5078            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5079            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5080            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5081        let Some(next_pane) = next_pane else {
 5082            return;
 5083        };
 5084        move_all_items(&pane, &next_pane, window, cx);
 5085        cx.notify();
 5086    }
 5087
 5088    fn remove_pane(
 5089        &mut self,
 5090        pane: Entity<Pane>,
 5091        focus_on: Option<Entity<Pane>>,
 5092        window: &mut Window,
 5093        cx: &mut Context<Self>,
 5094    ) {
 5095        if self.center.remove(&pane, cx).unwrap() {
 5096            self.force_remove_pane(&pane, &focus_on, window, cx);
 5097            self.unfollow_in_pane(&pane, window, cx);
 5098            self.last_leaders_by_pane.remove(&pane.downgrade());
 5099            for removed_item in pane.read(cx).items() {
 5100                self.panes_by_item.remove(&removed_item.item_id());
 5101            }
 5102
 5103            cx.notify();
 5104        } else {
 5105            self.active_item_path_changed(true, window, cx);
 5106        }
 5107        cx.emit(Event::PaneRemoved);
 5108    }
 5109
 5110    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5111        &mut self.panes
 5112    }
 5113
 5114    pub fn panes(&self) -> &[Entity<Pane>] {
 5115        &self.panes
 5116    }
 5117
 5118    pub fn active_pane(&self) -> &Entity<Pane> {
 5119        &self.active_pane
 5120    }
 5121
 5122    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5123        for dock in self.all_docks() {
 5124            if dock.focus_handle(cx).contains_focused(window, cx)
 5125                && let Some(pane) = dock
 5126                    .read(cx)
 5127                    .active_panel()
 5128                    .and_then(|panel| panel.pane(cx))
 5129            {
 5130                return pane;
 5131            }
 5132        }
 5133        self.active_pane().clone()
 5134    }
 5135
 5136    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5137        self.find_pane_in_direction(SplitDirection::Right, cx)
 5138            .unwrap_or_else(|| {
 5139                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5140            })
 5141    }
 5142
 5143    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5144        self.pane_for_item_id(handle.item_id())
 5145    }
 5146
 5147    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5148        let weak_pane = self.panes_by_item.get(&item_id)?;
 5149        weak_pane.upgrade()
 5150    }
 5151
 5152    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5153        self.panes
 5154            .iter()
 5155            .find(|pane| pane.entity_id() == entity_id)
 5156            .cloned()
 5157    }
 5158
 5159    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5160        self.follower_states.retain(|leader_id, state| {
 5161            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5162                for item in state.items_by_leader_view_id.values() {
 5163                    item.view.set_leader_id(None, window, cx);
 5164                }
 5165                false
 5166            } else {
 5167                true
 5168            }
 5169        });
 5170        cx.notify();
 5171    }
 5172
 5173    pub fn start_following(
 5174        &mut self,
 5175        leader_id: impl Into<CollaboratorId>,
 5176        window: &mut Window,
 5177        cx: &mut Context<Self>,
 5178    ) -> Option<Task<Result<()>>> {
 5179        let leader_id = leader_id.into();
 5180        let pane = self.active_pane().clone();
 5181
 5182        self.last_leaders_by_pane
 5183            .insert(pane.downgrade(), leader_id);
 5184        self.unfollow(leader_id, window, cx);
 5185        self.unfollow_in_pane(&pane, window, cx);
 5186        self.follower_states.insert(
 5187            leader_id,
 5188            FollowerState {
 5189                center_pane: pane.clone(),
 5190                dock_pane: None,
 5191                active_view_id: None,
 5192                items_by_leader_view_id: Default::default(),
 5193            },
 5194        );
 5195        cx.notify();
 5196
 5197        match leader_id {
 5198            CollaboratorId::PeerId(leader_peer_id) => {
 5199                let room_id = self.active_call()?.room_id(cx)?;
 5200                let project_id = self.project.read(cx).remote_id();
 5201                let request = self.app_state.client.request(proto::Follow {
 5202                    room_id,
 5203                    project_id,
 5204                    leader_id: Some(leader_peer_id),
 5205                });
 5206
 5207                Some(cx.spawn_in(window, async move |this, cx| {
 5208                    let response = request.await?;
 5209                    this.update(cx, |this, _| {
 5210                        let state = this
 5211                            .follower_states
 5212                            .get_mut(&leader_id)
 5213                            .context("following interrupted")?;
 5214                        state.active_view_id = response
 5215                            .active_view
 5216                            .as_ref()
 5217                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5218                        anyhow::Ok(())
 5219                    })??;
 5220                    if let Some(view) = response.active_view {
 5221                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5222                    }
 5223                    this.update_in(cx, |this, window, cx| {
 5224                        this.leader_updated(leader_id, window, cx)
 5225                    })?;
 5226                    Ok(())
 5227                }))
 5228            }
 5229            CollaboratorId::Agent => {
 5230                self.leader_updated(leader_id, window, cx)?;
 5231                Some(Task::ready(Ok(())))
 5232            }
 5233        }
 5234    }
 5235
 5236    pub fn follow_next_collaborator(
 5237        &mut self,
 5238        _: &FollowNextCollaborator,
 5239        window: &mut Window,
 5240        cx: &mut Context<Self>,
 5241    ) {
 5242        let collaborators = self.project.read(cx).collaborators();
 5243        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5244            let mut collaborators = collaborators.keys().copied();
 5245            for peer_id in collaborators.by_ref() {
 5246                if CollaboratorId::PeerId(peer_id) == leader_id {
 5247                    break;
 5248                }
 5249            }
 5250            collaborators.next().map(CollaboratorId::PeerId)
 5251        } else if let Some(last_leader_id) =
 5252            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5253        {
 5254            match last_leader_id {
 5255                CollaboratorId::PeerId(peer_id) => {
 5256                    if collaborators.contains_key(peer_id) {
 5257                        Some(*last_leader_id)
 5258                    } else {
 5259                        None
 5260                    }
 5261                }
 5262                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5263            }
 5264        } else {
 5265            None
 5266        };
 5267
 5268        let pane = self.active_pane.clone();
 5269        let Some(leader_id) = next_leader_id.or_else(|| {
 5270            Some(CollaboratorId::PeerId(
 5271                collaborators.keys().copied().next()?,
 5272            ))
 5273        }) else {
 5274            return;
 5275        };
 5276        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5277            return;
 5278        }
 5279        if let Some(task) = self.start_following(leader_id, window, cx) {
 5280            task.detach_and_log_err(cx)
 5281        }
 5282    }
 5283
 5284    pub fn follow(
 5285        &mut self,
 5286        leader_id: impl Into<CollaboratorId>,
 5287        window: &mut Window,
 5288        cx: &mut Context<Self>,
 5289    ) {
 5290        let leader_id = leader_id.into();
 5291
 5292        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5293            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5294                return;
 5295            };
 5296            let Some(remote_participant) =
 5297                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5298            else {
 5299                return;
 5300            };
 5301
 5302            let project = self.project.read(cx);
 5303
 5304            let other_project_id = match remote_participant.location {
 5305                ParticipantLocation::External => None,
 5306                ParticipantLocation::UnsharedProject => None,
 5307                ParticipantLocation::SharedProject { project_id } => {
 5308                    if Some(project_id) == project.remote_id() {
 5309                        None
 5310                    } else {
 5311                        Some(project_id)
 5312                    }
 5313                }
 5314            };
 5315
 5316            // if they are active in another project, follow there.
 5317            if let Some(project_id) = other_project_id {
 5318                let app_state = self.app_state.clone();
 5319                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5320                    .detach_and_log_err(cx);
 5321            }
 5322        }
 5323
 5324        // if you're already following, find the right pane and focus it.
 5325        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5326            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5327
 5328            return;
 5329        }
 5330
 5331        // Otherwise, follow.
 5332        if let Some(task) = self.start_following(leader_id, window, cx) {
 5333            task.detach_and_log_err(cx)
 5334        }
 5335    }
 5336
 5337    pub fn unfollow(
 5338        &mut self,
 5339        leader_id: impl Into<CollaboratorId>,
 5340        window: &mut Window,
 5341        cx: &mut Context<Self>,
 5342    ) -> Option<()> {
 5343        cx.notify();
 5344
 5345        let leader_id = leader_id.into();
 5346        let state = self.follower_states.remove(&leader_id)?;
 5347        for (_, item) in state.items_by_leader_view_id {
 5348            item.view.set_leader_id(None, window, cx);
 5349        }
 5350
 5351        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5352            let project_id = self.project.read(cx).remote_id();
 5353            let room_id = self.active_call()?.room_id(cx)?;
 5354            self.app_state
 5355                .client
 5356                .send(proto::Unfollow {
 5357                    room_id,
 5358                    project_id,
 5359                    leader_id: Some(leader_peer_id),
 5360                })
 5361                .log_err();
 5362        }
 5363
 5364        Some(())
 5365    }
 5366
 5367    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5368        self.follower_states.contains_key(&id.into())
 5369    }
 5370
 5371    fn active_item_path_changed(
 5372        &mut self,
 5373        focus_changed: bool,
 5374        window: &mut Window,
 5375        cx: &mut Context<Self>,
 5376    ) {
 5377        cx.emit(Event::ActiveItemChanged);
 5378        let active_entry = self.active_project_path(cx);
 5379        self.project.update(cx, |project, cx| {
 5380            project.set_active_path(active_entry.clone(), cx)
 5381        });
 5382
 5383        if focus_changed && let Some(project_path) = &active_entry {
 5384            let git_store_entity = self.project.read(cx).git_store().clone();
 5385            git_store_entity.update(cx, |git_store, cx| {
 5386                git_store.set_active_repo_for_path(project_path, cx);
 5387            });
 5388        }
 5389
 5390        self.update_window_title(window, cx);
 5391    }
 5392
 5393    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5394        let project = self.project().read(cx);
 5395        let mut title = String::new();
 5396
 5397        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5398            let name = {
 5399                let settings_location = SettingsLocation {
 5400                    worktree_id: worktree.read(cx).id(),
 5401                    path: RelPath::empty(),
 5402                };
 5403
 5404                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5405                match &settings.project_name {
 5406                    Some(name) => name.as_str(),
 5407                    None => worktree.read(cx).root_name_str(),
 5408                }
 5409            };
 5410            if i > 0 {
 5411                title.push_str(", ");
 5412            }
 5413            title.push_str(name);
 5414        }
 5415
 5416        if title.is_empty() {
 5417            title = "empty project".to_string();
 5418        }
 5419
 5420        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5421            let filename = path.path.file_name().or_else(|| {
 5422                Some(
 5423                    project
 5424                        .worktree_for_id(path.worktree_id, cx)?
 5425                        .read(cx)
 5426                        .root_name_str(),
 5427                )
 5428            });
 5429
 5430            if let Some(filename) = filename {
 5431                title.push_str("");
 5432                title.push_str(filename.as_ref());
 5433            }
 5434        }
 5435
 5436        if project.is_via_collab() {
 5437            title.push_str("");
 5438        } else if project.is_shared() {
 5439            title.push_str("");
 5440        }
 5441
 5442        if let Some(last_title) = self.last_window_title.as_ref()
 5443            && &title == last_title
 5444        {
 5445            return;
 5446        }
 5447        window.set_window_title(&title);
 5448        SystemWindowTabController::update_tab_title(
 5449            cx,
 5450            window.window_handle().window_id(),
 5451            SharedString::from(&title),
 5452        );
 5453        self.last_window_title = Some(title);
 5454    }
 5455
 5456    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5457        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5458        if is_edited != self.window_edited {
 5459            self.window_edited = is_edited;
 5460            window.set_window_edited(self.window_edited)
 5461        }
 5462    }
 5463
 5464    fn update_item_dirty_state(
 5465        &mut self,
 5466        item: &dyn ItemHandle,
 5467        window: &mut Window,
 5468        cx: &mut App,
 5469    ) {
 5470        let is_dirty = item.is_dirty(cx);
 5471        let item_id = item.item_id();
 5472        let was_dirty = self.dirty_items.contains_key(&item_id);
 5473        if is_dirty == was_dirty {
 5474            return;
 5475        }
 5476        if was_dirty {
 5477            self.dirty_items.remove(&item_id);
 5478            self.update_window_edited(window, cx);
 5479            return;
 5480        }
 5481
 5482        let workspace = self.weak_handle();
 5483        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5484            return;
 5485        };
 5486        let on_release_callback = Box::new(move |cx: &mut App| {
 5487            window_handle
 5488                .update(cx, |_, window, cx| {
 5489                    workspace
 5490                        .update(cx, |workspace, cx| {
 5491                            workspace.dirty_items.remove(&item_id);
 5492                            workspace.update_window_edited(window, cx)
 5493                        })
 5494                        .ok();
 5495                })
 5496                .ok();
 5497        });
 5498
 5499        let s = item.on_release(cx, on_release_callback);
 5500        self.dirty_items.insert(item_id, s);
 5501        self.update_window_edited(window, cx);
 5502    }
 5503
 5504    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5505        if self.notifications.is_empty() {
 5506            None
 5507        } else {
 5508            Some(
 5509                div()
 5510                    .absolute()
 5511                    .right_3()
 5512                    .bottom_3()
 5513                    .w_112()
 5514                    .h_full()
 5515                    .flex()
 5516                    .flex_col()
 5517                    .justify_end()
 5518                    .gap_2()
 5519                    .children(
 5520                        self.notifications
 5521                            .iter()
 5522                            .map(|(_, notification)| notification.clone().into_any()),
 5523                    ),
 5524            )
 5525        }
 5526    }
 5527
 5528    // RPC handlers
 5529
 5530    fn active_view_for_follower(
 5531        &self,
 5532        follower_project_id: Option<u64>,
 5533        window: &mut Window,
 5534        cx: &mut Context<Self>,
 5535    ) -> Option<proto::View> {
 5536        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5537        let item = item?;
 5538        let leader_id = self
 5539            .pane_for(&*item)
 5540            .and_then(|pane| self.leader_for_pane(&pane));
 5541        let leader_peer_id = match leader_id {
 5542            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5543            Some(CollaboratorId::Agent) | None => None,
 5544        };
 5545
 5546        let item_handle = item.to_followable_item_handle(cx)?;
 5547        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5548        let variant = item_handle.to_state_proto(window, cx)?;
 5549
 5550        if item_handle.is_project_item(window, cx)
 5551            && (follower_project_id.is_none()
 5552                || follower_project_id != self.project.read(cx).remote_id())
 5553        {
 5554            return None;
 5555        }
 5556
 5557        Some(proto::View {
 5558            id: id.to_proto(),
 5559            leader_id: leader_peer_id,
 5560            variant: Some(variant),
 5561            panel_id: panel_id.map(|id| id as i32),
 5562        })
 5563    }
 5564
 5565    fn handle_follow(
 5566        &mut self,
 5567        follower_project_id: Option<u64>,
 5568        window: &mut Window,
 5569        cx: &mut Context<Self>,
 5570    ) -> proto::FollowResponse {
 5571        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5572
 5573        cx.notify();
 5574        proto::FollowResponse {
 5575            views: active_view.iter().cloned().collect(),
 5576            active_view,
 5577        }
 5578    }
 5579
 5580    fn handle_update_followers(
 5581        &mut self,
 5582        leader_id: PeerId,
 5583        message: proto::UpdateFollowers,
 5584        _window: &mut Window,
 5585        _cx: &mut Context<Self>,
 5586    ) {
 5587        self.leader_updates_tx
 5588            .unbounded_send((leader_id, message))
 5589            .ok();
 5590    }
 5591
 5592    async fn process_leader_update(
 5593        this: &WeakEntity<Self>,
 5594        leader_id: PeerId,
 5595        update: proto::UpdateFollowers,
 5596        cx: &mut AsyncWindowContext,
 5597    ) -> Result<()> {
 5598        match update.variant.context("invalid update")? {
 5599            proto::update_followers::Variant::CreateView(view) => {
 5600                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5601                let should_add_view = this.update(cx, |this, _| {
 5602                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5603                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5604                    } else {
 5605                        anyhow::Ok(false)
 5606                    }
 5607                })??;
 5608
 5609                if should_add_view {
 5610                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5611                }
 5612            }
 5613            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5614                let should_add_view = this.update(cx, |this, _| {
 5615                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5616                        state.active_view_id = update_active_view
 5617                            .view
 5618                            .as_ref()
 5619                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5620
 5621                        if state.active_view_id.is_some_and(|view_id| {
 5622                            !state.items_by_leader_view_id.contains_key(&view_id)
 5623                        }) {
 5624                            anyhow::Ok(true)
 5625                        } else {
 5626                            anyhow::Ok(false)
 5627                        }
 5628                    } else {
 5629                        anyhow::Ok(false)
 5630                    }
 5631                })??;
 5632
 5633                if should_add_view && let Some(view) = update_active_view.view {
 5634                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5635                }
 5636            }
 5637            proto::update_followers::Variant::UpdateView(update_view) => {
 5638                let variant = update_view.variant.context("missing update view variant")?;
 5639                let id = update_view.id.context("missing update view id")?;
 5640                let mut tasks = Vec::new();
 5641                this.update_in(cx, |this, window, cx| {
 5642                    let project = this.project.clone();
 5643                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5644                        let view_id = ViewId::from_proto(id.clone())?;
 5645                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5646                            tasks.push(item.view.apply_update_proto(
 5647                                &project,
 5648                                variant.clone(),
 5649                                window,
 5650                                cx,
 5651                            ));
 5652                        }
 5653                    }
 5654                    anyhow::Ok(())
 5655                })??;
 5656                try_join_all(tasks).await.log_err();
 5657            }
 5658        }
 5659        this.update_in(cx, |this, window, cx| {
 5660            this.leader_updated(leader_id, window, cx)
 5661        })?;
 5662        Ok(())
 5663    }
 5664
 5665    async fn add_view_from_leader(
 5666        this: WeakEntity<Self>,
 5667        leader_id: PeerId,
 5668        view: &proto::View,
 5669        cx: &mut AsyncWindowContext,
 5670    ) -> Result<()> {
 5671        let this = this.upgrade().context("workspace dropped")?;
 5672
 5673        let Some(id) = view.id.clone() else {
 5674            anyhow::bail!("no id for view");
 5675        };
 5676        let id = ViewId::from_proto(id)?;
 5677        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5678
 5679        let pane = this.update(cx, |this, _cx| {
 5680            let state = this
 5681                .follower_states
 5682                .get(&leader_id.into())
 5683                .context("stopped following")?;
 5684            anyhow::Ok(state.pane().clone())
 5685        })?;
 5686        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5687            let client = this.read(cx).client().clone();
 5688            pane.items().find_map(|item| {
 5689                let item = item.to_followable_item_handle(cx)?;
 5690                if item.remote_id(&client, window, cx) == Some(id) {
 5691                    Some(item)
 5692                } else {
 5693                    None
 5694                }
 5695            })
 5696        })?;
 5697        let item = if let Some(existing_item) = existing_item {
 5698            existing_item
 5699        } else {
 5700            let variant = view.variant.clone();
 5701            anyhow::ensure!(variant.is_some(), "missing view variant");
 5702
 5703            let task = cx.update(|window, cx| {
 5704                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5705            })?;
 5706
 5707            let Some(task) = task else {
 5708                anyhow::bail!(
 5709                    "failed to construct view from leader (maybe from a different version of zed?)"
 5710                );
 5711            };
 5712
 5713            let mut new_item = task.await?;
 5714            pane.update_in(cx, |pane, window, cx| {
 5715                let mut item_to_remove = None;
 5716                for (ix, item) in pane.items().enumerate() {
 5717                    if let Some(item) = item.to_followable_item_handle(cx) {
 5718                        match new_item.dedup(item.as_ref(), window, cx) {
 5719                            Some(item::Dedup::KeepExisting) => {
 5720                                new_item =
 5721                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5722                                break;
 5723                            }
 5724                            Some(item::Dedup::ReplaceExisting) => {
 5725                                item_to_remove = Some((ix, item.item_id()));
 5726                                break;
 5727                            }
 5728                            None => {}
 5729                        }
 5730                    }
 5731                }
 5732
 5733                if let Some((ix, id)) = item_to_remove {
 5734                    pane.remove_item(id, false, false, window, cx);
 5735                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5736                }
 5737            })?;
 5738
 5739            new_item
 5740        };
 5741
 5742        this.update_in(cx, |this, window, cx| {
 5743            let state = this.follower_states.get_mut(&leader_id.into())?;
 5744            item.set_leader_id(Some(leader_id.into()), window, cx);
 5745            state.items_by_leader_view_id.insert(
 5746                id,
 5747                FollowerView {
 5748                    view: item,
 5749                    location: panel_id,
 5750                },
 5751            );
 5752
 5753            Some(())
 5754        })
 5755        .context("no follower state")?;
 5756
 5757        Ok(())
 5758    }
 5759
 5760    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5761        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5762            return;
 5763        };
 5764
 5765        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5766            let buffer_entity_id = agent_location.buffer.entity_id();
 5767            let view_id = ViewId {
 5768                creator: CollaboratorId::Agent,
 5769                id: buffer_entity_id.as_u64(),
 5770            };
 5771            follower_state.active_view_id = Some(view_id);
 5772
 5773            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5774                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5775                hash_map::Entry::Vacant(entry) => {
 5776                    let existing_view =
 5777                        follower_state
 5778                            .center_pane
 5779                            .read(cx)
 5780                            .items()
 5781                            .find_map(|item| {
 5782                                let item = item.to_followable_item_handle(cx)?;
 5783                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5784                                    && item.project_item_model_ids(cx).as_slice()
 5785                                        == [buffer_entity_id]
 5786                                {
 5787                                    Some(item)
 5788                                } else {
 5789                                    None
 5790                                }
 5791                            });
 5792                    let view = existing_view.or_else(|| {
 5793                        agent_location.buffer.upgrade().and_then(|buffer| {
 5794                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 5795                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 5796                            })?
 5797                            .to_followable_item_handle(cx)
 5798                        })
 5799                    });
 5800
 5801                    view.map(|view| {
 5802                        entry.insert(FollowerView {
 5803                            view,
 5804                            location: None,
 5805                        })
 5806                    })
 5807                }
 5808            };
 5809
 5810            if let Some(item) = item {
 5811                item.view
 5812                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 5813                item.view
 5814                    .update_agent_location(agent_location.position, window, cx);
 5815            }
 5816        } else {
 5817            follower_state.active_view_id = None;
 5818        }
 5819
 5820        self.leader_updated(CollaboratorId::Agent, window, cx);
 5821    }
 5822
 5823    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 5824        let mut is_project_item = true;
 5825        let mut update = proto::UpdateActiveView::default();
 5826        if window.is_window_active() {
 5827            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 5828
 5829            if let Some(item) = active_item
 5830                && item.item_focus_handle(cx).contains_focused(window, cx)
 5831            {
 5832                let leader_id = self
 5833                    .pane_for(&*item)
 5834                    .and_then(|pane| self.leader_for_pane(&pane));
 5835                let leader_peer_id = match leader_id {
 5836                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5837                    Some(CollaboratorId::Agent) | None => None,
 5838                };
 5839
 5840                if let Some(item) = item.to_followable_item_handle(cx) {
 5841                    let id = item
 5842                        .remote_id(&self.app_state.client, window, cx)
 5843                        .map(|id| id.to_proto());
 5844
 5845                    if let Some(id) = id
 5846                        && let Some(variant) = item.to_state_proto(window, cx)
 5847                    {
 5848                        let view = Some(proto::View {
 5849                            id,
 5850                            leader_id: leader_peer_id,
 5851                            variant: Some(variant),
 5852                            panel_id: panel_id.map(|id| id as i32),
 5853                        });
 5854
 5855                        is_project_item = item.is_project_item(window, cx);
 5856                        update = proto::UpdateActiveView { view };
 5857                    };
 5858                }
 5859            }
 5860        }
 5861
 5862        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 5863        if active_view_id != self.last_active_view_id.as_ref() {
 5864            self.last_active_view_id = active_view_id.cloned();
 5865            self.update_followers(
 5866                is_project_item,
 5867                proto::update_followers::Variant::UpdateActiveView(update),
 5868                window,
 5869                cx,
 5870            );
 5871        }
 5872    }
 5873
 5874    fn active_item_for_followers(
 5875        &self,
 5876        window: &mut Window,
 5877        cx: &mut App,
 5878    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 5879        let mut active_item = None;
 5880        let mut panel_id = None;
 5881        for dock in self.all_docks() {
 5882            if dock.focus_handle(cx).contains_focused(window, cx)
 5883                && let Some(panel) = dock.read(cx).active_panel()
 5884                && let Some(pane) = panel.pane(cx)
 5885                && let Some(item) = pane.read(cx).active_item()
 5886            {
 5887                active_item = Some(item);
 5888                panel_id = panel.remote_id();
 5889                break;
 5890            }
 5891        }
 5892
 5893        if active_item.is_none() {
 5894            active_item = self.active_pane().read(cx).active_item();
 5895        }
 5896        (active_item, panel_id)
 5897    }
 5898
 5899    fn update_followers(
 5900        &self,
 5901        project_only: bool,
 5902        update: proto::update_followers::Variant,
 5903        _: &mut Window,
 5904        cx: &mut App,
 5905    ) -> Option<()> {
 5906        // If this update only applies to for followers in the current project,
 5907        // then skip it unless this project is shared. If it applies to all
 5908        // followers, regardless of project, then set `project_id` to none,
 5909        // indicating that it goes to all followers.
 5910        let project_id = if project_only {
 5911            Some(self.project.read(cx).remote_id()?)
 5912        } else {
 5913            None
 5914        };
 5915        self.app_state().workspace_store.update(cx, |store, cx| {
 5916            store.update_followers(project_id, update, cx)
 5917        })
 5918    }
 5919
 5920    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 5921        self.follower_states.iter().find_map(|(leader_id, state)| {
 5922            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 5923                Some(*leader_id)
 5924            } else {
 5925                None
 5926            }
 5927        })
 5928    }
 5929
 5930    fn leader_updated(
 5931        &mut self,
 5932        leader_id: impl Into<CollaboratorId>,
 5933        window: &mut Window,
 5934        cx: &mut Context<Self>,
 5935    ) -> Option<Box<dyn ItemHandle>> {
 5936        cx.notify();
 5937
 5938        let leader_id = leader_id.into();
 5939        let (panel_id, item) = match leader_id {
 5940            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 5941            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 5942        };
 5943
 5944        let state = self.follower_states.get(&leader_id)?;
 5945        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 5946        let pane;
 5947        if let Some(panel_id) = panel_id {
 5948            pane = self
 5949                .activate_panel_for_proto_id(panel_id, window, cx)?
 5950                .pane(cx)?;
 5951            let state = self.follower_states.get_mut(&leader_id)?;
 5952            state.dock_pane = Some(pane.clone());
 5953        } else {
 5954            pane = state.center_pane.clone();
 5955            let state = self.follower_states.get_mut(&leader_id)?;
 5956            if let Some(dock_pane) = state.dock_pane.take() {
 5957                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 5958            }
 5959        }
 5960
 5961        pane.update(cx, |pane, cx| {
 5962            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 5963            if let Some(index) = pane.index_for_item(item.as_ref()) {
 5964                pane.activate_item(index, false, false, window, cx);
 5965            } else {
 5966                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 5967            }
 5968
 5969            if focus_active_item {
 5970                pane.focus_active_item(window, cx)
 5971            }
 5972        });
 5973
 5974        Some(item)
 5975    }
 5976
 5977    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 5978        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 5979        let active_view_id = state.active_view_id?;
 5980        Some(
 5981            state
 5982                .items_by_leader_view_id
 5983                .get(&active_view_id)?
 5984                .view
 5985                .boxed_clone(),
 5986        )
 5987    }
 5988
 5989    fn active_item_for_peer(
 5990        &self,
 5991        peer_id: PeerId,
 5992        window: &mut Window,
 5993        cx: &mut Context<Self>,
 5994    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 5995        let call = self.active_call()?;
 5996        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 5997        let leader_in_this_app;
 5998        let leader_in_this_project;
 5999        match participant.location {
 6000            ParticipantLocation::SharedProject { project_id } => {
 6001                leader_in_this_app = true;
 6002                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 6003            }
 6004            ParticipantLocation::UnsharedProject => {
 6005                leader_in_this_app = true;
 6006                leader_in_this_project = false;
 6007            }
 6008            ParticipantLocation::External => {
 6009                leader_in_this_app = false;
 6010                leader_in_this_project = false;
 6011            }
 6012        };
 6013        let state = self.follower_states.get(&peer_id.into())?;
 6014        let mut item_to_activate = None;
 6015        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 6016            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 6017                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 6018            {
 6019                item_to_activate = Some((item.location, item.view.boxed_clone()));
 6020            }
 6021        } else if let Some(shared_screen) =
 6022            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 6023        {
 6024            item_to_activate = Some((None, Box::new(shared_screen)));
 6025        }
 6026        item_to_activate
 6027    }
 6028
 6029    fn shared_screen_for_peer(
 6030        &self,
 6031        peer_id: PeerId,
 6032        pane: &Entity<Pane>,
 6033        window: &mut Window,
 6034        cx: &mut App,
 6035    ) -> Option<Entity<SharedScreen>> {
 6036        self.active_call()?
 6037            .create_shared_screen(peer_id, pane, window, cx)
 6038    }
 6039
 6040    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6041        if window.is_window_active() {
 6042            self.update_active_view_for_followers(window, cx);
 6043
 6044            if let Some(database_id) = self.database_id {
 6045                let db = WorkspaceDb::global(cx);
 6046                cx.background_spawn(async move { db.update_timestamp(database_id).await })
 6047                    .detach();
 6048            }
 6049        } else {
 6050            for pane in &self.panes {
 6051                pane.update(cx, |pane, cx| {
 6052                    if let Some(item) = pane.active_item() {
 6053                        item.workspace_deactivated(window, cx);
 6054                    }
 6055                    for item in pane.items() {
 6056                        if matches!(
 6057                            item.workspace_settings(cx).autosave,
 6058                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6059                        ) {
 6060                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6061                                .detach_and_log_err(cx);
 6062                        }
 6063                    }
 6064                });
 6065            }
 6066        }
 6067    }
 6068
 6069    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6070        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6071    }
 6072
 6073    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6074        self.active_call.as_ref().map(|(call, _)| call.clone())
 6075    }
 6076
 6077    fn on_active_call_event(
 6078        &mut self,
 6079        event: &ActiveCallEvent,
 6080        window: &mut Window,
 6081        cx: &mut Context<Self>,
 6082    ) {
 6083        match event {
 6084            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6085            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6086                self.leader_updated(participant_id, window, cx);
 6087            }
 6088        }
 6089    }
 6090
 6091    pub fn database_id(&self) -> Option<WorkspaceId> {
 6092        self.database_id
 6093    }
 6094
 6095    #[cfg(any(test, feature = "test-support"))]
 6096    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6097        self.database_id = Some(id);
 6098    }
 6099
 6100    pub fn session_id(&self) -> Option<String> {
 6101        self.session_id.clone()
 6102    }
 6103
 6104    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6105        let Some(display) = window.display(cx) else {
 6106            return Task::ready(());
 6107        };
 6108        let Ok(display_uuid) = display.uuid() else {
 6109            return Task::ready(());
 6110        };
 6111
 6112        let window_bounds = window.inner_window_bounds();
 6113        let database_id = self.database_id;
 6114        let has_paths = !self.root_paths(cx).is_empty();
 6115        let db = WorkspaceDb::global(cx);
 6116        let kvp = db::kvp::KeyValueStore::global(cx);
 6117
 6118        cx.background_executor().spawn(async move {
 6119            if !has_paths {
 6120                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6121                    .await
 6122                    .log_err();
 6123            }
 6124            if let Some(database_id) = database_id {
 6125                db.set_window_open_status(
 6126                    database_id,
 6127                    SerializedWindowBounds(window_bounds),
 6128                    display_uuid,
 6129                )
 6130                .await
 6131                .log_err();
 6132            } else {
 6133                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6134                    .await
 6135                    .log_err();
 6136            }
 6137        })
 6138    }
 6139
 6140    /// Bypass the 200ms serialization throttle and write workspace state to
 6141    /// the DB immediately. Returns a task the caller can await to ensure the
 6142    /// write completes. Used by the quit handler so the most recent state
 6143    /// isn't lost to a pending throttle timer when the process exits.
 6144    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6145        self._schedule_serialize_workspace.take();
 6146        self._serialize_workspace_task.take();
 6147        self.bounds_save_task_queued.take();
 6148
 6149        let bounds_task = self.save_window_bounds(window, cx);
 6150        let serialize_task = self.serialize_workspace_internal(window, cx);
 6151        cx.spawn(async move |_| {
 6152            bounds_task.await;
 6153            serialize_task.await;
 6154        })
 6155    }
 6156
 6157    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6158        let project = self.project().read(cx);
 6159        project
 6160            .visible_worktrees(cx)
 6161            .map(|worktree| worktree.read(cx).abs_path())
 6162            .collect::<Vec<_>>()
 6163    }
 6164
 6165    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6166        match member {
 6167            Member::Axis(PaneAxis { members, .. }) => {
 6168                for child in members.iter() {
 6169                    self.remove_panes(child.clone(), window, cx)
 6170                }
 6171            }
 6172            Member::Pane(pane) => {
 6173                self.force_remove_pane(&pane, &None, window, cx);
 6174            }
 6175        }
 6176    }
 6177
 6178    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6179        self.session_id.take();
 6180        self.serialize_workspace_internal(window, cx)
 6181    }
 6182
 6183    fn force_remove_pane(
 6184        &mut self,
 6185        pane: &Entity<Pane>,
 6186        focus_on: &Option<Entity<Pane>>,
 6187        window: &mut Window,
 6188        cx: &mut Context<Workspace>,
 6189    ) {
 6190        self.panes.retain(|p| p != pane);
 6191        if let Some(focus_on) = focus_on {
 6192            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6193        } else if self.active_pane() == pane {
 6194            self.panes
 6195                .last()
 6196                .unwrap()
 6197                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6198        }
 6199        if self.last_active_center_pane == Some(pane.downgrade()) {
 6200            self.last_active_center_pane = None;
 6201        }
 6202        cx.notify();
 6203    }
 6204
 6205    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6206        if self._schedule_serialize_workspace.is_none() {
 6207            self._schedule_serialize_workspace =
 6208                Some(cx.spawn_in(window, async move |this, cx| {
 6209                    cx.background_executor()
 6210                        .timer(SERIALIZATION_THROTTLE_TIME)
 6211                        .await;
 6212                    this.update_in(cx, |this, window, cx| {
 6213                        this._serialize_workspace_task =
 6214                            Some(this.serialize_workspace_internal(window, cx));
 6215                        this._schedule_serialize_workspace.take();
 6216                    })
 6217                    .log_err();
 6218                }));
 6219        }
 6220    }
 6221
 6222    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6223        let Some(database_id) = self.database_id() else {
 6224            return Task::ready(());
 6225        };
 6226
 6227        fn serialize_pane_handle(
 6228            pane_handle: &Entity<Pane>,
 6229            window: &mut Window,
 6230            cx: &mut App,
 6231        ) -> SerializedPane {
 6232            let (items, active, pinned_count) = {
 6233                let pane = pane_handle.read(cx);
 6234                let active_item_id = pane.active_item().map(|item| item.item_id());
 6235                (
 6236                    pane.items()
 6237                        .filter_map(|handle| {
 6238                            let handle = handle.to_serializable_item_handle(cx)?;
 6239
 6240                            Some(SerializedItem {
 6241                                kind: Arc::from(handle.serialized_item_kind()),
 6242                                item_id: handle.item_id().as_u64(),
 6243                                active: Some(handle.item_id()) == active_item_id,
 6244                                preview: pane.is_active_preview_item(handle.item_id()),
 6245                            })
 6246                        })
 6247                        .collect::<Vec<_>>(),
 6248                    pane.has_focus(window, cx),
 6249                    pane.pinned_count(),
 6250                )
 6251            };
 6252
 6253            SerializedPane::new(items, active, pinned_count)
 6254        }
 6255
 6256        fn build_serialized_pane_group(
 6257            pane_group: &Member,
 6258            window: &mut Window,
 6259            cx: &mut App,
 6260        ) -> SerializedPaneGroup {
 6261            match pane_group {
 6262                Member::Axis(PaneAxis {
 6263                    axis,
 6264                    members,
 6265                    flexes,
 6266                    bounding_boxes: _,
 6267                }) => SerializedPaneGroup::Group {
 6268                    axis: SerializedAxis(*axis),
 6269                    children: members
 6270                        .iter()
 6271                        .map(|member| build_serialized_pane_group(member, window, cx))
 6272                        .collect::<Vec<_>>(),
 6273                    flexes: Some(flexes.lock().clone()),
 6274                },
 6275                Member::Pane(pane_handle) => {
 6276                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6277                }
 6278            }
 6279        }
 6280
 6281        fn build_serialized_docks(
 6282            this: &Workspace,
 6283            window: &mut Window,
 6284            cx: &mut App,
 6285        ) -> DockStructure {
 6286            this.capture_dock_state(window, cx)
 6287        }
 6288
 6289        match self.workspace_location(cx) {
 6290            WorkspaceLocation::Location(location, paths) => {
 6291                let breakpoints = self.project.update(cx, |project, cx| {
 6292                    project
 6293                        .breakpoint_store()
 6294                        .read(cx)
 6295                        .all_source_breakpoints(cx)
 6296                });
 6297                let user_toolchains = self
 6298                    .project
 6299                    .read(cx)
 6300                    .user_toolchains(cx)
 6301                    .unwrap_or_default();
 6302
 6303                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6304                let docks = build_serialized_docks(self, window, cx);
 6305                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6306
 6307                let serialized_workspace = SerializedWorkspace {
 6308                    id: database_id,
 6309                    location,
 6310                    paths,
 6311                    center_group,
 6312                    window_bounds,
 6313                    display: Default::default(),
 6314                    docks,
 6315                    centered_layout: self.centered_layout,
 6316                    session_id: self.session_id.clone(),
 6317                    breakpoints,
 6318                    window_id: Some(window.window_handle().window_id().as_u64()),
 6319                    user_toolchains,
 6320                };
 6321
 6322                let db = WorkspaceDb::global(cx);
 6323                window.spawn(cx, async move |_| {
 6324                    db.save_workspace(serialized_workspace).await;
 6325                })
 6326            }
 6327            WorkspaceLocation::DetachFromSession => {
 6328                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6329                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6330                // Save dock state for empty local workspaces
 6331                let docks = build_serialized_docks(self, window, cx);
 6332                let db = WorkspaceDb::global(cx);
 6333                let kvp = db::kvp::KeyValueStore::global(cx);
 6334                window.spawn(cx, async move |_| {
 6335                    db.set_window_open_status(
 6336                        database_id,
 6337                        window_bounds,
 6338                        display.unwrap_or_default(),
 6339                    )
 6340                    .await
 6341                    .log_err();
 6342                    db.set_session_id(database_id, None).await.log_err();
 6343                    persistence::write_default_dock_state(&kvp, docks)
 6344                        .await
 6345                        .log_err();
 6346                })
 6347            }
 6348            WorkspaceLocation::None => {
 6349                // Save dock state for empty non-local workspaces
 6350                let docks = build_serialized_docks(self, window, cx);
 6351                let kvp = db::kvp::KeyValueStore::global(cx);
 6352                window.spawn(cx, async move |_| {
 6353                    persistence::write_default_dock_state(&kvp, docks)
 6354                        .await
 6355                        .log_err();
 6356                })
 6357            }
 6358        }
 6359    }
 6360
 6361    fn has_any_items_open(&self, cx: &App) -> bool {
 6362        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6363    }
 6364
 6365    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6366        let paths = PathList::new(&self.root_paths(cx));
 6367        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6368            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6369        } else if self.project.read(cx).is_local() {
 6370            if !paths.is_empty() || self.has_any_items_open(cx) {
 6371                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6372            } else {
 6373                WorkspaceLocation::DetachFromSession
 6374            }
 6375        } else {
 6376            WorkspaceLocation::None
 6377        }
 6378    }
 6379
 6380    fn update_history(&self, cx: &mut App) {
 6381        let Some(id) = self.database_id() else {
 6382            return;
 6383        };
 6384        if !self.project.read(cx).is_local() {
 6385            return;
 6386        }
 6387        if let Some(manager) = HistoryManager::global(cx) {
 6388            let paths = PathList::new(&self.root_paths(cx));
 6389            manager.update(cx, |this, cx| {
 6390                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6391            });
 6392        }
 6393    }
 6394
 6395    async fn serialize_items(
 6396        this: &WeakEntity<Self>,
 6397        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6398        cx: &mut AsyncWindowContext,
 6399    ) -> Result<()> {
 6400        const CHUNK_SIZE: usize = 200;
 6401
 6402        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6403
 6404        while let Some(items_received) = serializable_items.next().await {
 6405            let unique_items =
 6406                items_received
 6407                    .into_iter()
 6408                    .fold(HashMap::default(), |mut acc, item| {
 6409                        acc.entry(item.item_id()).or_insert(item);
 6410                        acc
 6411                    });
 6412
 6413            // We use into_iter() here so that the references to the items are moved into
 6414            // the tasks and not kept alive while we're sleeping.
 6415            for (_, item) in unique_items.into_iter() {
 6416                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6417                    item.serialize(workspace, false, window, cx)
 6418                }) {
 6419                    cx.background_spawn(async move { task.await.log_err() })
 6420                        .detach();
 6421                }
 6422            }
 6423
 6424            cx.background_executor()
 6425                .timer(SERIALIZATION_THROTTLE_TIME)
 6426                .await;
 6427        }
 6428
 6429        Ok(())
 6430    }
 6431
 6432    pub(crate) fn enqueue_item_serialization(
 6433        &mut self,
 6434        item: Box<dyn SerializableItemHandle>,
 6435    ) -> Result<()> {
 6436        self.serializable_items_tx
 6437            .unbounded_send(item)
 6438            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6439    }
 6440
 6441    pub(crate) fn load_workspace(
 6442        serialized_workspace: SerializedWorkspace,
 6443        paths_to_open: Vec<Option<ProjectPath>>,
 6444        window: &mut Window,
 6445        cx: &mut Context<Workspace>,
 6446    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6447        cx.spawn_in(window, async move |workspace, cx| {
 6448            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6449
 6450            let mut center_group = None;
 6451            let mut center_items = None;
 6452
 6453            // Traverse the splits tree and add to things
 6454            if let Some((group, active_pane, items)) = serialized_workspace
 6455                .center_group
 6456                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6457                .await
 6458            {
 6459                center_items = Some(items);
 6460                center_group = Some((group, active_pane))
 6461            }
 6462
 6463            let mut items_by_project_path = HashMap::default();
 6464            let mut item_ids_by_kind = HashMap::default();
 6465            let mut all_deserialized_items = Vec::default();
 6466            cx.update(|_, cx| {
 6467                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6468                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6469                        item_ids_by_kind
 6470                            .entry(serializable_item_handle.serialized_item_kind())
 6471                            .or_insert(Vec::new())
 6472                            .push(item.item_id().as_u64() as ItemId);
 6473                    }
 6474
 6475                    if let Some(project_path) = item.project_path(cx) {
 6476                        items_by_project_path.insert(project_path, item.clone());
 6477                    }
 6478                    all_deserialized_items.push(item);
 6479                }
 6480            })?;
 6481
 6482            let opened_items = paths_to_open
 6483                .into_iter()
 6484                .map(|path_to_open| {
 6485                    path_to_open
 6486                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6487                })
 6488                .collect::<Vec<_>>();
 6489
 6490            // Remove old panes from workspace panes list
 6491            workspace.update_in(cx, |workspace, window, cx| {
 6492                if let Some((center_group, active_pane)) = center_group {
 6493                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6494
 6495                    // Swap workspace center group
 6496                    workspace.center = PaneGroup::with_root(center_group);
 6497                    workspace.center.set_is_center(true);
 6498                    workspace.center.mark_positions(cx);
 6499
 6500                    if let Some(active_pane) = active_pane {
 6501                        workspace.set_active_pane(&active_pane, window, cx);
 6502                        cx.focus_self(window);
 6503                    } else {
 6504                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6505                    }
 6506                }
 6507
 6508                let docks = serialized_workspace.docks;
 6509
 6510                for (dock, serialized_dock) in [
 6511                    (&mut workspace.right_dock, docks.right),
 6512                    (&mut workspace.left_dock, docks.left),
 6513                    (&mut workspace.bottom_dock, docks.bottom),
 6514                ]
 6515                .iter_mut()
 6516                {
 6517                    dock.update(cx, |dock, cx| {
 6518                        dock.serialized_dock = Some(serialized_dock.clone());
 6519                        dock.restore_state(window, cx);
 6520                    });
 6521                }
 6522
 6523                cx.notify();
 6524            })?;
 6525
 6526            let _ = project
 6527                .update(cx, |project, cx| {
 6528                    project
 6529                        .breakpoint_store()
 6530                        .update(cx, |breakpoint_store, cx| {
 6531                            breakpoint_store
 6532                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6533                        })
 6534                })
 6535                .await;
 6536
 6537            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6538            // after loading the items, we might have different items and in order to avoid
 6539            // the database filling up, we delete items that haven't been loaded now.
 6540            //
 6541            // The items that have been loaded, have been saved after they've been added to the workspace.
 6542            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6543                item_ids_by_kind
 6544                    .into_iter()
 6545                    .map(|(item_kind, loaded_items)| {
 6546                        SerializableItemRegistry::cleanup(
 6547                            item_kind,
 6548                            serialized_workspace.id,
 6549                            loaded_items,
 6550                            window,
 6551                            cx,
 6552                        )
 6553                        .log_err()
 6554                    })
 6555                    .collect::<Vec<_>>()
 6556            })?;
 6557
 6558            futures::future::join_all(clean_up_tasks).await;
 6559
 6560            workspace
 6561                .update_in(cx, |workspace, window, cx| {
 6562                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6563                    workspace.serialize_workspace_internal(window, cx).detach();
 6564
 6565                    // Ensure that we mark the window as edited if we did load dirty items
 6566                    workspace.update_window_edited(window, cx);
 6567                })
 6568                .ok();
 6569
 6570            Ok(opened_items)
 6571        })
 6572    }
 6573
 6574    pub fn key_context(&self, cx: &App) -> KeyContext {
 6575        let mut context = KeyContext::new_with_defaults();
 6576        context.add("Workspace");
 6577        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6578        if let Some(status) = self
 6579            .debugger_provider
 6580            .as_ref()
 6581            .and_then(|provider| provider.active_thread_state(cx))
 6582        {
 6583            match status {
 6584                ThreadStatus::Running | ThreadStatus::Stepping => {
 6585                    context.add("debugger_running");
 6586                }
 6587                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6588                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6589            }
 6590        }
 6591
 6592        if self.left_dock.read(cx).is_open() {
 6593            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6594                context.set("left_dock", active_panel.panel_key());
 6595            }
 6596        }
 6597
 6598        if self.right_dock.read(cx).is_open() {
 6599            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6600                context.set("right_dock", active_panel.panel_key());
 6601            }
 6602        }
 6603
 6604        if self.bottom_dock.read(cx).is_open() {
 6605            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6606                context.set("bottom_dock", active_panel.panel_key());
 6607            }
 6608        }
 6609
 6610        context
 6611    }
 6612
 6613    /// Multiworkspace uses this to add workspace action handling to itself
 6614    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6615        self.add_workspace_actions_listeners(div, window, cx)
 6616            .on_action(cx.listener(
 6617                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6618                    for action in &action_sequence.0 {
 6619                        window.dispatch_action(action.boxed_clone(), cx);
 6620                    }
 6621                },
 6622            ))
 6623            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6624            .on_action(cx.listener(Self::close_all_items_and_panes))
 6625            .on_action(cx.listener(Self::close_item_in_all_panes))
 6626            .on_action(cx.listener(Self::save_all))
 6627            .on_action(cx.listener(Self::send_keystrokes))
 6628            .on_action(cx.listener(Self::add_folder_to_project))
 6629            .on_action(cx.listener(Self::follow_next_collaborator))
 6630            .on_action(cx.listener(Self::activate_pane_at_index))
 6631            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6632            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6633            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6634            .on_action(cx.listener(Self::toggle_theme_mode))
 6635            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6636                let pane = workspace.active_pane().clone();
 6637                workspace.unfollow_in_pane(&pane, window, cx);
 6638            }))
 6639            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6640                workspace
 6641                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6642                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6643            }))
 6644            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6645                workspace
 6646                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6647                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6648            }))
 6649            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6650                workspace
 6651                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6652                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6653            }))
 6654            .on_action(
 6655                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6656                    workspace.activate_previous_pane(window, cx)
 6657                }),
 6658            )
 6659            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6660                workspace.activate_next_pane(window, cx)
 6661            }))
 6662            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6663                workspace.activate_last_pane(window, cx)
 6664            }))
 6665            .on_action(
 6666                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6667                    workspace.activate_next_window(cx)
 6668                }),
 6669            )
 6670            .on_action(
 6671                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6672                    workspace.activate_previous_window(cx)
 6673                }),
 6674            )
 6675            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6676                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6677            }))
 6678            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6679                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6680            }))
 6681            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6682                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6683            }))
 6684            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6685                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6686            }))
 6687            .on_action(cx.listener(
 6688                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6689                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6690                },
 6691            ))
 6692            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6693                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6694            }))
 6695            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6696                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6697            }))
 6698            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6699                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6700            }))
 6701            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6702                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6703            }))
 6704            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6705                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6706                    SplitDirection::Down,
 6707                    SplitDirection::Up,
 6708                    SplitDirection::Right,
 6709                    SplitDirection::Left,
 6710                ];
 6711                for dir in DIRECTION_PRIORITY {
 6712                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6713                        workspace.swap_pane_in_direction(dir, cx);
 6714                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6715                        break;
 6716                    }
 6717                }
 6718            }))
 6719            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6720                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6721            }))
 6722            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6723                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6724            }))
 6725            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6726                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6727            }))
 6728            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6729                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6730            }))
 6731            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6732                this.toggle_dock(DockPosition::Left, window, cx);
 6733            }))
 6734            .on_action(cx.listener(
 6735                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6736                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6737                },
 6738            ))
 6739            .on_action(cx.listener(
 6740                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6741                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6742                },
 6743            ))
 6744            .on_action(cx.listener(
 6745                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6746                    if !workspace.close_active_dock(window, cx) {
 6747                        cx.propagate();
 6748                    }
 6749                },
 6750            ))
 6751            .on_action(
 6752                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6753                    workspace.close_all_docks(window, cx);
 6754                }),
 6755            )
 6756            .on_action(cx.listener(Self::toggle_all_docks))
 6757            .on_action(cx.listener(
 6758                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6759                    workspace.clear_all_notifications(cx);
 6760                },
 6761            ))
 6762            .on_action(cx.listener(
 6763                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6764                    workspace.clear_navigation_history(window, cx);
 6765                },
 6766            ))
 6767            .on_action(cx.listener(
 6768                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6769                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6770                        workspace.suppress_notification(&notification_id, cx);
 6771                    }
 6772                },
 6773            ))
 6774            .on_action(cx.listener(
 6775                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6776                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6777                },
 6778            ))
 6779            .on_action(
 6780                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6781                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6782                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6783                            trusted_worktrees.clear_trusted_paths()
 6784                        });
 6785                        let db = WorkspaceDb::global(cx);
 6786                        cx.spawn(async move |_, cx| {
 6787                            if db.clear_trusted_worktrees().await.log_err().is_some() {
 6788                                cx.update(|cx| reload(cx));
 6789                            }
 6790                        })
 6791                        .detach();
 6792                    }
 6793                }),
 6794            )
 6795            .on_action(cx.listener(
 6796                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 6797                    workspace.reopen_closed_item(window, cx).detach();
 6798                },
 6799            ))
 6800            .on_action(cx.listener(
 6801                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 6802                    for dock in workspace.all_docks() {
 6803                        if dock.focus_handle(cx).contains_focused(window, cx) {
 6804                            let Some(panel) = dock.read(cx).active_panel() else {
 6805                                return;
 6806                            };
 6807
 6808                            // Set to `None`, then the size will fall back to the default.
 6809                            panel.clone().set_size(None, window, cx);
 6810
 6811                            return;
 6812                        }
 6813                    }
 6814                },
 6815            ))
 6816            .on_action(cx.listener(
 6817                |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
 6818                    for dock in workspace.all_docks() {
 6819                        if let Some(panel) = dock.read(cx).visible_panel() {
 6820                            // Set to `None`, then the size will fall back to the default.
 6821                            panel.clone().set_size(None, window, cx);
 6822                        }
 6823                    }
 6824                },
 6825            ))
 6826            .on_action(cx.listener(
 6827                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 6828                    adjust_active_dock_size_by_px(
 6829                        px_with_ui_font_fallback(act.px, cx),
 6830                        workspace,
 6831                        window,
 6832                        cx,
 6833                    );
 6834                },
 6835            ))
 6836            .on_action(cx.listener(
 6837                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 6838                    adjust_active_dock_size_by_px(
 6839                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6840                        workspace,
 6841                        window,
 6842                        cx,
 6843                    );
 6844                },
 6845            ))
 6846            .on_action(cx.listener(
 6847                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 6848                    adjust_open_docks_size_by_px(
 6849                        px_with_ui_font_fallback(act.px, cx),
 6850                        workspace,
 6851                        window,
 6852                        cx,
 6853                    );
 6854                },
 6855            ))
 6856            .on_action(cx.listener(
 6857                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 6858                    adjust_open_docks_size_by_px(
 6859                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6860                        workspace,
 6861                        window,
 6862                        cx,
 6863                    );
 6864                },
 6865            ))
 6866            .on_action(cx.listener(Workspace::toggle_centered_layout))
 6867            .on_action(cx.listener(
 6868                |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
 6869                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6870                        let dock = active_dock.read(cx);
 6871                        if let Some(active_panel) = dock.active_panel() {
 6872                            if active_panel.pane(cx).is_none() {
 6873                                let mut recent_pane: Option<Entity<Pane>> = None;
 6874                                let mut recent_timestamp = 0;
 6875                                for pane_handle in workspace.panes() {
 6876                                    let pane = pane_handle.read(cx);
 6877                                    for entry in pane.activation_history() {
 6878                                        if entry.timestamp > recent_timestamp {
 6879                                            recent_timestamp = entry.timestamp;
 6880                                            recent_pane = Some(pane_handle.clone());
 6881                                        }
 6882                                    }
 6883                                }
 6884
 6885                                if let Some(pane) = recent_pane {
 6886                                    pane.update(cx, |pane, cx| {
 6887                                        let current_index = pane.active_item_index();
 6888                                        let items_len = pane.items_len();
 6889                                        if items_len > 0 {
 6890                                            let next_index = if current_index + 1 < items_len {
 6891                                                current_index + 1
 6892                                            } else {
 6893                                                0
 6894                                            };
 6895                                            pane.activate_item(
 6896                                                next_index, false, false, window, cx,
 6897                                            );
 6898                                        }
 6899                                    });
 6900                                    return;
 6901                                }
 6902                            }
 6903                        }
 6904                    }
 6905                    cx.propagate();
 6906                },
 6907            ))
 6908            .on_action(cx.listener(
 6909                |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
 6910                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6911                        let dock = active_dock.read(cx);
 6912                        if let Some(active_panel) = dock.active_panel() {
 6913                            if active_panel.pane(cx).is_none() {
 6914                                let mut recent_pane: Option<Entity<Pane>> = None;
 6915                                let mut recent_timestamp = 0;
 6916                                for pane_handle in workspace.panes() {
 6917                                    let pane = pane_handle.read(cx);
 6918                                    for entry in pane.activation_history() {
 6919                                        if entry.timestamp > recent_timestamp {
 6920                                            recent_timestamp = entry.timestamp;
 6921                                            recent_pane = Some(pane_handle.clone());
 6922                                        }
 6923                                    }
 6924                                }
 6925
 6926                                if let Some(pane) = recent_pane {
 6927                                    pane.update(cx, |pane, cx| {
 6928                                        let current_index = pane.active_item_index();
 6929                                        let items_len = pane.items_len();
 6930                                        if items_len > 0 {
 6931                                            let prev_index = if current_index > 0 {
 6932                                                current_index - 1
 6933                                            } else {
 6934                                                items_len.saturating_sub(1)
 6935                                            };
 6936                                            pane.activate_item(
 6937                                                prev_index, false, false, window, cx,
 6938                                            );
 6939                                        }
 6940                                    });
 6941                                    return;
 6942                                }
 6943                            }
 6944                        }
 6945                    }
 6946                    cx.propagate();
 6947                },
 6948            ))
 6949            .on_action(cx.listener(
 6950                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 6951                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6952                        let dock = active_dock.read(cx);
 6953                        if let Some(active_panel) = dock.active_panel() {
 6954                            if active_panel.pane(cx).is_none() {
 6955                                let active_pane = workspace.active_pane().clone();
 6956                                active_pane.update(cx, |pane, cx| {
 6957                                    pane.close_active_item(action, window, cx)
 6958                                        .detach_and_log_err(cx);
 6959                                });
 6960                                return;
 6961                            }
 6962                        }
 6963                    }
 6964                    cx.propagate();
 6965                },
 6966            ))
 6967            .on_action(
 6968                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 6969                    let pane = workspace.active_pane().clone();
 6970                    if let Some(item) = pane.read(cx).active_item() {
 6971                        item.toggle_read_only(window, cx);
 6972                    }
 6973                }),
 6974            )
 6975            .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
 6976                workspace.focus_center_pane(window, cx);
 6977            }))
 6978            .on_action(cx.listener(Workspace::cancel))
 6979    }
 6980
 6981    #[cfg(any(test, feature = "test-support"))]
 6982    pub fn set_random_database_id(&mut self) {
 6983        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 6984    }
 6985
 6986    #[cfg(any(test, feature = "test-support"))]
 6987    pub(crate) fn test_new(
 6988        project: Entity<Project>,
 6989        window: &mut Window,
 6990        cx: &mut Context<Self>,
 6991    ) -> Self {
 6992        use node_runtime::NodeRuntime;
 6993        use session::Session;
 6994
 6995        let client = project.read(cx).client();
 6996        let user_store = project.read(cx).user_store();
 6997        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 6998        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 6999        window.activate_window();
 7000        let app_state = Arc::new(AppState {
 7001            languages: project.read(cx).languages().clone(),
 7002            workspace_store,
 7003            client,
 7004            user_store,
 7005            fs: project.read(cx).fs().clone(),
 7006            build_window_options: |_, _| Default::default(),
 7007            node_runtime: NodeRuntime::unavailable(),
 7008            session,
 7009        });
 7010        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 7011        workspace
 7012            .active_pane
 7013            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 7014        workspace
 7015    }
 7016
 7017    pub fn register_action<A: Action>(
 7018        &mut self,
 7019        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 7020    ) -> &mut Self {
 7021        let callback = Arc::new(callback);
 7022
 7023        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 7024            let callback = callback.clone();
 7025            div.on_action(cx.listener(move |workspace, event, window, cx| {
 7026                (callback)(workspace, event, window, cx)
 7027            }))
 7028        }));
 7029        self
 7030    }
 7031    pub fn register_action_renderer(
 7032        &mut self,
 7033        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 7034    ) -> &mut Self {
 7035        self.workspace_actions.push(Box::new(callback));
 7036        self
 7037    }
 7038
 7039    fn add_workspace_actions_listeners(
 7040        &self,
 7041        mut div: Div,
 7042        window: &mut Window,
 7043        cx: &mut Context<Self>,
 7044    ) -> Div {
 7045        for action in self.workspace_actions.iter() {
 7046            div = (action)(div, self, window, cx)
 7047        }
 7048        div
 7049    }
 7050
 7051    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 7052        self.modal_layer.read(cx).has_active_modal()
 7053    }
 7054
 7055    pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
 7056        self.modal_layer
 7057            .read(cx)
 7058            .is_active_modal_command_palette(cx)
 7059    }
 7060
 7061    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7062        self.modal_layer.read(cx).active_modal()
 7063    }
 7064
 7065    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7066    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7067    /// If no modal is active, the new modal will be shown.
 7068    ///
 7069    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7070    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7071    /// will not be shown.
 7072    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7073    where
 7074        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7075    {
 7076        self.modal_layer.update(cx, |modal_layer, cx| {
 7077            modal_layer.toggle_modal(window, cx, build)
 7078        })
 7079    }
 7080
 7081    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7082        self.modal_layer
 7083            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7084    }
 7085
 7086    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7087        self.toast_layer
 7088            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7089    }
 7090
 7091    pub fn toggle_centered_layout(
 7092        &mut self,
 7093        _: &ToggleCenteredLayout,
 7094        _: &mut Window,
 7095        cx: &mut Context<Self>,
 7096    ) {
 7097        self.centered_layout = !self.centered_layout;
 7098        if let Some(database_id) = self.database_id() {
 7099            let db = WorkspaceDb::global(cx);
 7100            let centered_layout = self.centered_layout;
 7101            cx.background_spawn(async move {
 7102                db.set_centered_layout(database_id, centered_layout).await
 7103            })
 7104            .detach_and_log_err(cx);
 7105        }
 7106        cx.notify();
 7107    }
 7108
 7109    fn adjust_padding(padding: Option<f32>) -> f32 {
 7110        padding
 7111            .unwrap_or(CenteredPaddingSettings::default().0)
 7112            .clamp(
 7113                CenteredPaddingSettings::MIN_PADDING,
 7114                CenteredPaddingSettings::MAX_PADDING,
 7115            )
 7116    }
 7117
 7118    fn render_dock(
 7119        &self,
 7120        position: DockPosition,
 7121        dock: &Entity<Dock>,
 7122        window: &mut Window,
 7123        cx: &mut App,
 7124    ) -> Option<Div> {
 7125        if self.zoomed_position == Some(position) {
 7126            return None;
 7127        }
 7128
 7129        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7130            let pane = panel.pane(cx)?;
 7131            let follower_states = &self.follower_states;
 7132            leader_border_for_pane(follower_states, &pane, window, cx)
 7133        });
 7134
 7135        Some(
 7136            div()
 7137                .flex()
 7138                .flex_none()
 7139                .overflow_hidden()
 7140                .child(dock.clone())
 7141                .children(leader_border),
 7142        )
 7143    }
 7144
 7145    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7146        window
 7147            .root::<MultiWorkspace>()
 7148            .flatten()
 7149            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7150    }
 7151
 7152    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7153        self.zoomed.as_ref()
 7154    }
 7155
 7156    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7157        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7158            return;
 7159        };
 7160        let windows = cx.windows();
 7161        let next_window =
 7162            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7163                || {
 7164                    windows
 7165                        .iter()
 7166                        .cycle()
 7167                        .skip_while(|window| window.window_id() != current_window_id)
 7168                        .nth(1)
 7169                },
 7170            );
 7171
 7172        if let Some(window) = next_window {
 7173            window
 7174                .update(cx, |_, window, _| window.activate_window())
 7175                .ok();
 7176        }
 7177    }
 7178
 7179    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7180        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7181            return;
 7182        };
 7183        let windows = cx.windows();
 7184        let prev_window =
 7185            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7186                || {
 7187                    windows
 7188                        .iter()
 7189                        .rev()
 7190                        .cycle()
 7191                        .skip_while(|window| window.window_id() != current_window_id)
 7192                        .nth(1)
 7193                },
 7194            );
 7195
 7196        if let Some(window) = prev_window {
 7197            window
 7198                .update(cx, |_, window, _| window.activate_window())
 7199                .ok();
 7200        }
 7201    }
 7202
 7203    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7204        if cx.stop_active_drag(window) {
 7205        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7206            dismiss_app_notification(&notification_id, cx);
 7207        } else {
 7208            cx.propagate();
 7209        }
 7210    }
 7211
 7212    fn adjust_dock_size_by_px(
 7213        &mut self,
 7214        panel_size: Pixels,
 7215        dock_pos: DockPosition,
 7216        px: Pixels,
 7217        window: &mut Window,
 7218        cx: &mut Context<Self>,
 7219    ) {
 7220        match dock_pos {
 7221            DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
 7222            DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
 7223            DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
 7224        }
 7225    }
 7226
 7227    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7228        let workspace_width = self.bounds.size.width;
 7229        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7230
 7231        self.right_dock.read_with(cx, |right_dock, cx| {
 7232            let right_dock_size = right_dock
 7233                .active_panel_size(window, cx)
 7234                .unwrap_or(Pixels::ZERO);
 7235            if right_dock_size + size > workspace_width {
 7236                size = workspace_width - right_dock_size
 7237            }
 7238        });
 7239
 7240        self.left_dock.update(cx, |left_dock, cx| {
 7241            if WorkspaceSettings::get_global(cx)
 7242                .resize_all_panels_in_dock
 7243                .contains(&DockPosition::Left)
 7244            {
 7245                left_dock.resize_all_panels(Some(size), window, cx);
 7246            } else {
 7247                left_dock.resize_active_panel(Some(size), window, cx);
 7248            }
 7249        });
 7250    }
 7251
 7252    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7253        let workspace_width = self.bounds.size.width;
 7254        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7255        self.left_dock.read_with(cx, |left_dock, cx| {
 7256            let left_dock_size = left_dock
 7257                .active_panel_size(window, cx)
 7258                .unwrap_or(Pixels::ZERO);
 7259            if left_dock_size + size > workspace_width {
 7260                size = workspace_width - left_dock_size
 7261            }
 7262        });
 7263        self.right_dock.update(cx, |right_dock, cx| {
 7264            if WorkspaceSettings::get_global(cx)
 7265                .resize_all_panels_in_dock
 7266                .contains(&DockPosition::Right)
 7267            {
 7268                right_dock.resize_all_panels(Some(size), window, cx);
 7269            } else {
 7270                right_dock.resize_active_panel(Some(size), window, cx);
 7271            }
 7272        });
 7273    }
 7274
 7275    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7276        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7277        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7278            if WorkspaceSettings::get_global(cx)
 7279                .resize_all_panels_in_dock
 7280                .contains(&DockPosition::Bottom)
 7281            {
 7282                bottom_dock.resize_all_panels(Some(size), window, cx);
 7283            } else {
 7284                bottom_dock.resize_active_panel(Some(size), window, cx);
 7285            }
 7286        });
 7287    }
 7288
 7289    fn toggle_edit_predictions_all_files(
 7290        &mut self,
 7291        _: &ToggleEditPrediction,
 7292        _window: &mut Window,
 7293        cx: &mut Context<Self>,
 7294    ) {
 7295        let fs = self.project().read(cx).fs().clone();
 7296        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7297        update_settings_file(fs, cx, move |file, _| {
 7298            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7299        });
 7300    }
 7301
 7302    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7303        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7304        let next_mode = match current_mode {
 7305            Some(theme::ThemeAppearanceMode::Light) => theme::ThemeAppearanceMode::Dark,
 7306            Some(theme::ThemeAppearanceMode::Dark) => theme::ThemeAppearanceMode::Light,
 7307            Some(theme::ThemeAppearanceMode::System) | None => match cx.theme().appearance() {
 7308                theme::Appearance::Light => theme::ThemeAppearanceMode::Dark,
 7309                theme::Appearance::Dark => theme::ThemeAppearanceMode::Light,
 7310            },
 7311        };
 7312
 7313        let fs = self.project().read(cx).fs().clone();
 7314        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7315            theme::set_mode(settings, next_mode);
 7316        });
 7317    }
 7318
 7319    pub fn show_worktree_trust_security_modal(
 7320        &mut self,
 7321        toggle: bool,
 7322        window: &mut Window,
 7323        cx: &mut Context<Self>,
 7324    ) {
 7325        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7326            if toggle {
 7327                security_modal.update(cx, |security_modal, cx| {
 7328                    security_modal.dismiss(cx);
 7329                })
 7330            } else {
 7331                security_modal.update(cx, |security_modal, cx| {
 7332                    security_modal.refresh_restricted_paths(cx);
 7333                });
 7334            }
 7335        } else {
 7336            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7337                .map(|trusted_worktrees| {
 7338                    trusted_worktrees
 7339                        .read(cx)
 7340                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7341                })
 7342                .unwrap_or(false);
 7343            if has_restricted_worktrees {
 7344                let project = self.project().read(cx);
 7345                let remote_host = project
 7346                    .remote_connection_options(cx)
 7347                    .map(RemoteHostLocation::from);
 7348                let worktree_store = project.worktree_store().downgrade();
 7349                self.toggle_modal(window, cx, |_, cx| {
 7350                    SecurityModal::new(worktree_store, remote_host, cx)
 7351                });
 7352            }
 7353        }
 7354    }
 7355}
 7356
 7357pub trait AnyActiveCall {
 7358    fn entity(&self) -> AnyEntity;
 7359    fn is_in_room(&self, _: &App) -> bool;
 7360    fn room_id(&self, _: &App) -> Option<u64>;
 7361    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7362    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7363    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7364    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7365    fn is_sharing_project(&self, _: &App) -> bool;
 7366    fn has_remote_participants(&self, _: &App) -> bool;
 7367    fn local_participant_is_guest(&self, _: &App) -> bool;
 7368    fn client(&self, _: &App) -> Arc<Client>;
 7369    fn share_on_join(&self, _: &App) -> bool;
 7370    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7371    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7372    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7373    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7374    fn join_project(
 7375        &self,
 7376        _: u64,
 7377        _: Arc<LanguageRegistry>,
 7378        _: Arc<dyn Fs>,
 7379        _: &mut App,
 7380    ) -> Task<Result<Entity<Project>>>;
 7381    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7382    fn subscribe(
 7383        &self,
 7384        _: &mut Window,
 7385        _: &mut Context<Workspace>,
 7386        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7387    ) -> Subscription;
 7388    fn create_shared_screen(
 7389        &self,
 7390        _: PeerId,
 7391        _: &Entity<Pane>,
 7392        _: &mut Window,
 7393        _: &mut App,
 7394    ) -> Option<Entity<SharedScreen>>;
 7395}
 7396
 7397#[derive(Clone)]
 7398pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7399impl Global for GlobalAnyActiveCall {}
 7400
 7401impl GlobalAnyActiveCall {
 7402    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7403        cx.try_global()
 7404    }
 7405
 7406    pub(crate) fn global(cx: &App) -> &Self {
 7407        cx.global()
 7408    }
 7409}
 7410
 7411pub fn merge_conflict_notification_id() -> NotificationId {
 7412    struct MergeConflictNotification;
 7413    NotificationId::unique::<MergeConflictNotification>()
 7414}
 7415
 7416/// Workspace-local view of a remote participant's location.
 7417#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7418pub enum ParticipantLocation {
 7419    SharedProject { project_id: u64 },
 7420    UnsharedProject,
 7421    External,
 7422}
 7423
 7424impl ParticipantLocation {
 7425    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7426        match location
 7427            .and_then(|l| l.variant)
 7428            .context("participant location was not provided")?
 7429        {
 7430            proto::participant_location::Variant::SharedProject(project) => {
 7431                Ok(Self::SharedProject {
 7432                    project_id: project.id,
 7433                })
 7434            }
 7435            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7436            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7437        }
 7438    }
 7439}
 7440/// Workspace-local view of a remote collaborator's state.
 7441/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7442#[derive(Clone)]
 7443pub struct RemoteCollaborator {
 7444    pub user: Arc<User>,
 7445    pub peer_id: PeerId,
 7446    pub location: ParticipantLocation,
 7447    pub participant_index: ParticipantIndex,
 7448}
 7449
 7450pub enum ActiveCallEvent {
 7451    ParticipantLocationChanged { participant_id: PeerId },
 7452    RemoteVideoTracksChanged { participant_id: PeerId },
 7453}
 7454
 7455fn leader_border_for_pane(
 7456    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7457    pane: &Entity<Pane>,
 7458    _: &Window,
 7459    cx: &App,
 7460) -> Option<Div> {
 7461    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7462        if state.pane() == pane {
 7463            Some((*leader_id, state))
 7464        } else {
 7465            None
 7466        }
 7467    })?;
 7468
 7469    let mut leader_color = match leader_id {
 7470        CollaboratorId::PeerId(leader_peer_id) => {
 7471            let leader = GlobalAnyActiveCall::try_global(cx)?
 7472                .0
 7473                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7474
 7475            cx.theme()
 7476                .players()
 7477                .color_for_participant(leader.participant_index.0)
 7478                .cursor
 7479        }
 7480        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7481    };
 7482    leader_color.fade_out(0.3);
 7483    Some(
 7484        div()
 7485            .absolute()
 7486            .size_full()
 7487            .left_0()
 7488            .top_0()
 7489            .border_2()
 7490            .border_color(leader_color),
 7491    )
 7492}
 7493
 7494fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7495    ZED_WINDOW_POSITION
 7496        .zip(*ZED_WINDOW_SIZE)
 7497        .map(|(position, size)| Bounds {
 7498            origin: position,
 7499            size,
 7500        })
 7501}
 7502
 7503fn open_items(
 7504    serialized_workspace: Option<SerializedWorkspace>,
 7505    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7506    window: &mut Window,
 7507    cx: &mut Context<Workspace>,
 7508) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7509    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7510        Workspace::load_workspace(
 7511            serialized_workspace,
 7512            project_paths_to_open
 7513                .iter()
 7514                .map(|(_, project_path)| project_path)
 7515                .cloned()
 7516                .collect(),
 7517            window,
 7518            cx,
 7519        )
 7520    });
 7521
 7522    cx.spawn_in(window, async move |workspace, cx| {
 7523        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7524
 7525        if let Some(restored_items) = restored_items {
 7526            let restored_items = restored_items.await?;
 7527
 7528            let restored_project_paths = restored_items
 7529                .iter()
 7530                .filter_map(|item| {
 7531                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7532                        .ok()
 7533                        .flatten()
 7534                })
 7535                .collect::<HashSet<_>>();
 7536
 7537            for restored_item in restored_items {
 7538                opened_items.push(restored_item.map(Ok));
 7539            }
 7540
 7541            project_paths_to_open
 7542                .iter_mut()
 7543                .for_each(|(_, project_path)| {
 7544                    if let Some(project_path_to_open) = project_path
 7545                        && restored_project_paths.contains(project_path_to_open)
 7546                    {
 7547                        *project_path = None;
 7548                    }
 7549                });
 7550        } else {
 7551            for _ in 0..project_paths_to_open.len() {
 7552                opened_items.push(None);
 7553            }
 7554        }
 7555        assert!(opened_items.len() == project_paths_to_open.len());
 7556
 7557        let tasks =
 7558            project_paths_to_open
 7559                .into_iter()
 7560                .enumerate()
 7561                .map(|(ix, (abs_path, project_path))| {
 7562                    let workspace = workspace.clone();
 7563                    cx.spawn(async move |cx| {
 7564                        let file_project_path = project_path?;
 7565                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7566                            workspace.project().update(cx, |project, cx| {
 7567                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7568                            })
 7569                        });
 7570
 7571                        // We only want to open file paths here. If one of the items
 7572                        // here is a directory, it was already opened further above
 7573                        // with a `find_or_create_worktree`.
 7574                        if let Ok(task) = abs_path_task
 7575                            && task.await.is_none_or(|p| p.is_file())
 7576                        {
 7577                            return Some((
 7578                                ix,
 7579                                workspace
 7580                                    .update_in(cx, |workspace, window, cx| {
 7581                                        workspace.open_path(
 7582                                            file_project_path,
 7583                                            None,
 7584                                            true,
 7585                                            window,
 7586                                            cx,
 7587                                        )
 7588                                    })
 7589                                    .log_err()?
 7590                                    .await,
 7591                            ));
 7592                        }
 7593                        None
 7594                    })
 7595                });
 7596
 7597        let tasks = tasks.collect::<Vec<_>>();
 7598
 7599        let tasks = futures::future::join_all(tasks);
 7600        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7601            opened_items[ix] = Some(path_open_result);
 7602        }
 7603
 7604        Ok(opened_items)
 7605    })
 7606}
 7607
 7608#[derive(Clone)]
 7609enum ActivateInDirectionTarget {
 7610    Pane(Entity<Pane>),
 7611    Dock(Entity<Dock>),
 7612    Sidebar(FocusHandle),
 7613}
 7614
 7615fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7616    window
 7617        .update(cx, |multi_workspace, _, cx| {
 7618            let workspace = multi_workspace.workspace().clone();
 7619            workspace.update(cx, |workspace, cx| {
 7620                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7621                    struct DatabaseFailedNotification;
 7622
 7623                    workspace.show_notification(
 7624                        NotificationId::unique::<DatabaseFailedNotification>(),
 7625                        cx,
 7626                        |cx| {
 7627                            cx.new(|cx| {
 7628                                MessageNotification::new("Failed to load the database file.", cx)
 7629                                    .primary_message("File an Issue")
 7630                                    .primary_icon(IconName::Plus)
 7631                                    .primary_on_click(|window, cx| {
 7632                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7633                                    })
 7634                            })
 7635                        },
 7636                    );
 7637                }
 7638            });
 7639        })
 7640        .log_err();
 7641}
 7642
 7643fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7644    if val == 0 {
 7645        ThemeSettings::get_global(cx).ui_font_size(cx)
 7646    } else {
 7647        px(val as f32)
 7648    }
 7649}
 7650
 7651fn adjust_active_dock_size_by_px(
 7652    px: Pixels,
 7653    workspace: &mut Workspace,
 7654    window: &mut Window,
 7655    cx: &mut Context<Workspace>,
 7656) {
 7657    let Some(active_dock) = workspace
 7658        .all_docks()
 7659        .into_iter()
 7660        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7661    else {
 7662        return;
 7663    };
 7664    let dock = active_dock.read(cx);
 7665    let Some(panel_size) = dock.active_panel_size(window, cx) else {
 7666        return;
 7667    };
 7668    let dock_pos = dock.position();
 7669    workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
 7670}
 7671
 7672fn adjust_open_docks_size_by_px(
 7673    px: Pixels,
 7674    workspace: &mut Workspace,
 7675    window: &mut Window,
 7676    cx: &mut Context<Workspace>,
 7677) {
 7678    let docks = workspace
 7679        .all_docks()
 7680        .into_iter()
 7681        .filter_map(|dock| {
 7682            if dock.read(cx).is_open() {
 7683                let dock = dock.read(cx);
 7684                let panel_size = dock.active_panel_size(window, cx)?;
 7685                let dock_pos = dock.position();
 7686                Some((panel_size, dock_pos, px))
 7687            } else {
 7688                None
 7689            }
 7690        })
 7691        .collect::<Vec<_>>();
 7692
 7693    docks
 7694        .into_iter()
 7695        .for_each(|(panel_size, dock_pos, offset)| {
 7696            workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
 7697        });
 7698}
 7699
 7700impl Focusable for Workspace {
 7701    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7702        self.active_pane.focus_handle(cx)
 7703    }
 7704}
 7705
 7706#[derive(Clone)]
 7707struct DraggedDock(DockPosition);
 7708
 7709impl Render for DraggedDock {
 7710    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7711        gpui::Empty
 7712    }
 7713}
 7714
 7715impl Render for Workspace {
 7716    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 7717        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 7718        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 7719            log::info!("Rendered first frame");
 7720        }
 7721
 7722        let centered_layout = self.centered_layout
 7723            && self.center.panes().len() == 1
 7724            && self.active_item(cx).is_some();
 7725        let render_padding = |size| {
 7726            (size > 0.0).then(|| {
 7727                div()
 7728                    .h_full()
 7729                    .w(relative(size))
 7730                    .bg(cx.theme().colors().editor_background)
 7731                    .border_color(cx.theme().colors().pane_group_border)
 7732            })
 7733        };
 7734        let paddings = if centered_layout {
 7735            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 7736            (
 7737                render_padding(Self::adjust_padding(
 7738                    settings.left_padding.map(|padding| padding.0),
 7739                )),
 7740                render_padding(Self::adjust_padding(
 7741                    settings.right_padding.map(|padding| padding.0),
 7742                )),
 7743            )
 7744        } else {
 7745            (None, None)
 7746        };
 7747        let ui_font = theme::setup_ui_font(window, cx);
 7748
 7749        let theme = cx.theme().clone();
 7750        let colors = theme.colors();
 7751        let notification_entities = self
 7752            .notifications
 7753            .iter()
 7754            .map(|(_, notification)| notification.entity_id())
 7755            .collect::<Vec<_>>();
 7756        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 7757
 7758        div()
 7759            .relative()
 7760            .size_full()
 7761            .flex()
 7762            .flex_col()
 7763            .font(ui_font)
 7764            .gap_0()
 7765                .justify_start()
 7766                .items_start()
 7767                .text_color(colors.text)
 7768                .overflow_hidden()
 7769                .children(self.titlebar_item.clone())
 7770                .on_modifiers_changed(move |_, _, cx| {
 7771                    for &id in &notification_entities {
 7772                        cx.notify(id);
 7773                    }
 7774                })
 7775                .child(
 7776                    div()
 7777                        .size_full()
 7778                        .relative()
 7779                        .flex_1()
 7780                        .flex()
 7781                        .flex_col()
 7782                        .child(
 7783                            div()
 7784                                .id("workspace")
 7785                                .bg(colors.background)
 7786                                .relative()
 7787                                .flex_1()
 7788                                .w_full()
 7789                                .flex()
 7790                                .flex_col()
 7791                                .overflow_hidden()
 7792                                .border_t_1()
 7793                                .border_b_1()
 7794                                .border_color(colors.border)
 7795                                .child({
 7796                                    let this = cx.entity();
 7797                                    canvas(
 7798                                        move |bounds, window, cx| {
 7799                                            this.update(cx, |this, cx| {
 7800                                                let bounds_changed = this.bounds != bounds;
 7801                                                this.bounds = bounds;
 7802
 7803                                                if bounds_changed {
 7804                                                    this.left_dock.update(cx, |dock, cx| {
 7805                                                        dock.clamp_panel_size(
 7806                                                            bounds.size.width,
 7807                                                            window,
 7808                                                            cx,
 7809                                                        )
 7810                                                    });
 7811
 7812                                                    this.right_dock.update(cx, |dock, cx| {
 7813                                                        dock.clamp_panel_size(
 7814                                                            bounds.size.width,
 7815                                                            window,
 7816                                                            cx,
 7817                                                        )
 7818                                                    });
 7819
 7820                                                    this.bottom_dock.update(cx, |dock, cx| {
 7821                                                        dock.clamp_panel_size(
 7822                                                            bounds.size.height,
 7823                                                            window,
 7824                                                            cx,
 7825                                                        )
 7826                                                    });
 7827                                                }
 7828                                            })
 7829                                        },
 7830                                        |_, _, _, _| {},
 7831                                    )
 7832                                    .absolute()
 7833                                    .size_full()
 7834                                })
 7835                                .when(self.zoomed.is_none(), |this| {
 7836                                    this.on_drag_move(cx.listener(
 7837                                        move |workspace,
 7838                                              e: &DragMoveEvent<DraggedDock>,
 7839                                              window,
 7840                                              cx| {
 7841                                            if workspace.previous_dock_drag_coordinates
 7842                                                != Some(e.event.position)
 7843                                            {
 7844                                                workspace.previous_dock_drag_coordinates =
 7845                                                    Some(e.event.position);
 7846
 7847                                                match e.drag(cx).0 {
 7848                                                    DockPosition::Left => {
 7849                                                        workspace.resize_left_dock(
 7850                                                            e.event.position.x
 7851                                                                - workspace.bounds.left(),
 7852                                                            window,
 7853                                                            cx,
 7854                                                        );
 7855                                                    }
 7856                                                    DockPosition::Right => {
 7857                                                        workspace.resize_right_dock(
 7858                                                            workspace.bounds.right()
 7859                                                                - e.event.position.x,
 7860                                                            window,
 7861                                                            cx,
 7862                                                        );
 7863                                                    }
 7864                                                    DockPosition::Bottom => {
 7865                                                        workspace.resize_bottom_dock(
 7866                                                            workspace.bounds.bottom()
 7867                                                                - e.event.position.y,
 7868                                                            window,
 7869                                                            cx,
 7870                                                        );
 7871                                                    }
 7872                                                };
 7873                                                workspace.serialize_workspace(window, cx);
 7874                                            }
 7875                                        },
 7876                                    ))
 7877
 7878                                })
 7879                                .child({
 7880                                    match bottom_dock_layout {
 7881                                        BottomDockLayout::Full => div()
 7882                                            .flex()
 7883                                            .flex_col()
 7884                                            .h_full()
 7885                                            .child(
 7886                                                div()
 7887                                                    .flex()
 7888                                                    .flex_row()
 7889                                                    .flex_1()
 7890                                                    .overflow_hidden()
 7891                                                    .children(self.render_dock(
 7892                                                        DockPosition::Left,
 7893                                                        &self.left_dock,
 7894                                                        window,
 7895                                                        cx,
 7896                                                    ))
 7897
 7898                                                    .child(
 7899                                                        div()
 7900                                                            .flex()
 7901                                                            .flex_col()
 7902                                                            .flex_1()
 7903                                                            .overflow_hidden()
 7904                                                            .child(
 7905                                                                h_flex()
 7906                                                                    .flex_1()
 7907                                                                    .when_some(
 7908                                                                        paddings.0,
 7909                                                                        |this, p| {
 7910                                                                            this.child(
 7911                                                                                p.border_r_1(),
 7912                                                                            )
 7913                                                                        },
 7914                                                                    )
 7915                                                                    .child(self.center.render(
 7916                                                                        self.zoomed.as_ref(),
 7917                                                                        &PaneRenderContext {
 7918                                                                            follower_states:
 7919                                                                                &self.follower_states,
 7920                                                                            active_call: self.active_call(),
 7921                                                                            active_pane: &self.active_pane,
 7922                                                                            app_state: &self.app_state,
 7923                                                                            project: &self.project,
 7924                                                                            workspace: &self.weak_self,
 7925                                                                        },
 7926                                                                        window,
 7927                                                                        cx,
 7928                                                                    ))
 7929                                                                    .when_some(
 7930                                                                        paddings.1,
 7931                                                                        |this, p| {
 7932                                                                            this.child(
 7933                                                                                p.border_l_1(),
 7934                                                                            )
 7935                                                                        },
 7936                                                                    ),
 7937                                                            ),
 7938                                                    )
 7939
 7940                                                    .children(self.render_dock(
 7941                                                        DockPosition::Right,
 7942                                                        &self.right_dock,
 7943                                                        window,
 7944                                                        cx,
 7945                                                    )),
 7946                                            )
 7947                                            .child(div().w_full().children(self.render_dock(
 7948                                                DockPosition::Bottom,
 7949                                                &self.bottom_dock,
 7950                                                window,
 7951                                                cx
 7952                                            ))),
 7953
 7954                                        BottomDockLayout::LeftAligned => div()
 7955                                            .flex()
 7956                                            .flex_row()
 7957                                            .h_full()
 7958                                            .child(
 7959                                                div()
 7960                                                    .flex()
 7961                                                    .flex_col()
 7962                                                    .flex_1()
 7963                                                    .h_full()
 7964                                                    .child(
 7965                                                        div()
 7966                                                            .flex()
 7967                                                            .flex_row()
 7968                                                            .flex_1()
 7969                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 7970
 7971                                                            .child(
 7972                                                                div()
 7973                                                                    .flex()
 7974                                                                    .flex_col()
 7975                                                                    .flex_1()
 7976                                                                    .overflow_hidden()
 7977                                                                    .child(
 7978                                                                        h_flex()
 7979                                                                            .flex_1()
 7980                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7981                                                                            .child(self.center.render(
 7982                                                                                self.zoomed.as_ref(),
 7983                                                                                &PaneRenderContext {
 7984                                                                                    follower_states:
 7985                                                                                        &self.follower_states,
 7986                                                                                    active_call: self.active_call(),
 7987                                                                                    active_pane: &self.active_pane,
 7988                                                                                    app_state: &self.app_state,
 7989                                                                                    project: &self.project,
 7990                                                                                    workspace: &self.weak_self,
 7991                                                                                },
 7992                                                                                window,
 7993                                                                                cx,
 7994                                                                            ))
 7995                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7996                                                                    )
 7997                                                            )
 7998
 7999                                                    )
 8000                                                    .child(
 8001                                                        div()
 8002                                                            .w_full()
 8003                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8004                                                    ),
 8005                                            )
 8006                                            .children(self.render_dock(
 8007                                                DockPosition::Right,
 8008                                                &self.right_dock,
 8009                                                window,
 8010                                                cx,
 8011                                            )),
 8012                                        BottomDockLayout::RightAligned => div()
 8013                                            .flex()
 8014                                            .flex_row()
 8015                                            .h_full()
 8016                                            .children(self.render_dock(
 8017                                                DockPosition::Left,
 8018                                                &self.left_dock,
 8019                                                window,
 8020                                                cx,
 8021                                            ))
 8022
 8023                                            .child(
 8024                                                div()
 8025                                                    .flex()
 8026                                                    .flex_col()
 8027                                                    .flex_1()
 8028                                                    .h_full()
 8029                                                    .child(
 8030                                                        div()
 8031                                                            .flex()
 8032                                                            .flex_row()
 8033                                                            .flex_1()
 8034                                                            .child(
 8035                                                                div()
 8036                                                                    .flex()
 8037                                                                    .flex_col()
 8038                                                                    .flex_1()
 8039                                                                    .overflow_hidden()
 8040                                                                    .child(
 8041                                                                        h_flex()
 8042                                                                            .flex_1()
 8043                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8044                                                                            .child(self.center.render(
 8045                                                                                self.zoomed.as_ref(),
 8046                                                                                &PaneRenderContext {
 8047                                                                                    follower_states:
 8048                                                                                        &self.follower_states,
 8049                                                                                    active_call: self.active_call(),
 8050                                                                                    active_pane: &self.active_pane,
 8051                                                                                    app_state: &self.app_state,
 8052                                                                                    project: &self.project,
 8053                                                                                    workspace: &self.weak_self,
 8054                                                                                },
 8055                                                                                window,
 8056                                                                                cx,
 8057                                                                            ))
 8058                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8059                                                                    )
 8060                                                            )
 8061
 8062                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 8063                                                    )
 8064                                                    .child(
 8065                                                        div()
 8066                                                            .w_full()
 8067                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8068                                                    ),
 8069                                            ),
 8070                                        BottomDockLayout::Contained => div()
 8071                                            .flex()
 8072                                            .flex_row()
 8073                                            .h_full()
 8074                                            .children(self.render_dock(
 8075                                                DockPosition::Left,
 8076                                                &self.left_dock,
 8077                                                window,
 8078                                                cx,
 8079                                            ))
 8080
 8081                                            .child(
 8082                                                div()
 8083                                                    .flex()
 8084                                                    .flex_col()
 8085                                                    .flex_1()
 8086                                                    .overflow_hidden()
 8087                                                    .child(
 8088                                                        h_flex()
 8089                                                            .flex_1()
 8090                                                            .when_some(paddings.0, |this, p| {
 8091                                                                this.child(p.border_r_1())
 8092                                                            })
 8093                                                            .child(self.center.render(
 8094                                                                self.zoomed.as_ref(),
 8095                                                                &PaneRenderContext {
 8096                                                                    follower_states:
 8097                                                                        &self.follower_states,
 8098                                                                    active_call: self.active_call(),
 8099                                                                    active_pane: &self.active_pane,
 8100                                                                    app_state: &self.app_state,
 8101                                                                    project: &self.project,
 8102                                                                    workspace: &self.weak_self,
 8103                                                                },
 8104                                                                window,
 8105                                                                cx,
 8106                                                            ))
 8107                                                            .when_some(paddings.1, |this, p| {
 8108                                                                this.child(p.border_l_1())
 8109                                                            }),
 8110                                                    )
 8111                                                    .children(self.render_dock(
 8112                                                        DockPosition::Bottom,
 8113                                                        &self.bottom_dock,
 8114                                                        window,
 8115                                                        cx,
 8116                                                    )),
 8117                                            )
 8118
 8119                                            .children(self.render_dock(
 8120                                                DockPosition::Right,
 8121                                                &self.right_dock,
 8122                                                window,
 8123                                                cx,
 8124                                            )),
 8125                                    }
 8126                                })
 8127                                .children(self.zoomed.as_ref().and_then(|view| {
 8128                                    let zoomed_view = view.upgrade()?;
 8129                                    let div = div()
 8130                                        .occlude()
 8131                                        .absolute()
 8132                                        .overflow_hidden()
 8133                                        .border_color(colors.border)
 8134                                        .bg(colors.background)
 8135                                        .child(zoomed_view)
 8136                                        .inset_0()
 8137                                        .shadow_lg();
 8138
 8139                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8140                                       return Some(div);
 8141                                    }
 8142
 8143                                    Some(match self.zoomed_position {
 8144                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8145                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8146                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8147                                        None => {
 8148                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8149                                        }
 8150                                    })
 8151                                }))
 8152                                .children(self.render_notifications(window, cx)),
 8153                        )
 8154                        .when(self.status_bar_visible(cx), |parent| {
 8155                            parent.child(self.status_bar.clone())
 8156                        })
 8157                        .child(self.toast_layer.clone()),
 8158                )
 8159    }
 8160}
 8161
 8162impl WorkspaceStore {
 8163    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8164        Self {
 8165            workspaces: Default::default(),
 8166            _subscriptions: vec![
 8167                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8168                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8169            ],
 8170            client,
 8171        }
 8172    }
 8173
 8174    pub fn update_followers(
 8175        &self,
 8176        project_id: Option<u64>,
 8177        update: proto::update_followers::Variant,
 8178        cx: &App,
 8179    ) -> Option<()> {
 8180        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8181        let room_id = active_call.0.room_id(cx)?;
 8182        self.client
 8183            .send(proto::UpdateFollowers {
 8184                room_id,
 8185                project_id,
 8186                variant: Some(update),
 8187            })
 8188            .log_err()
 8189    }
 8190
 8191    pub async fn handle_follow(
 8192        this: Entity<Self>,
 8193        envelope: TypedEnvelope<proto::Follow>,
 8194        mut cx: AsyncApp,
 8195    ) -> Result<proto::FollowResponse> {
 8196        this.update(&mut cx, |this, cx| {
 8197            let follower = Follower {
 8198                project_id: envelope.payload.project_id,
 8199                peer_id: envelope.original_sender_id()?,
 8200            };
 8201
 8202            let mut response = proto::FollowResponse::default();
 8203
 8204            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8205                let Some(workspace) = weak_workspace.upgrade() else {
 8206                    return false;
 8207                };
 8208                window_handle
 8209                    .update(cx, |_, window, cx| {
 8210                        workspace.update(cx, |workspace, cx| {
 8211                            let handler_response =
 8212                                workspace.handle_follow(follower.project_id, window, cx);
 8213                            if let Some(active_view) = handler_response.active_view
 8214                                && workspace.project.read(cx).remote_id() == follower.project_id
 8215                            {
 8216                                response.active_view = Some(active_view)
 8217                            }
 8218                        });
 8219                    })
 8220                    .is_ok()
 8221            });
 8222
 8223            Ok(response)
 8224        })
 8225    }
 8226
 8227    async fn handle_update_followers(
 8228        this: Entity<Self>,
 8229        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8230        mut cx: AsyncApp,
 8231    ) -> Result<()> {
 8232        let leader_id = envelope.original_sender_id()?;
 8233        let update = envelope.payload;
 8234
 8235        this.update(&mut cx, |this, cx| {
 8236            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8237                let Some(workspace) = weak_workspace.upgrade() else {
 8238                    return false;
 8239                };
 8240                window_handle
 8241                    .update(cx, |_, window, cx| {
 8242                        workspace.update(cx, |workspace, cx| {
 8243                            let project_id = workspace.project.read(cx).remote_id();
 8244                            if update.project_id != project_id && update.project_id.is_some() {
 8245                                return;
 8246                            }
 8247                            workspace.handle_update_followers(
 8248                                leader_id,
 8249                                update.clone(),
 8250                                window,
 8251                                cx,
 8252                            );
 8253                        });
 8254                    })
 8255                    .is_ok()
 8256            });
 8257            Ok(())
 8258        })
 8259    }
 8260
 8261    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8262        self.workspaces.iter().map(|(_, weak)| weak)
 8263    }
 8264
 8265    pub fn workspaces_with_windows(
 8266        &self,
 8267    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8268        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8269    }
 8270}
 8271
 8272impl ViewId {
 8273    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8274        Ok(Self {
 8275            creator: message
 8276                .creator
 8277                .map(CollaboratorId::PeerId)
 8278                .context("creator is missing")?,
 8279            id: message.id,
 8280        })
 8281    }
 8282
 8283    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8284        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8285            Some(proto::ViewId {
 8286                creator: Some(peer_id),
 8287                id: self.id,
 8288            })
 8289        } else {
 8290            None
 8291        }
 8292    }
 8293}
 8294
 8295impl FollowerState {
 8296    fn pane(&self) -> &Entity<Pane> {
 8297        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8298    }
 8299}
 8300
 8301pub trait WorkspaceHandle {
 8302    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8303}
 8304
 8305impl WorkspaceHandle for Entity<Workspace> {
 8306    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8307        self.read(cx)
 8308            .worktrees(cx)
 8309            .flat_map(|worktree| {
 8310                let worktree_id = worktree.read(cx).id();
 8311                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8312                    worktree_id,
 8313                    path: f.path.clone(),
 8314                })
 8315            })
 8316            .collect::<Vec<_>>()
 8317    }
 8318}
 8319
 8320pub async fn last_opened_workspace_location(
 8321    db: &WorkspaceDb,
 8322    fs: &dyn fs::Fs,
 8323) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8324    db.last_workspace(fs)
 8325        .await
 8326        .log_err()
 8327        .flatten()
 8328        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8329}
 8330
 8331pub async fn last_session_workspace_locations(
 8332    db: &WorkspaceDb,
 8333    last_session_id: &str,
 8334    last_session_window_stack: Option<Vec<WindowId>>,
 8335    fs: &dyn fs::Fs,
 8336) -> Option<Vec<SessionWorkspace>> {
 8337    db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8338        .await
 8339        .log_err()
 8340}
 8341
 8342pub struct MultiWorkspaceRestoreResult {
 8343    pub window_handle: WindowHandle<MultiWorkspace>,
 8344    pub errors: Vec<anyhow::Error>,
 8345}
 8346
 8347pub async fn restore_multiworkspace(
 8348    multi_workspace: SerializedMultiWorkspace,
 8349    app_state: Arc<AppState>,
 8350    cx: &mut AsyncApp,
 8351) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8352    let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
 8353    let mut group_iter = workspaces.into_iter();
 8354    let first = group_iter
 8355        .next()
 8356        .context("window group must not be empty")?;
 8357
 8358    let window_handle = if first.paths.is_empty() {
 8359        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8360            .await?
 8361    } else {
 8362        let OpenResult { window, .. } = cx
 8363            .update(|cx| {
 8364                Workspace::new_local(
 8365                    first.paths.paths().to_vec(),
 8366                    app_state.clone(),
 8367                    None,
 8368                    None,
 8369                    None,
 8370                    true,
 8371                    cx,
 8372                )
 8373            })
 8374            .await?;
 8375        window
 8376    };
 8377
 8378    let mut errors = Vec::new();
 8379
 8380    for session_workspace in group_iter {
 8381        let error = if session_workspace.paths.is_empty() {
 8382            cx.update(|cx| {
 8383                open_workspace_by_id(
 8384                    session_workspace.workspace_id,
 8385                    app_state.clone(),
 8386                    Some(window_handle),
 8387                    cx,
 8388                )
 8389            })
 8390            .await
 8391            .err()
 8392        } else {
 8393            cx.update(|cx| {
 8394                Workspace::new_local(
 8395                    session_workspace.paths.paths().to_vec(),
 8396                    app_state.clone(),
 8397                    Some(window_handle),
 8398                    None,
 8399                    None,
 8400                    false,
 8401                    cx,
 8402                )
 8403            })
 8404            .await
 8405            .err()
 8406        };
 8407
 8408        if let Some(error) = error {
 8409            errors.push(error);
 8410        }
 8411    }
 8412
 8413    if let Some(target_id) = state.active_workspace_id {
 8414        window_handle
 8415            .update(cx, |multi_workspace, window, cx| {
 8416                let target_index = multi_workspace
 8417                    .workspaces()
 8418                    .iter()
 8419                    .position(|ws| ws.read(cx).database_id() == Some(target_id));
 8420                if let Some(index) = target_index {
 8421                    multi_workspace.activate_index(index, window, cx);
 8422                } else if !multi_workspace.workspaces().is_empty() {
 8423                    multi_workspace.activate_index(0, window, cx);
 8424                }
 8425            })
 8426            .ok();
 8427    } else {
 8428        window_handle
 8429            .update(cx, |multi_workspace, window, cx| {
 8430                if !multi_workspace.workspaces().is_empty() {
 8431                    multi_workspace.activate_index(0, window, cx);
 8432                }
 8433            })
 8434            .ok();
 8435    }
 8436
 8437    if state.sidebar_open {
 8438        window_handle
 8439            .update(cx, |multi_workspace, _, cx| {
 8440                multi_workspace.open_sidebar(cx);
 8441            })
 8442            .ok();
 8443    }
 8444
 8445    window_handle
 8446        .update(cx, |_, window, _cx| {
 8447            window.activate_window();
 8448        })
 8449        .ok();
 8450
 8451    Ok(MultiWorkspaceRestoreResult {
 8452        window_handle,
 8453        errors,
 8454    })
 8455}
 8456
 8457actions!(
 8458    collab,
 8459    [
 8460        /// Opens the channel notes for the current call.
 8461        ///
 8462        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8463        /// channel in the collab panel.
 8464        ///
 8465        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8466        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8467        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8468        OpenChannelNotes,
 8469        /// Mutes your microphone.
 8470        Mute,
 8471        /// Deafens yourself (mute both microphone and speakers).
 8472        Deafen,
 8473        /// Leaves the current call.
 8474        LeaveCall,
 8475        /// Shares the current project with collaborators.
 8476        ShareProject,
 8477        /// Shares your screen with collaborators.
 8478        ScreenShare,
 8479        /// Copies the current room name and session id for debugging purposes.
 8480        CopyRoomId,
 8481    ]
 8482);
 8483
 8484/// Opens the channel notes for a specific channel by its ID.
 8485#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8486#[action(namespace = collab)]
 8487#[serde(deny_unknown_fields)]
 8488pub struct OpenChannelNotesById {
 8489    pub channel_id: u64,
 8490}
 8491
 8492actions!(
 8493    zed,
 8494    [
 8495        /// Opens the Zed log file.
 8496        OpenLog,
 8497        /// Reveals the Zed log file in the system file manager.
 8498        RevealLogInFileManager
 8499    ]
 8500);
 8501
 8502async fn join_channel_internal(
 8503    channel_id: ChannelId,
 8504    app_state: &Arc<AppState>,
 8505    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8506    requesting_workspace: Option<WeakEntity<Workspace>>,
 8507    active_call: &dyn AnyActiveCall,
 8508    cx: &mut AsyncApp,
 8509) -> Result<bool> {
 8510    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8511        if !active_call.is_in_room(cx) {
 8512            return (false, false);
 8513        }
 8514
 8515        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8516        let should_prompt = active_call.is_sharing_project(cx)
 8517            && active_call.has_remote_participants(cx)
 8518            && !already_in_channel;
 8519        (should_prompt, already_in_channel)
 8520    });
 8521
 8522    if already_in_channel {
 8523        let task = cx.update(|cx| {
 8524            if let Some((project, host)) = active_call.most_active_project(cx) {
 8525                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8526            } else {
 8527                None
 8528            }
 8529        });
 8530        if let Some(task) = task {
 8531            task.await?;
 8532        }
 8533        return anyhow::Ok(true);
 8534    }
 8535
 8536    if should_prompt {
 8537        if let Some(multi_workspace) = requesting_window {
 8538            let answer = multi_workspace
 8539                .update(cx, |_, window, cx| {
 8540                    window.prompt(
 8541                        PromptLevel::Warning,
 8542                        "Do you want to switch channels?",
 8543                        Some("Leaving this call will unshare your current project."),
 8544                        &["Yes, Join Channel", "Cancel"],
 8545                        cx,
 8546                    )
 8547                })?
 8548                .await;
 8549
 8550            if answer == Ok(1) {
 8551                return Ok(false);
 8552            }
 8553        } else {
 8554            return Ok(false);
 8555        }
 8556    }
 8557
 8558    let client = cx.update(|cx| active_call.client(cx));
 8559
 8560    let mut client_status = client.status();
 8561
 8562    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8563    'outer: loop {
 8564        let Some(status) = client_status.recv().await else {
 8565            anyhow::bail!("error connecting");
 8566        };
 8567
 8568        match status {
 8569            Status::Connecting
 8570            | Status::Authenticating
 8571            | Status::Authenticated
 8572            | Status::Reconnecting
 8573            | Status::Reauthenticating
 8574            | Status::Reauthenticated => continue,
 8575            Status::Connected { .. } => break 'outer,
 8576            Status::SignedOut | Status::AuthenticationError => {
 8577                return Err(ErrorCode::SignedOut.into());
 8578            }
 8579            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8580            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8581                return Err(ErrorCode::Disconnected.into());
 8582            }
 8583        }
 8584    }
 8585
 8586    let joined = cx
 8587        .update(|cx| active_call.join_channel(channel_id, cx))
 8588        .await?;
 8589
 8590    if !joined {
 8591        return anyhow::Ok(true);
 8592    }
 8593
 8594    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8595
 8596    let task = cx.update(|cx| {
 8597        if let Some((project, host)) = active_call.most_active_project(cx) {
 8598            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8599        }
 8600
 8601        // If you are the first to join a channel, see if you should share your project.
 8602        if !active_call.has_remote_participants(cx)
 8603            && !active_call.local_participant_is_guest(cx)
 8604            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8605        {
 8606            let project = workspace.update(cx, |workspace, cx| {
 8607                let project = workspace.project.read(cx);
 8608
 8609                if !active_call.share_on_join(cx) {
 8610                    return None;
 8611                }
 8612
 8613                if (project.is_local() || project.is_via_remote_server())
 8614                    && project.visible_worktrees(cx).any(|tree| {
 8615                        tree.read(cx)
 8616                            .root_entry()
 8617                            .is_some_and(|entry| entry.is_dir())
 8618                    })
 8619                {
 8620                    Some(workspace.project.clone())
 8621                } else {
 8622                    None
 8623                }
 8624            });
 8625            if let Some(project) = project {
 8626                let share_task = active_call.share_project(project, cx);
 8627                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8628                    share_task.await?;
 8629                    Ok(())
 8630                }));
 8631            }
 8632        }
 8633
 8634        None
 8635    });
 8636    if let Some(task) = task {
 8637        task.await?;
 8638        return anyhow::Ok(true);
 8639    }
 8640    anyhow::Ok(false)
 8641}
 8642
 8643pub fn join_channel(
 8644    channel_id: ChannelId,
 8645    app_state: Arc<AppState>,
 8646    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8647    requesting_workspace: Option<WeakEntity<Workspace>>,
 8648    cx: &mut App,
 8649) -> Task<Result<()>> {
 8650    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8651    cx.spawn(async move |cx| {
 8652        let result = join_channel_internal(
 8653            channel_id,
 8654            &app_state,
 8655            requesting_window,
 8656            requesting_workspace,
 8657            &*active_call.0,
 8658            cx,
 8659        )
 8660        .await;
 8661
 8662        // join channel succeeded, and opened a window
 8663        if matches!(result, Ok(true)) {
 8664            return anyhow::Ok(());
 8665        }
 8666
 8667        // find an existing workspace to focus and show call controls
 8668        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8669        if active_window.is_none() {
 8670            // no open workspaces, make one to show the error in (blergh)
 8671            let OpenResult {
 8672                window: window_handle,
 8673                ..
 8674            } = cx
 8675                .update(|cx| {
 8676                    Workspace::new_local(
 8677                        vec![],
 8678                        app_state.clone(),
 8679                        requesting_window,
 8680                        None,
 8681                        None,
 8682                        true,
 8683                        cx,
 8684                    )
 8685                })
 8686                .await?;
 8687
 8688            window_handle
 8689                .update(cx, |_, window, _cx| {
 8690                    window.activate_window();
 8691                })
 8692                .ok();
 8693
 8694            if result.is_ok() {
 8695                cx.update(|cx| {
 8696                    cx.dispatch_action(&OpenChannelNotes);
 8697                });
 8698            }
 8699
 8700            active_window = Some(window_handle);
 8701        }
 8702
 8703        if let Err(err) = result {
 8704            log::error!("failed to join channel: {}", err);
 8705            if let Some(active_window) = active_window {
 8706                active_window
 8707                    .update(cx, |_, window, cx| {
 8708                        let detail: SharedString = match err.error_code() {
 8709                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 8710                            ErrorCode::UpgradeRequired => concat!(
 8711                                "Your are running an unsupported version of Zed. ",
 8712                                "Please update to continue."
 8713                            )
 8714                            .into(),
 8715                            ErrorCode::NoSuchChannel => concat!(
 8716                                "No matching channel was found. ",
 8717                                "Please check the link and try again."
 8718                            )
 8719                            .into(),
 8720                            ErrorCode::Forbidden => concat!(
 8721                                "This channel is private, and you do not have access. ",
 8722                                "Please ask someone to add you and try again."
 8723                            )
 8724                            .into(),
 8725                            ErrorCode::Disconnected => {
 8726                                "Please check your internet connection and try again.".into()
 8727                            }
 8728                            _ => format!("{}\n\nPlease try again.", err).into(),
 8729                        };
 8730                        window.prompt(
 8731                            PromptLevel::Critical,
 8732                            "Failed to join channel",
 8733                            Some(&detail),
 8734                            &["Ok"],
 8735                            cx,
 8736                        )
 8737                    })?
 8738                    .await
 8739                    .ok();
 8740            }
 8741        }
 8742
 8743        // return ok, we showed the error to the user.
 8744        anyhow::Ok(())
 8745    })
 8746}
 8747
 8748pub async fn get_any_active_multi_workspace(
 8749    app_state: Arc<AppState>,
 8750    mut cx: AsyncApp,
 8751) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8752    // find an existing workspace to focus and show call controls
 8753    let active_window = activate_any_workspace_window(&mut cx);
 8754    if active_window.is_none() {
 8755        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
 8756            .await?;
 8757    }
 8758    activate_any_workspace_window(&mut cx).context("could not open zed")
 8759}
 8760
 8761fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 8762    cx.update(|cx| {
 8763        if let Some(workspace_window) = cx
 8764            .active_window()
 8765            .and_then(|window| window.downcast::<MultiWorkspace>())
 8766        {
 8767            return Some(workspace_window);
 8768        }
 8769
 8770        for window in cx.windows() {
 8771            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 8772                workspace_window
 8773                    .update(cx, |_, window, _| window.activate_window())
 8774                    .ok();
 8775                return Some(workspace_window);
 8776            }
 8777        }
 8778        None
 8779    })
 8780}
 8781
 8782pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 8783    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 8784}
 8785
 8786pub fn workspace_windows_for_location(
 8787    serialized_location: &SerializedWorkspaceLocation,
 8788    cx: &App,
 8789) -> Vec<WindowHandle<MultiWorkspace>> {
 8790    cx.windows()
 8791        .into_iter()
 8792        .filter_map(|window| window.downcast::<MultiWorkspace>())
 8793        .filter(|multi_workspace| {
 8794            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 8795                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 8796                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 8797                }
 8798                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 8799                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 8800                    a.distro_name == b.distro_name
 8801                }
 8802                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 8803                    a.container_id == b.container_id
 8804                }
 8805                #[cfg(any(test, feature = "test-support"))]
 8806                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 8807                    a.id == b.id
 8808                }
 8809                _ => false,
 8810            };
 8811
 8812            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 8813                multi_workspace.workspaces().iter().any(|workspace| {
 8814                    match workspace.read(cx).workspace_location(cx) {
 8815                        WorkspaceLocation::Location(location, _) => {
 8816                            match (&location, serialized_location) {
 8817                                (
 8818                                    SerializedWorkspaceLocation::Local,
 8819                                    SerializedWorkspaceLocation::Local,
 8820                                ) => true,
 8821                                (
 8822                                    SerializedWorkspaceLocation::Remote(a),
 8823                                    SerializedWorkspaceLocation::Remote(b),
 8824                                ) => same_host(a, b),
 8825                                _ => false,
 8826                            }
 8827                        }
 8828                        _ => false,
 8829                    }
 8830                })
 8831            })
 8832        })
 8833        .collect()
 8834}
 8835
 8836fn find_exact_existing_workspace(
 8837    abs_paths: &[PathBuf],
 8838    location: &SerializedWorkspaceLocation,
 8839    cx: &App,
 8840) -> Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> {
 8841    let requested_paths = PathList::new(abs_paths);
 8842    let active_window = cx
 8843        .active_window()
 8844        .and_then(|window| window.downcast::<MultiWorkspace>());
 8845    let mut windows = workspace_windows_for_location(location, cx);
 8846
 8847    if let Some(active_window) = active_window {
 8848        if let Some(index) = windows.iter().position(|window| *window == active_window) {
 8849            let active_window = windows.remove(index);
 8850            windows.insert(0, active_window);
 8851        }
 8852    }
 8853
 8854    windows.into_iter().find_map(|window| {
 8855        let multi_workspace = window.read(cx).ok()?;
 8856        multi_workspace.workspaces().iter().find_map(|workspace| {
 8857            match workspace.read(cx).workspace_location(cx) {
 8858                WorkspaceLocation::Location(workspace_location, workspace_paths)
 8859                    if &workspace_location == location
 8860                        && workspace_paths.paths() == requested_paths.paths() =>
 8861                {
 8862                    Some((window, workspace.clone()))
 8863                }
 8864                _ => None,
 8865            }
 8866        })
 8867    })
 8868}
 8869
 8870pub async fn find_existing_workspace(
 8871    abs_paths: &[PathBuf],
 8872    open_options: &OpenOptions,
 8873    location: &SerializedWorkspaceLocation,
 8874    cx: &mut AsyncApp,
 8875) -> (
 8876    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 8877    OpenVisible,
 8878) {
 8879    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 8880    let mut open_visible = OpenVisible::All;
 8881    let mut best_match = None;
 8882
 8883    if open_options.open_new_workspace != Some(true) {
 8884        cx.update(|cx| {
 8885            for window in workspace_windows_for_location(location, cx) {
 8886                if let Ok(multi_workspace) = window.read(cx) {
 8887                    for workspace in multi_workspace.workspaces() {
 8888                        let project = workspace.read(cx).project.read(cx);
 8889                        let m = project.visibility_for_paths(
 8890                            abs_paths,
 8891                            open_options.open_new_workspace == None,
 8892                            cx,
 8893                        );
 8894                        if m > best_match {
 8895                            existing = Some((window, workspace.clone()));
 8896                            best_match = m;
 8897                        } else if best_match.is_none()
 8898                            && open_options.open_new_workspace == Some(false)
 8899                        {
 8900                            existing = Some((window, workspace.clone()))
 8901                        }
 8902                    }
 8903                }
 8904            }
 8905        });
 8906
 8907        let all_paths_are_files = existing
 8908            .as_ref()
 8909            .and_then(|(_, target_workspace)| {
 8910                cx.update(|cx| {
 8911                    let workspace = target_workspace.read(cx);
 8912                    let project = workspace.project.read(cx);
 8913                    let path_style = workspace.path_style(cx);
 8914                    Some(!abs_paths.iter().any(|path| {
 8915                        let path = util::paths::SanitizedPath::new(path);
 8916                        project.worktrees(cx).any(|worktree| {
 8917                            let worktree = worktree.read(cx);
 8918                            let abs_path = worktree.abs_path();
 8919                            path_style
 8920                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 8921                                .and_then(|rel| worktree.entry_for_path(&rel))
 8922                                .is_some_and(|e| e.is_dir())
 8923                        })
 8924                    }))
 8925                })
 8926            })
 8927            .unwrap_or(false);
 8928
 8929        if open_options.open_new_workspace.is_none()
 8930            && existing.is_some()
 8931            && open_options.wait
 8932            && all_paths_are_files
 8933        {
 8934            cx.update(|cx| {
 8935                let windows = workspace_windows_for_location(location, cx);
 8936                let window = cx
 8937                    .active_window()
 8938                    .and_then(|window| window.downcast::<MultiWorkspace>())
 8939                    .filter(|window| windows.contains(window))
 8940                    .or_else(|| windows.into_iter().next());
 8941                if let Some(window) = window {
 8942                    if let Ok(multi_workspace) = window.read(cx) {
 8943                        let active_workspace = multi_workspace.workspace().clone();
 8944                        existing = Some((window, active_workspace));
 8945                        open_visible = OpenVisible::None;
 8946                    }
 8947                }
 8948            });
 8949        }
 8950    }
 8951    (existing, open_visible)
 8952}
 8953
 8954#[derive(Default, Clone)]
 8955pub struct OpenOptions {
 8956    pub visible: Option<OpenVisible>,
 8957    pub focus: Option<bool>,
 8958    pub open_new_workspace: Option<bool>,
 8959    pub wait: bool,
 8960    pub replace_window: Option<WindowHandle<MultiWorkspace>>,
 8961    pub env: Option<HashMap<String, String>>,
 8962}
 8963
 8964/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 8965/// or [`Workspace::open_workspace_for_paths`].
 8966pub struct OpenResult {
 8967    pub window: WindowHandle<MultiWorkspace>,
 8968    pub workspace: Entity<Workspace>,
 8969    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 8970}
 8971
 8972/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 8973pub fn open_workspace_by_id(
 8974    workspace_id: WorkspaceId,
 8975    app_state: Arc<AppState>,
 8976    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8977    cx: &mut App,
 8978) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 8979    let project_handle = Project::local(
 8980        app_state.client.clone(),
 8981        app_state.node_runtime.clone(),
 8982        app_state.user_store.clone(),
 8983        app_state.languages.clone(),
 8984        app_state.fs.clone(),
 8985        None,
 8986        project::LocalProjectFlags {
 8987            init_worktree_trust: true,
 8988            ..project::LocalProjectFlags::default()
 8989        },
 8990        cx,
 8991    );
 8992
 8993    let db = WorkspaceDb::global(cx);
 8994    let kvp = db::kvp::KeyValueStore::global(cx);
 8995    cx.spawn(async move |cx| {
 8996        let serialized_workspace = db
 8997            .workspace_for_id(workspace_id)
 8998            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 8999
 9000        let centered_layout = serialized_workspace.centered_layout;
 9001
 9002        let (window, workspace) = if let Some(window) = requesting_window {
 9003            let workspace = window.update(cx, |multi_workspace, window, cx| {
 9004                let workspace = cx.new(|cx| {
 9005                    let mut workspace = Workspace::new(
 9006                        Some(workspace_id),
 9007                        project_handle.clone(),
 9008                        app_state.clone(),
 9009                        window,
 9010                        cx,
 9011                    );
 9012                    workspace.centered_layout = centered_layout;
 9013                    workspace
 9014                });
 9015                multi_workspace.add_workspace(workspace.clone(), cx);
 9016                workspace
 9017            })?;
 9018            (window, workspace)
 9019        } else {
 9020            let window_bounds_override = window_bounds_env_override();
 9021
 9022            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 9023                (Some(WindowBounds::Windowed(bounds)), None)
 9024            } else if let Some(display) = serialized_workspace.display
 9025                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 9026            {
 9027                (Some(bounds.0), Some(display))
 9028            } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
 9029                (Some(bounds), Some(display))
 9030            } else {
 9031                (None, None)
 9032            };
 9033
 9034            let options = cx.update(|cx| {
 9035                let mut options = (app_state.build_window_options)(display, cx);
 9036                options.window_bounds = window_bounds;
 9037                options
 9038            });
 9039
 9040            let window = cx.open_window(options, {
 9041                let app_state = app_state.clone();
 9042                let project_handle = project_handle.clone();
 9043                move |window, cx| {
 9044                    let workspace = cx.new(|cx| {
 9045                        let mut workspace = Workspace::new(
 9046                            Some(workspace_id),
 9047                            project_handle,
 9048                            app_state,
 9049                            window,
 9050                            cx,
 9051                        );
 9052                        workspace.centered_layout = centered_layout;
 9053                        workspace
 9054                    });
 9055                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9056                }
 9057            })?;
 9058
 9059            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 9060                multi_workspace.workspace().clone()
 9061            })?;
 9062
 9063            (window, workspace)
 9064        };
 9065
 9066        notify_if_database_failed(window, cx);
 9067
 9068        // Restore items from the serialized workspace
 9069        window
 9070            .update(cx, |_, window, cx| {
 9071                workspace.update(cx, |_workspace, cx| {
 9072                    open_items(Some(serialized_workspace), vec![], window, cx)
 9073                })
 9074            })?
 9075            .await?;
 9076
 9077        window.update(cx, |_, window, cx| {
 9078            workspace.update(cx, |workspace, cx| {
 9079                workspace.serialize_workspace(window, cx);
 9080            });
 9081        })?;
 9082
 9083        Ok(window)
 9084    })
 9085}
 9086
 9087#[allow(clippy::type_complexity)]
 9088pub fn open_paths(
 9089    abs_paths: &[PathBuf],
 9090    app_state: Arc<AppState>,
 9091    open_options: OpenOptions,
 9092    cx: &mut App,
 9093) -> Task<anyhow::Result<OpenResult>> {
 9094    let abs_paths = abs_paths.to_vec();
 9095    #[cfg(target_os = "windows")]
 9096    let wsl_path = abs_paths
 9097        .iter()
 9098        .find_map(|p| util::paths::WslPath::from_path(p));
 9099
 9100    cx.spawn(async move |cx| {
 9101        let (mut existing, mut open_visible) = find_existing_workspace(
 9102            &abs_paths,
 9103            &open_options,
 9104            &SerializedWorkspaceLocation::Local,
 9105            cx,
 9106        )
 9107        .await;
 9108
 9109        // Fallback: if no workspace contains the paths and all paths are files,
 9110        // prefer an existing local workspace window (active window first).
 9111        if open_options.open_new_workspace.is_none() && existing.is_none() {
 9112            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 9113            let all_metadatas = futures::future::join_all(all_paths)
 9114                .await
 9115                .into_iter()
 9116                .filter_map(|result| result.ok().flatten())
 9117                .collect::<Vec<_>>();
 9118
 9119            if all_metadatas.iter().all(|file| !file.is_dir) {
 9120                cx.update(|cx| {
 9121                    let windows = workspace_windows_for_location(
 9122                        &SerializedWorkspaceLocation::Local,
 9123                        cx,
 9124                    );
 9125                    let window = cx
 9126                        .active_window()
 9127                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9128                        .filter(|window| windows.contains(window))
 9129                        .or_else(|| windows.into_iter().next());
 9130                    if let Some(window) = window {
 9131                        if let Ok(multi_workspace) = window.read(cx) {
 9132                            let active_workspace = multi_workspace.workspace().clone();
 9133                            existing = Some((window, active_workspace));
 9134                            open_visible = OpenVisible::None;
 9135                        }
 9136                    }
 9137                });
 9138            }
 9139        }
 9140
 9141        let result = if let Some((existing, target_workspace)) = existing {
 9142            let open_task = existing
 9143                .update(cx, |multi_workspace, window, cx| {
 9144                    window.activate_window();
 9145                    multi_workspace.activate(target_workspace.clone(), cx);
 9146                    target_workspace.update(cx, |workspace, cx| {
 9147                        workspace.open_paths(
 9148                            abs_paths,
 9149                            OpenOptions {
 9150                                visible: Some(open_visible),
 9151                                ..Default::default()
 9152                            },
 9153                            None,
 9154                            window,
 9155                            cx,
 9156                        )
 9157                    })
 9158                })?
 9159                .await;
 9160
 9161            _ = existing.update(cx, |multi_workspace, _, cx| {
 9162                let workspace = multi_workspace.workspace().clone();
 9163                workspace.update(cx, |workspace, cx| {
 9164                    for item in open_task.iter().flatten() {
 9165                        if let Err(e) = item {
 9166                            workspace.show_error(&e, cx);
 9167                        }
 9168                    }
 9169                });
 9170            });
 9171
 9172            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9173        } else {
 9174            let result = cx
 9175                .update(move |cx| {
 9176                    Workspace::new_local(
 9177                        abs_paths,
 9178                        app_state.clone(),
 9179                        open_options.replace_window,
 9180                        open_options.env,
 9181                        None,
 9182                        true,
 9183                        cx,
 9184                    )
 9185                })
 9186                .await;
 9187
 9188            if let Ok(ref result) = result {
 9189                result.window
 9190                    .update(cx, |_, window, _cx| {
 9191                        window.activate_window();
 9192                    })
 9193                    .log_err();
 9194            }
 9195
 9196            result
 9197        };
 9198
 9199        #[cfg(target_os = "windows")]
 9200        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9201            && let Ok(ref result) = result
 9202        {
 9203            result.window
 9204                .update(cx, move |multi_workspace, _window, cx| {
 9205                    struct OpenInWsl;
 9206                    let workspace = multi_workspace.workspace().clone();
 9207                    workspace.update(cx, |workspace, cx| {
 9208                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9209                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9210                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9211                            cx.new(move |cx| {
 9212                                MessageNotification::new(msg, cx)
 9213                                    .primary_message("Open in WSL")
 9214                                    .primary_icon(IconName::FolderOpen)
 9215                                    .primary_on_click(move |window, cx| {
 9216                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9217                                                distro: remote::WslConnectionOptions {
 9218                                                        distro_name: distro.clone(),
 9219                                                    user: None,
 9220                                                },
 9221                                                paths: vec![path.clone().into()],
 9222                                            }), cx)
 9223                                    })
 9224                            })
 9225                        });
 9226                    });
 9227                })
 9228                .unwrap();
 9229        };
 9230        result
 9231    })
 9232}
 9233
 9234pub fn open_new(
 9235    open_options: OpenOptions,
 9236    app_state: Arc<AppState>,
 9237    cx: &mut App,
 9238    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9239) -> Task<anyhow::Result<()>> {
 9240    let task = Workspace::new_local(
 9241        Vec::new(),
 9242        app_state,
 9243        open_options.replace_window,
 9244        open_options.env,
 9245        Some(Box::new(init)),
 9246        true,
 9247        cx,
 9248    );
 9249    cx.spawn(async move |cx| {
 9250        let OpenResult { window, .. } = task.await?;
 9251        window
 9252            .update(cx, |_, window, _cx| {
 9253                window.activate_window();
 9254            })
 9255            .ok();
 9256        Ok(())
 9257    })
 9258}
 9259
 9260pub fn create_and_open_local_file(
 9261    path: &'static Path,
 9262    window: &mut Window,
 9263    cx: &mut Context<Workspace>,
 9264    default_content: impl 'static + Send + FnOnce() -> Rope,
 9265) -> Task<Result<Box<dyn ItemHandle>>> {
 9266    cx.spawn_in(window, async move |workspace, cx| {
 9267        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9268        if !fs.is_file(path).await {
 9269            fs.create_file(path, Default::default()).await?;
 9270            fs.save(path, &default_content(), Default::default())
 9271                .await?;
 9272        }
 9273
 9274        workspace
 9275            .update_in(cx, |workspace, window, cx| {
 9276                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9277                    let path = workspace
 9278                        .project
 9279                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9280                    cx.spawn_in(window, async move |workspace, cx| {
 9281                        let path = path.await?;
 9282                        let mut items = workspace
 9283                            .update_in(cx, |workspace, window, cx| {
 9284                                workspace.open_paths(
 9285                                    vec![path.to_path_buf()],
 9286                                    OpenOptions {
 9287                                        visible: Some(OpenVisible::None),
 9288                                        ..Default::default()
 9289                                    },
 9290                                    None,
 9291                                    window,
 9292                                    cx,
 9293                                )
 9294                            })?
 9295                            .await;
 9296                        let item = items.pop().flatten();
 9297                        item.with_context(|| format!("path {path:?} is not a file"))?
 9298                    })
 9299                })
 9300            })?
 9301            .await?
 9302            .await
 9303    })
 9304}
 9305
 9306pub fn open_remote_project_with_new_connection(
 9307    window: WindowHandle<MultiWorkspace>,
 9308    remote_connection: Arc<dyn RemoteConnection>,
 9309    cancel_rx: oneshot::Receiver<()>,
 9310    delegate: Arc<dyn RemoteClientDelegate>,
 9311    app_state: Arc<AppState>,
 9312    paths: Vec<PathBuf>,
 9313    cx: &mut App,
 9314) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9315    cx.spawn(async move |cx| {
 9316        let (workspace_id, serialized_workspace) =
 9317            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9318                .await?;
 9319
 9320        let session = match cx
 9321            .update(|cx| {
 9322                remote::RemoteClient::new(
 9323                    ConnectionIdentifier::Workspace(workspace_id.0),
 9324                    remote_connection,
 9325                    cancel_rx,
 9326                    delegate,
 9327                    cx,
 9328                )
 9329            })
 9330            .await?
 9331        {
 9332            Some(result) => result,
 9333            None => return Ok(Vec::new()),
 9334        };
 9335
 9336        let project = cx.update(|cx| {
 9337            project::Project::remote(
 9338                session,
 9339                app_state.client.clone(),
 9340                app_state.node_runtime.clone(),
 9341                app_state.user_store.clone(),
 9342                app_state.languages.clone(),
 9343                app_state.fs.clone(),
 9344                true,
 9345                cx,
 9346            )
 9347        });
 9348
 9349        open_remote_project_inner(
 9350            project,
 9351            paths,
 9352            workspace_id,
 9353            serialized_workspace,
 9354            app_state,
 9355            window,
 9356            cx,
 9357        )
 9358        .await
 9359    })
 9360}
 9361
 9362pub fn open_remote_project_with_existing_connection(
 9363    connection_options: RemoteConnectionOptions,
 9364    project: Entity<Project>,
 9365    paths: Vec<PathBuf>,
 9366    app_state: Arc<AppState>,
 9367    window: WindowHandle<MultiWorkspace>,
 9368    cx: &mut AsyncApp,
 9369) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9370    cx.spawn(async move |cx| {
 9371        let (workspace_id, serialized_workspace) =
 9372            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9373
 9374        open_remote_project_inner(
 9375            project,
 9376            paths,
 9377            workspace_id,
 9378            serialized_workspace,
 9379            app_state,
 9380            window,
 9381            cx,
 9382        )
 9383        .await
 9384    })
 9385}
 9386
 9387async fn open_remote_project_inner(
 9388    project: Entity<Project>,
 9389    paths: Vec<PathBuf>,
 9390    workspace_id: WorkspaceId,
 9391    serialized_workspace: Option<SerializedWorkspace>,
 9392    app_state: Arc<AppState>,
 9393    window: WindowHandle<MultiWorkspace>,
 9394    cx: &mut AsyncApp,
 9395) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9396    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9397    let toolchains = db.toolchains(workspace_id).await?;
 9398    for (toolchain, worktree_path, path) in toolchains {
 9399        project
 9400            .update(cx, |this, cx| {
 9401                let Some(worktree_id) =
 9402                    this.find_worktree(&worktree_path, cx)
 9403                        .and_then(|(worktree, rel_path)| {
 9404                            if rel_path.is_empty() {
 9405                                Some(worktree.read(cx).id())
 9406                            } else {
 9407                                None
 9408                            }
 9409                        })
 9410                else {
 9411                    return Task::ready(None);
 9412                };
 9413
 9414                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9415            })
 9416            .await;
 9417    }
 9418    let mut project_paths_to_open = vec![];
 9419    let mut project_path_errors = vec![];
 9420
 9421    for path in paths {
 9422        let result = cx
 9423            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9424            .await;
 9425        match result {
 9426            Ok((_, project_path)) => {
 9427                project_paths_to_open.push((path.clone(), Some(project_path)));
 9428            }
 9429            Err(error) => {
 9430                project_path_errors.push(error);
 9431            }
 9432        };
 9433    }
 9434
 9435    if project_paths_to_open.is_empty() {
 9436        return Err(project_path_errors.pop().context("no paths given")?);
 9437    }
 9438
 9439    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9440        telemetry::event!("SSH Project Opened");
 9441
 9442        let new_workspace = cx.new(|cx| {
 9443            let mut workspace =
 9444                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9445            workspace.update_history(cx);
 9446
 9447            if let Some(ref serialized) = serialized_workspace {
 9448                workspace.centered_layout = serialized.centered_layout;
 9449            }
 9450
 9451            workspace
 9452        });
 9453
 9454        multi_workspace.activate(new_workspace.clone(), cx);
 9455        new_workspace
 9456    })?;
 9457
 9458    let items = window
 9459        .update(cx, |_, window, cx| {
 9460            window.activate_window();
 9461            workspace.update(cx, |_workspace, cx| {
 9462                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9463            })
 9464        })?
 9465        .await?;
 9466
 9467    workspace.update(cx, |workspace, cx| {
 9468        for error in project_path_errors {
 9469            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9470                if let Some(path) = error.error_tag("path") {
 9471                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9472                }
 9473            } else {
 9474                workspace.show_error(&error, cx)
 9475            }
 9476        }
 9477    });
 9478
 9479    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9480}
 9481
 9482fn deserialize_remote_project(
 9483    connection_options: RemoteConnectionOptions,
 9484    paths: Vec<PathBuf>,
 9485    cx: &AsyncApp,
 9486) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9487    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9488    cx.background_spawn(async move {
 9489        let remote_connection_id = db
 9490            .get_or_create_remote_connection(connection_options)
 9491            .await?;
 9492
 9493        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
 9494
 9495        let workspace_id = if let Some(workspace_id) =
 9496            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9497        {
 9498            workspace_id
 9499        } else {
 9500            db.next_id().await?
 9501        };
 9502
 9503        Ok((workspace_id, serialized_workspace))
 9504    })
 9505}
 9506
 9507pub fn join_in_room_project(
 9508    project_id: u64,
 9509    follow_user_id: u64,
 9510    app_state: Arc<AppState>,
 9511    cx: &mut App,
 9512) -> Task<Result<()>> {
 9513    let windows = cx.windows();
 9514    cx.spawn(async move |cx| {
 9515        let existing_window_and_workspace: Option<(
 9516            WindowHandle<MultiWorkspace>,
 9517            Entity<Workspace>,
 9518        )> = windows.into_iter().find_map(|window_handle| {
 9519            window_handle
 9520                .downcast::<MultiWorkspace>()
 9521                .and_then(|window_handle| {
 9522                    window_handle
 9523                        .update(cx, |multi_workspace, _window, cx| {
 9524                            for workspace in multi_workspace.workspaces() {
 9525                                if workspace.read(cx).project().read(cx).remote_id()
 9526                                    == Some(project_id)
 9527                                {
 9528                                    return Some((window_handle, workspace.clone()));
 9529                                }
 9530                            }
 9531                            None
 9532                        })
 9533                        .unwrap_or(None)
 9534                })
 9535        });
 9536
 9537        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9538            existing_window_and_workspace
 9539        {
 9540            existing_window
 9541                .update(cx, |multi_workspace, _, cx| {
 9542                    multi_workspace.activate(target_workspace, cx);
 9543                })
 9544                .ok();
 9545            existing_window
 9546        } else {
 9547            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9548            let project = cx
 9549                .update(|cx| {
 9550                    active_call.0.join_project(
 9551                        project_id,
 9552                        app_state.languages.clone(),
 9553                        app_state.fs.clone(),
 9554                        cx,
 9555                    )
 9556                })
 9557                .await?;
 9558
 9559            let window_bounds_override = window_bounds_env_override();
 9560            cx.update(|cx| {
 9561                let mut options = (app_state.build_window_options)(None, cx);
 9562                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9563                cx.open_window(options, |window, cx| {
 9564                    let workspace = cx.new(|cx| {
 9565                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9566                    });
 9567                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9568                })
 9569            })?
 9570        };
 9571
 9572        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9573            cx.activate(true);
 9574            window.activate_window();
 9575
 9576            // We set the active workspace above, so this is the correct workspace.
 9577            let workspace = multi_workspace.workspace().clone();
 9578            workspace.update(cx, |workspace, cx| {
 9579                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9580                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9581                    .or_else(|| {
 9582                        // If we couldn't follow the given user, follow the host instead.
 9583                        let collaborator = workspace
 9584                            .project()
 9585                            .read(cx)
 9586                            .collaborators()
 9587                            .values()
 9588                            .find(|collaborator| collaborator.is_host)?;
 9589                        Some(collaborator.peer_id)
 9590                    });
 9591
 9592                if let Some(follow_peer_id) = follow_peer_id {
 9593                    workspace.follow(follow_peer_id, window, cx);
 9594                }
 9595            });
 9596        })?;
 9597
 9598        anyhow::Ok(())
 9599    })
 9600}
 9601
 9602pub fn reload(cx: &mut App) {
 9603    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9604    let mut workspace_windows = cx
 9605        .windows()
 9606        .into_iter()
 9607        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9608        .collect::<Vec<_>>();
 9609
 9610    // If multiple windows have unsaved changes, and need a save prompt,
 9611    // prompt in the active window before switching to a different window.
 9612    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9613
 9614    let mut prompt = None;
 9615    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9616        prompt = window
 9617            .update(cx, |_, window, cx| {
 9618                window.prompt(
 9619                    PromptLevel::Info,
 9620                    "Are you sure you want to restart?",
 9621                    None,
 9622                    &["Restart", "Cancel"],
 9623                    cx,
 9624                )
 9625            })
 9626            .ok();
 9627    }
 9628
 9629    cx.spawn(async move |cx| {
 9630        if let Some(prompt) = prompt {
 9631            let answer = prompt.await?;
 9632            if answer != 0 {
 9633                return anyhow::Ok(());
 9634            }
 9635        }
 9636
 9637        // If the user cancels any save prompt, then keep the app open.
 9638        for window in workspace_windows {
 9639            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9640                let workspace = multi_workspace.workspace().clone();
 9641                workspace.update(cx, |workspace, cx| {
 9642                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9643                })
 9644            }) && !should_close.await?
 9645            {
 9646                return anyhow::Ok(());
 9647            }
 9648        }
 9649        cx.update(|cx| cx.restart());
 9650        anyhow::Ok(())
 9651    })
 9652    .detach_and_log_err(cx);
 9653}
 9654
 9655fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9656    let mut parts = value.split(',');
 9657    let x: usize = parts.next()?.parse().ok()?;
 9658    let y: usize = parts.next()?.parse().ok()?;
 9659    Some(point(px(x as f32), px(y as f32)))
 9660}
 9661
 9662fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9663    let mut parts = value.split(',');
 9664    let width: usize = parts.next()?.parse().ok()?;
 9665    let height: usize = parts.next()?.parse().ok()?;
 9666    Some(size(px(width as f32), px(height as f32)))
 9667}
 9668
 9669/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9670/// appropriate.
 9671///
 9672/// The `border_radius_tiling` parameter allows overriding which corners get
 9673/// rounded, independently of the actual window tiling state. This is used
 9674/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9675/// we want square corners on the left (so the sidebar appears flush with the
 9676/// window edge) but we still need the shadow padding for proper visual
 9677/// appearance. Unlike actual window tiling, this only affects border radius -
 9678/// not padding or shadows.
 9679pub fn client_side_decorations(
 9680    element: impl IntoElement,
 9681    window: &mut Window,
 9682    cx: &mut App,
 9683    border_radius_tiling: Tiling,
 9684) -> Stateful<Div> {
 9685    const BORDER_SIZE: Pixels = px(1.0);
 9686    let decorations = window.window_decorations();
 9687    let tiling = match decorations {
 9688        Decorations::Server => Tiling::default(),
 9689        Decorations::Client { tiling } => tiling,
 9690    };
 9691
 9692    match decorations {
 9693        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9694        Decorations::Server => window.set_client_inset(px(0.0)),
 9695    }
 9696
 9697    struct GlobalResizeEdge(ResizeEdge);
 9698    impl Global for GlobalResizeEdge {}
 9699
 9700    div()
 9701        .id("window-backdrop")
 9702        .bg(transparent_black())
 9703        .map(|div| match decorations {
 9704            Decorations::Server => div,
 9705            Decorations::Client { .. } => div
 9706                .when(
 9707                    !(tiling.top
 9708                        || tiling.right
 9709                        || border_radius_tiling.top
 9710                        || border_radius_tiling.right),
 9711                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9712                )
 9713                .when(
 9714                    !(tiling.top
 9715                        || tiling.left
 9716                        || border_radius_tiling.top
 9717                        || border_radius_tiling.left),
 9718                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9719                )
 9720                .when(
 9721                    !(tiling.bottom
 9722                        || tiling.right
 9723                        || border_radius_tiling.bottom
 9724                        || border_radius_tiling.right),
 9725                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9726                )
 9727                .when(
 9728                    !(tiling.bottom
 9729                        || tiling.left
 9730                        || border_radius_tiling.bottom
 9731                        || border_radius_tiling.left),
 9732                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9733                )
 9734                .when(!tiling.top, |div| {
 9735                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9736                })
 9737                .when(!tiling.bottom, |div| {
 9738                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9739                })
 9740                .when(!tiling.left, |div| {
 9741                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9742                })
 9743                .when(!tiling.right, |div| {
 9744                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9745                })
 9746                .on_mouse_move(move |e, window, cx| {
 9747                    let size = window.window_bounds().get_bounds().size;
 9748                    let pos = e.position;
 9749
 9750                    let new_edge =
 9751                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 9752
 9753                    let edge = cx.try_global::<GlobalResizeEdge>();
 9754                    if new_edge != edge.map(|edge| edge.0) {
 9755                        window
 9756                            .window_handle()
 9757                            .update(cx, |workspace, _, cx| {
 9758                                cx.notify(workspace.entity_id());
 9759                            })
 9760                            .ok();
 9761                    }
 9762                })
 9763                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 9764                    let size = window.window_bounds().get_bounds().size;
 9765                    let pos = e.position;
 9766
 9767                    let edge = match resize_edge(
 9768                        pos,
 9769                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 9770                        size,
 9771                        tiling,
 9772                    ) {
 9773                        Some(value) => value,
 9774                        None => return,
 9775                    };
 9776
 9777                    window.start_window_resize(edge);
 9778                }),
 9779        })
 9780        .size_full()
 9781        .child(
 9782            div()
 9783                .cursor(CursorStyle::Arrow)
 9784                .map(|div| match decorations {
 9785                    Decorations::Server => div,
 9786                    Decorations::Client { .. } => div
 9787                        .border_color(cx.theme().colors().border)
 9788                        .when(
 9789                            !(tiling.top
 9790                                || tiling.right
 9791                                || border_radius_tiling.top
 9792                                || border_radius_tiling.right),
 9793                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9794                        )
 9795                        .when(
 9796                            !(tiling.top
 9797                                || tiling.left
 9798                                || border_radius_tiling.top
 9799                                || border_radius_tiling.left),
 9800                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9801                        )
 9802                        .when(
 9803                            !(tiling.bottom
 9804                                || tiling.right
 9805                                || border_radius_tiling.bottom
 9806                                || border_radius_tiling.right),
 9807                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9808                        )
 9809                        .when(
 9810                            !(tiling.bottom
 9811                                || tiling.left
 9812                                || border_radius_tiling.bottom
 9813                                || border_radius_tiling.left),
 9814                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9815                        )
 9816                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 9817                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 9818                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 9819                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 9820                        .when(!tiling.is_tiled(), |div| {
 9821                            div.shadow(vec![gpui::BoxShadow {
 9822                                color: Hsla {
 9823                                    h: 0.,
 9824                                    s: 0.,
 9825                                    l: 0.,
 9826                                    a: 0.4,
 9827                                },
 9828                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 9829                                spread_radius: px(0.),
 9830                                offset: point(px(0.0), px(0.0)),
 9831                            }])
 9832                        }),
 9833                })
 9834                .on_mouse_move(|_e, _, cx| {
 9835                    cx.stop_propagation();
 9836                })
 9837                .size_full()
 9838                .child(element),
 9839        )
 9840        .map(|div| match decorations {
 9841            Decorations::Server => div,
 9842            Decorations::Client { tiling, .. } => div.child(
 9843                canvas(
 9844                    |_bounds, window, _| {
 9845                        window.insert_hitbox(
 9846                            Bounds::new(
 9847                                point(px(0.0), px(0.0)),
 9848                                window.window_bounds().get_bounds().size,
 9849                            ),
 9850                            HitboxBehavior::Normal,
 9851                        )
 9852                    },
 9853                    move |_bounds, hitbox, window, cx| {
 9854                        let mouse = window.mouse_position();
 9855                        let size = window.window_bounds().get_bounds().size;
 9856                        let Some(edge) =
 9857                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 9858                        else {
 9859                            return;
 9860                        };
 9861                        cx.set_global(GlobalResizeEdge(edge));
 9862                        window.set_cursor_style(
 9863                            match edge {
 9864                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 9865                                ResizeEdge::Left | ResizeEdge::Right => {
 9866                                    CursorStyle::ResizeLeftRight
 9867                                }
 9868                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 9869                                    CursorStyle::ResizeUpLeftDownRight
 9870                                }
 9871                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 9872                                    CursorStyle::ResizeUpRightDownLeft
 9873                                }
 9874                            },
 9875                            &hitbox,
 9876                        );
 9877                    },
 9878                )
 9879                .size_full()
 9880                .absolute(),
 9881            ),
 9882        })
 9883}
 9884
 9885fn resize_edge(
 9886    pos: Point<Pixels>,
 9887    shadow_size: Pixels,
 9888    window_size: Size<Pixels>,
 9889    tiling: Tiling,
 9890) -> Option<ResizeEdge> {
 9891    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 9892    if bounds.contains(&pos) {
 9893        return None;
 9894    }
 9895
 9896    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 9897    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 9898    if !tiling.top && top_left_bounds.contains(&pos) {
 9899        return Some(ResizeEdge::TopLeft);
 9900    }
 9901
 9902    let top_right_bounds = Bounds::new(
 9903        Point::new(window_size.width - corner_size.width, px(0.)),
 9904        corner_size,
 9905    );
 9906    if !tiling.top && top_right_bounds.contains(&pos) {
 9907        return Some(ResizeEdge::TopRight);
 9908    }
 9909
 9910    let bottom_left_bounds = Bounds::new(
 9911        Point::new(px(0.), window_size.height - corner_size.height),
 9912        corner_size,
 9913    );
 9914    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 9915        return Some(ResizeEdge::BottomLeft);
 9916    }
 9917
 9918    let bottom_right_bounds = Bounds::new(
 9919        Point::new(
 9920            window_size.width - corner_size.width,
 9921            window_size.height - corner_size.height,
 9922        ),
 9923        corner_size,
 9924    );
 9925    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 9926        return Some(ResizeEdge::BottomRight);
 9927    }
 9928
 9929    if !tiling.top && pos.y < shadow_size {
 9930        Some(ResizeEdge::Top)
 9931    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 9932        Some(ResizeEdge::Bottom)
 9933    } else if !tiling.left && pos.x < shadow_size {
 9934        Some(ResizeEdge::Left)
 9935    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 9936        Some(ResizeEdge::Right)
 9937    } else {
 9938        None
 9939    }
 9940}
 9941
 9942fn join_pane_into_active(
 9943    active_pane: &Entity<Pane>,
 9944    pane: &Entity<Pane>,
 9945    window: &mut Window,
 9946    cx: &mut App,
 9947) {
 9948    if pane == active_pane {
 9949    } else if pane.read(cx).items_len() == 0 {
 9950        pane.update(cx, |_, cx| {
 9951            cx.emit(pane::Event::Remove {
 9952                focus_on_pane: None,
 9953            });
 9954        })
 9955    } else {
 9956        move_all_items(pane, active_pane, window, cx);
 9957    }
 9958}
 9959
 9960fn move_all_items(
 9961    from_pane: &Entity<Pane>,
 9962    to_pane: &Entity<Pane>,
 9963    window: &mut Window,
 9964    cx: &mut App,
 9965) {
 9966    let destination_is_different = from_pane != to_pane;
 9967    let mut moved_items = 0;
 9968    for (item_ix, item_handle) in from_pane
 9969        .read(cx)
 9970        .items()
 9971        .enumerate()
 9972        .map(|(ix, item)| (ix, item.clone()))
 9973        .collect::<Vec<_>>()
 9974    {
 9975        let ix = item_ix - moved_items;
 9976        if destination_is_different {
 9977            // Close item from previous pane
 9978            from_pane.update(cx, |source, cx| {
 9979                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 9980            });
 9981            moved_items += 1;
 9982        }
 9983
 9984        // This automatically removes duplicate items in the pane
 9985        to_pane.update(cx, |destination, cx| {
 9986            destination.add_item(item_handle, true, true, None, window, cx);
 9987            window.focus(&destination.focus_handle(cx), cx)
 9988        });
 9989    }
 9990}
 9991
 9992pub fn move_item(
 9993    source: &Entity<Pane>,
 9994    destination: &Entity<Pane>,
 9995    item_id_to_move: EntityId,
 9996    destination_index: usize,
 9997    activate: bool,
 9998    window: &mut Window,
 9999    cx: &mut App,
10000) {
10001    let Some((item_ix, item_handle)) = source
10002        .read(cx)
10003        .items()
10004        .enumerate()
10005        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10006        .map(|(ix, item)| (ix, item.clone()))
10007    else {
10008        // Tab was closed during drag
10009        return;
10010    };
10011
10012    if source != destination {
10013        // Close item from previous pane
10014        source.update(cx, |source, cx| {
10015            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10016        });
10017    }
10018
10019    // This automatically removes duplicate items in the pane
10020    destination.update(cx, |destination, cx| {
10021        destination.add_item_inner(
10022            item_handle,
10023            activate,
10024            activate,
10025            activate,
10026            Some(destination_index),
10027            window,
10028            cx,
10029        );
10030        if activate {
10031            window.focus(&destination.focus_handle(cx), cx)
10032        }
10033    });
10034}
10035
10036pub fn move_active_item(
10037    source: &Entity<Pane>,
10038    destination: &Entity<Pane>,
10039    focus_destination: bool,
10040    close_if_empty: bool,
10041    window: &mut Window,
10042    cx: &mut App,
10043) {
10044    if source == destination {
10045        return;
10046    }
10047    let Some(active_item) = source.read(cx).active_item() else {
10048        return;
10049    };
10050    source.update(cx, |source_pane, cx| {
10051        let item_id = active_item.item_id();
10052        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10053        destination.update(cx, |target_pane, cx| {
10054            target_pane.add_item(
10055                active_item,
10056                focus_destination,
10057                focus_destination,
10058                Some(target_pane.items_len()),
10059                window,
10060                cx,
10061            );
10062        });
10063    });
10064}
10065
10066pub fn clone_active_item(
10067    workspace_id: Option<WorkspaceId>,
10068    source: &Entity<Pane>,
10069    destination: &Entity<Pane>,
10070    focus_destination: bool,
10071    window: &mut Window,
10072    cx: &mut App,
10073) {
10074    if source == destination {
10075        return;
10076    }
10077    let Some(active_item) = source.read(cx).active_item() else {
10078        return;
10079    };
10080    if !active_item.can_split(cx) {
10081        return;
10082    }
10083    let destination = destination.downgrade();
10084    let task = active_item.clone_on_split(workspace_id, window, cx);
10085    window
10086        .spawn(cx, async move |cx| {
10087            let Some(clone) = task.await else {
10088                return;
10089            };
10090            destination
10091                .update_in(cx, |target_pane, window, cx| {
10092                    target_pane.add_item(
10093                        clone,
10094                        focus_destination,
10095                        focus_destination,
10096                        Some(target_pane.items_len()),
10097                        window,
10098                        cx,
10099                    );
10100                })
10101                .log_err();
10102        })
10103        .detach();
10104}
10105
10106#[derive(Debug)]
10107pub struct WorkspacePosition {
10108    pub window_bounds: Option<WindowBounds>,
10109    pub display: Option<Uuid>,
10110    pub centered_layout: bool,
10111}
10112
10113pub fn remote_workspace_position_from_db(
10114    connection_options: RemoteConnectionOptions,
10115    paths_to_open: &[PathBuf],
10116    cx: &App,
10117) -> Task<Result<WorkspacePosition>> {
10118    let paths = paths_to_open.to_vec();
10119    let db = WorkspaceDb::global(cx);
10120    let kvp = db::kvp::KeyValueStore::global(cx);
10121
10122    cx.background_spawn(async move {
10123        let remote_connection_id = db
10124            .get_or_create_remote_connection(connection_options)
10125            .await
10126            .context("fetching serialized ssh project")?;
10127        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10128
10129        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10130            (Some(WindowBounds::Windowed(bounds)), None)
10131        } else {
10132            let restorable_bounds = serialized_workspace
10133                .as_ref()
10134                .and_then(|workspace| {
10135                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10136                })
10137                .or_else(|| persistence::read_default_window_bounds(&kvp));
10138
10139            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10140                (Some(serialized_bounds), Some(serialized_display))
10141            } else {
10142                (None, None)
10143            }
10144        };
10145
10146        let centered_layout = serialized_workspace
10147            .as_ref()
10148            .map(|w| w.centered_layout)
10149            .unwrap_or(false);
10150
10151        Ok(WorkspacePosition {
10152            window_bounds,
10153            display,
10154            centered_layout,
10155        })
10156    })
10157}
10158
10159pub fn with_active_or_new_workspace(
10160    cx: &mut App,
10161    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10162) {
10163    match cx
10164        .active_window()
10165        .and_then(|w| w.downcast::<MultiWorkspace>())
10166    {
10167        Some(multi_workspace) => {
10168            cx.defer(move |cx| {
10169                multi_workspace
10170                    .update(cx, |multi_workspace, window, cx| {
10171                        let workspace = multi_workspace.workspace().clone();
10172                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10173                    })
10174                    .log_err();
10175            });
10176        }
10177        None => {
10178            let app_state = AppState::global(cx);
10179            if let Some(app_state) = app_state.upgrade() {
10180                open_new(
10181                    OpenOptions::default(),
10182                    app_state,
10183                    cx,
10184                    move |workspace, window, cx| f(workspace, window, cx),
10185                )
10186                .detach_and_log_err(cx);
10187            }
10188        }
10189    }
10190}
10191
10192#[cfg(test)]
10193mod tests {
10194    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10195
10196    use super::*;
10197    use crate::{
10198        dock::{PanelEvent, test::TestPanel},
10199        item::{
10200            ItemBufferKind, ItemEvent,
10201            test::{TestItem, TestProjectItem},
10202        },
10203    };
10204    use fs::FakeFs;
10205    use gpui::{
10206        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10207        UpdateGlobal, VisualTestContext, px,
10208    };
10209    use project::{Project, ProjectEntryId};
10210    use serde_json::json;
10211    use settings::SettingsStore;
10212    use util::path;
10213    use util::rel_path::rel_path;
10214
10215    #[gpui::test]
10216    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10217        init_test(cx);
10218
10219        let fs = FakeFs::new(cx.executor());
10220        let project = Project::test(fs, [], cx).await;
10221        let (workspace, cx) =
10222            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10223
10224        // Adding an item with no ambiguity renders the tab without detail.
10225        let item1 = cx.new(|cx| {
10226            let mut item = TestItem::new(cx);
10227            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10228            item
10229        });
10230        workspace.update_in(cx, |workspace, window, cx| {
10231            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10232        });
10233        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10234
10235        // Adding an item that creates ambiguity increases the level of detail on
10236        // both tabs.
10237        let item2 = cx.new_window_entity(|_window, cx| {
10238            let mut item = TestItem::new(cx);
10239            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10240            item
10241        });
10242        workspace.update_in(cx, |workspace, window, cx| {
10243            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10244        });
10245        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10246        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10247
10248        // Adding an item that creates ambiguity increases the level of detail only
10249        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10250        // we stop at the highest detail available.
10251        let item3 = cx.new(|cx| {
10252            let mut item = TestItem::new(cx);
10253            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10254            item
10255        });
10256        workspace.update_in(cx, |workspace, window, cx| {
10257            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10258        });
10259        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10260        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10261        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10262    }
10263
10264    #[gpui::test]
10265    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10266        init_test(cx);
10267
10268        let fs = FakeFs::new(cx.executor());
10269        fs.insert_tree(
10270            "/root1",
10271            json!({
10272                "one.txt": "",
10273                "two.txt": "",
10274            }),
10275        )
10276        .await;
10277        fs.insert_tree(
10278            "/root2",
10279            json!({
10280                "three.txt": "",
10281            }),
10282        )
10283        .await;
10284
10285        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10286        let (workspace, cx) =
10287            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10288        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10289        let worktree_id = project.update(cx, |project, cx| {
10290            project.worktrees(cx).next().unwrap().read(cx).id()
10291        });
10292
10293        let item1 = cx.new(|cx| {
10294            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10295        });
10296        let item2 = cx.new(|cx| {
10297            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10298        });
10299
10300        // Add an item to an empty pane
10301        workspace.update_in(cx, |workspace, window, cx| {
10302            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10303        });
10304        project.update(cx, |project, cx| {
10305            assert_eq!(
10306                project.active_entry(),
10307                project
10308                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10309                    .map(|e| e.id)
10310            );
10311        });
10312        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10313
10314        // Add a second item to a non-empty pane
10315        workspace.update_in(cx, |workspace, window, cx| {
10316            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10317        });
10318        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10319        project.update(cx, |project, cx| {
10320            assert_eq!(
10321                project.active_entry(),
10322                project
10323                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10324                    .map(|e| e.id)
10325            );
10326        });
10327
10328        // Close the active item
10329        pane.update_in(cx, |pane, window, cx| {
10330            pane.close_active_item(&Default::default(), window, cx)
10331        })
10332        .await
10333        .unwrap();
10334        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10335        project.update(cx, |project, cx| {
10336            assert_eq!(
10337                project.active_entry(),
10338                project
10339                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10340                    .map(|e| e.id)
10341            );
10342        });
10343
10344        // Add a project folder
10345        project
10346            .update(cx, |project, cx| {
10347                project.find_or_create_worktree("root2", true, cx)
10348            })
10349            .await
10350            .unwrap();
10351        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10352
10353        // Remove a project folder
10354        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10355        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10356    }
10357
10358    #[gpui::test]
10359    async fn test_close_window(cx: &mut TestAppContext) {
10360        init_test(cx);
10361
10362        let fs = FakeFs::new(cx.executor());
10363        fs.insert_tree("/root", json!({ "one": "" })).await;
10364
10365        let project = Project::test(fs, ["root".as_ref()], cx).await;
10366        let (workspace, cx) =
10367            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10368
10369        // When there are no dirty items, there's nothing to do.
10370        let item1 = cx.new(TestItem::new);
10371        workspace.update_in(cx, |w, window, cx| {
10372            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10373        });
10374        let task = workspace.update_in(cx, |w, window, cx| {
10375            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10376        });
10377        assert!(task.await.unwrap());
10378
10379        // When there are dirty untitled items, prompt to save each one. If the user
10380        // cancels any prompt, then abort.
10381        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10382        let item3 = cx.new(|cx| {
10383            TestItem::new(cx)
10384                .with_dirty(true)
10385                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10386        });
10387        workspace.update_in(cx, |w, window, cx| {
10388            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10389            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10390        });
10391        let task = workspace.update_in(cx, |w, window, cx| {
10392            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10393        });
10394        cx.executor().run_until_parked();
10395        cx.simulate_prompt_answer("Cancel"); // cancel save all
10396        cx.executor().run_until_parked();
10397        assert!(!cx.has_pending_prompt());
10398        assert!(!task.await.unwrap());
10399    }
10400
10401    #[gpui::test]
10402    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10403        init_test(cx);
10404
10405        let fs = FakeFs::new(cx.executor());
10406        fs.insert_tree("/root", json!({ "one": "" })).await;
10407
10408        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10409        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10410        let multi_workspace_handle =
10411            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10412        cx.run_until_parked();
10413
10414        let workspace_a = multi_workspace_handle
10415            .read_with(cx, |mw, _| mw.workspace().clone())
10416            .unwrap();
10417
10418        let workspace_b = multi_workspace_handle
10419            .update(cx, |mw, window, cx| {
10420                mw.test_add_workspace(project_b, window, cx)
10421            })
10422            .unwrap();
10423
10424        // Activate workspace A
10425        multi_workspace_handle
10426            .update(cx, |mw, window, cx| {
10427                mw.activate_index(0, window, cx);
10428            })
10429            .unwrap();
10430
10431        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10432
10433        // Workspace A has a clean item
10434        let item_a = cx.new(TestItem::new);
10435        workspace_a.update_in(cx, |w, window, cx| {
10436            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10437        });
10438
10439        // Workspace B has a dirty item
10440        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10441        workspace_b.update_in(cx, |w, window, cx| {
10442            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10443        });
10444
10445        // Verify workspace A is active
10446        multi_workspace_handle
10447            .read_with(cx, |mw, _| {
10448                assert_eq!(mw.active_workspace_index(), 0);
10449            })
10450            .unwrap();
10451
10452        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10453        multi_workspace_handle
10454            .update(cx, |mw, window, cx| {
10455                mw.close_window(&CloseWindow, window, cx);
10456            })
10457            .unwrap();
10458        cx.run_until_parked();
10459
10460        // Workspace B should now be active since it has dirty items that need attention
10461        multi_workspace_handle
10462            .read_with(cx, |mw, _| {
10463                assert_eq!(
10464                    mw.active_workspace_index(),
10465                    1,
10466                    "workspace B should be activated when it prompts"
10467                );
10468            })
10469            .unwrap();
10470
10471        // User cancels the save prompt from workspace B
10472        cx.simulate_prompt_answer("Cancel");
10473        cx.run_until_parked();
10474
10475        // Window should still exist because workspace B's close was cancelled
10476        assert!(
10477            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10478            "window should still exist after cancelling one workspace's close"
10479        );
10480    }
10481
10482    #[gpui::test]
10483    async fn test_open_workspace_for_paths_keeps_overlapping_directory_workspaces_distinct(
10484        cx: &mut TestAppContext,
10485    ) {
10486        init_test(cx);
10487        cx.update(|cx| {
10488            use feature_flags::FeatureFlagAppExt as _;
10489            cx.update_flags(false, vec!["agent-v2".to_string()]);
10490        });
10491
10492        let fs = FakeFs::new(cx.executor());
10493        fs.insert_tree("/zed", json!({ "src": {} })).await;
10494        fs.insert_tree("/foo", json!({ "lib": {} })).await;
10495
10496        let project = Project::test(fs.clone(), ["/zed".as_ref()], cx).await;
10497        let multi_workspace_handle =
10498            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
10499        cx.run_until_parked();
10500
10501        let open_task = multi_workspace_handle
10502            .update(cx, |multi_workspace, window, cx| {
10503                let workspace = multi_workspace.workspace().clone();
10504                workspace.update(cx, |workspace, cx| {
10505                    workspace.open_workspace_for_paths(
10506                        true,
10507                        vec![PathBuf::from("/zed"), PathBuf::from("/foo")],
10508                        window,
10509                        cx,
10510                    )
10511                })
10512            })
10513            .unwrap();
10514
10515        let opened_workspace = open_task.await.unwrap();
10516        cx.run_until_parked();
10517
10518        multi_workspace_handle
10519            .read_with(cx, |multi_workspace, cx| {
10520                assert_eq!(multi_workspace.workspaces().len(), 2);
10521
10522                let original_paths =
10523                    PathList::new(&multi_workspace.workspaces()[0].read(cx).root_paths(cx));
10524                assert_eq!(original_paths.paths(), &[PathBuf::from("/zed")]);
10525
10526                let opened_paths = PathList::new(&opened_workspace.read(cx).root_paths(cx));
10527                assert_eq!(
10528                    opened_paths.paths(),
10529                    &[PathBuf::from("/foo"), PathBuf::from("/zed")]
10530                );
10531            })
10532            .unwrap();
10533    }
10534
10535    #[gpui::test]
10536    async fn test_open_workspace_for_paths_reuses_exact_directory_workspace_match(
10537        cx: &mut TestAppContext,
10538    ) {
10539        init_test(cx);
10540        cx.update(|cx| {
10541            use feature_flags::FeatureFlagAppExt as _;
10542            cx.update_flags(false, vec!["agent-v2".to_string()]);
10543        });
10544
10545        let fs = FakeFs::new(cx.executor());
10546        fs.insert_tree("/zed", json!({ "src": {} })).await;
10547        fs.insert_tree("/foo", json!({ "lib": {} })).await;
10548
10549        let project = Project::test(fs.clone(), ["/zed".as_ref(), "/foo".as_ref()], cx).await;
10550        let multi_workspace_handle =
10551            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
10552        cx.run_until_parked();
10553
10554        let original_workspace = multi_workspace_handle
10555            .read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone())
10556            .unwrap();
10557        let original_workspace_id = original_workspace.entity_id();
10558
10559        let open_task = multi_workspace_handle
10560            .update(cx, |multi_workspace, window, cx| {
10561                let workspace = multi_workspace.workspace().clone();
10562                workspace.update(cx, |workspace, cx| {
10563                    workspace.open_workspace_for_paths(
10564                        true,
10565                        vec![PathBuf::from("/foo"), PathBuf::from("/zed")],
10566                        window,
10567                        cx,
10568                    )
10569                })
10570            })
10571            .unwrap();
10572
10573        let opened_workspace = open_task.await.unwrap();
10574        cx.run_until_parked();
10575
10576        multi_workspace_handle
10577            .read_with(cx, |multi_workspace, _| {
10578                assert_eq!(multi_workspace.workspaces().len(), 1);
10579                assert_eq!(multi_workspace.active_workspace_index(), 0);
10580            })
10581            .unwrap();
10582
10583        assert_eq!(opened_workspace.entity_id(), original_workspace_id);
10584    }
10585
10586    #[gpui::test]
10587    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10588        init_test(cx);
10589
10590        // Register TestItem as a serializable item
10591        cx.update(|cx| {
10592            register_serializable_item::<TestItem>(cx);
10593        });
10594
10595        let fs = FakeFs::new(cx.executor());
10596        fs.insert_tree("/root", json!({ "one": "" })).await;
10597
10598        let project = Project::test(fs, ["root".as_ref()], cx).await;
10599        let (workspace, cx) =
10600            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10601
10602        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10603        let item1 = cx.new(|cx| {
10604            TestItem::new(cx)
10605                .with_dirty(true)
10606                .with_serialize(|| Some(Task::ready(Ok(()))))
10607        });
10608        let item2 = cx.new(|cx| {
10609            TestItem::new(cx)
10610                .with_dirty(true)
10611                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10612                .with_serialize(|| Some(Task::ready(Ok(()))))
10613        });
10614        workspace.update_in(cx, |w, window, cx| {
10615            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10616            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10617        });
10618        let task = workspace.update_in(cx, |w, window, cx| {
10619            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10620        });
10621        assert!(task.await.unwrap());
10622    }
10623
10624    #[gpui::test]
10625    async fn test_close_pane_items(cx: &mut TestAppContext) {
10626        init_test(cx);
10627
10628        let fs = FakeFs::new(cx.executor());
10629
10630        let project = Project::test(fs, None, cx).await;
10631        let (workspace, cx) =
10632            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10633
10634        let item1 = cx.new(|cx| {
10635            TestItem::new(cx)
10636                .with_dirty(true)
10637                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10638        });
10639        let item2 = cx.new(|cx| {
10640            TestItem::new(cx)
10641                .with_dirty(true)
10642                .with_conflict(true)
10643                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10644        });
10645        let item3 = cx.new(|cx| {
10646            TestItem::new(cx)
10647                .with_dirty(true)
10648                .with_conflict(true)
10649                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10650        });
10651        let item4 = cx.new(|cx| {
10652            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10653                let project_item = TestProjectItem::new_untitled(cx);
10654                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10655                project_item
10656            }])
10657        });
10658        let pane = workspace.update_in(cx, |workspace, window, cx| {
10659            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10660            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10661            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10662            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10663            workspace.active_pane().clone()
10664        });
10665
10666        let close_items = pane.update_in(cx, |pane, window, cx| {
10667            pane.activate_item(1, true, true, window, cx);
10668            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10669            let item1_id = item1.item_id();
10670            let item3_id = item3.item_id();
10671            let item4_id = item4.item_id();
10672            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10673                [item1_id, item3_id, item4_id].contains(&id)
10674            })
10675        });
10676        cx.executor().run_until_parked();
10677
10678        assert!(cx.has_pending_prompt());
10679        cx.simulate_prompt_answer("Save all");
10680
10681        cx.executor().run_until_parked();
10682
10683        // Item 1 is saved. There's a prompt to save item 3.
10684        pane.update(cx, |pane, cx| {
10685            assert_eq!(item1.read(cx).save_count, 1);
10686            assert_eq!(item1.read(cx).save_as_count, 0);
10687            assert_eq!(item1.read(cx).reload_count, 0);
10688            assert_eq!(pane.items_len(), 3);
10689            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10690        });
10691        assert!(cx.has_pending_prompt());
10692
10693        // Cancel saving item 3.
10694        cx.simulate_prompt_answer("Discard");
10695        cx.executor().run_until_parked();
10696
10697        // Item 3 is reloaded. There's a prompt to save item 4.
10698        pane.update(cx, |pane, cx| {
10699            assert_eq!(item3.read(cx).save_count, 0);
10700            assert_eq!(item3.read(cx).save_as_count, 0);
10701            assert_eq!(item3.read(cx).reload_count, 1);
10702            assert_eq!(pane.items_len(), 2);
10703            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10704        });
10705
10706        // There's a prompt for a path for item 4.
10707        cx.simulate_new_path_selection(|_| Some(Default::default()));
10708        close_items.await.unwrap();
10709
10710        // The requested items are closed.
10711        pane.update(cx, |pane, cx| {
10712            assert_eq!(item4.read(cx).save_count, 0);
10713            assert_eq!(item4.read(cx).save_as_count, 1);
10714            assert_eq!(item4.read(cx).reload_count, 0);
10715            assert_eq!(pane.items_len(), 1);
10716            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10717        });
10718    }
10719
10720    #[gpui::test]
10721    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10722        init_test(cx);
10723
10724        let fs = FakeFs::new(cx.executor());
10725        let project = Project::test(fs, [], cx).await;
10726        let (workspace, cx) =
10727            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10728
10729        // Create several workspace items with single project entries, and two
10730        // workspace items with multiple project entries.
10731        let single_entry_items = (0..=4)
10732            .map(|project_entry_id| {
10733                cx.new(|cx| {
10734                    TestItem::new(cx)
10735                        .with_dirty(true)
10736                        .with_project_items(&[dirty_project_item(
10737                            project_entry_id,
10738                            &format!("{project_entry_id}.txt"),
10739                            cx,
10740                        )])
10741                })
10742            })
10743            .collect::<Vec<_>>();
10744        let item_2_3 = cx.new(|cx| {
10745            TestItem::new(cx)
10746                .with_dirty(true)
10747                .with_buffer_kind(ItemBufferKind::Multibuffer)
10748                .with_project_items(&[
10749                    single_entry_items[2].read(cx).project_items[0].clone(),
10750                    single_entry_items[3].read(cx).project_items[0].clone(),
10751                ])
10752        });
10753        let item_3_4 = cx.new(|cx| {
10754            TestItem::new(cx)
10755                .with_dirty(true)
10756                .with_buffer_kind(ItemBufferKind::Multibuffer)
10757                .with_project_items(&[
10758                    single_entry_items[3].read(cx).project_items[0].clone(),
10759                    single_entry_items[4].read(cx).project_items[0].clone(),
10760                ])
10761        });
10762
10763        // Create two panes that contain the following project entries:
10764        //   left pane:
10765        //     multi-entry items:   (2, 3)
10766        //     single-entry items:  0, 2, 3, 4
10767        //   right pane:
10768        //     single-entry items:  4, 1
10769        //     multi-entry items:   (3, 4)
10770        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10771            let left_pane = workspace.active_pane().clone();
10772            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10773            workspace.add_item_to_active_pane(
10774                single_entry_items[0].boxed_clone(),
10775                None,
10776                true,
10777                window,
10778                cx,
10779            );
10780            workspace.add_item_to_active_pane(
10781                single_entry_items[2].boxed_clone(),
10782                None,
10783                true,
10784                window,
10785                cx,
10786            );
10787            workspace.add_item_to_active_pane(
10788                single_entry_items[3].boxed_clone(),
10789                None,
10790                true,
10791                window,
10792                cx,
10793            );
10794            workspace.add_item_to_active_pane(
10795                single_entry_items[4].boxed_clone(),
10796                None,
10797                true,
10798                window,
10799                cx,
10800            );
10801
10802            let right_pane =
10803                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10804
10805            let boxed_clone = single_entry_items[1].boxed_clone();
10806            let right_pane = window.spawn(cx, async move |cx| {
10807                right_pane.await.inspect(|right_pane| {
10808                    right_pane
10809                        .update_in(cx, |pane, window, cx| {
10810                            pane.add_item(boxed_clone, true, true, None, window, cx);
10811                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10812                        })
10813                        .unwrap();
10814                })
10815            });
10816
10817            (left_pane, right_pane)
10818        });
10819        let right_pane = right_pane.await.unwrap();
10820        cx.focus(&right_pane);
10821
10822        let close = right_pane.update_in(cx, |pane, window, cx| {
10823            pane.close_all_items(&CloseAllItems::default(), window, cx)
10824                .unwrap()
10825        });
10826        cx.executor().run_until_parked();
10827
10828        let msg = cx.pending_prompt().unwrap().0;
10829        assert!(msg.contains("1.txt"));
10830        assert!(!msg.contains("2.txt"));
10831        assert!(!msg.contains("3.txt"));
10832        assert!(!msg.contains("4.txt"));
10833
10834        // With best-effort close, cancelling item 1 keeps it open but items 4
10835        // and (3,4) still close since their entries exist in left pane.
10836        cx.simulate_prompt_answer("Cancel");
10837        close.await;
10838
10839        right_pane.read_with(cx, |pane, _| {
10840            assert_eq!(pane.items_len(), 1);
10841        });
10842
10843        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10844        left_pane
10845            .update_in(cx, |left_pane, window, cx| {
10846                left_pane.close_item_by_id(
10847                    single_entry_items[3].entity_id(),
10848                    SaveIntent::Skip,
10849                    window,
10850                    cx,
10851                )
10852            })
10853            .await
10854            .unwrap();
10855
10856        let close = left_pane.update_in(cx, |pane, window, cx| {
10857            pane.close_all_items(&CloseAllItems::default(), window, cx)
10858                .unwrap()
10859        });
10860        cx.executor().run_until_parked();
10861
10862        let details = cx.pending_prompt().unwrap().1;
10863        assert!(details.contains("0.txt"));
10864        assert!(details.contains("3.txt"));
10865        assert!(details.contains("4.txt"));
10866        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10867        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10868        // assert!(!details.contains("2.txt"));
10869
10870        cx.simulate_prompt_answer("Save all");
10871        cx.executor().run_until_parked();
10872        close.await;
10873
10874        left_pane.read_with(cx, |pane, _| {
10875            assert_eq!(pane.items_len(), 0);
10876        });
10877    }
10878
10879    #[gpui::test]
10880    async fn test_autosave(cx: &mut gpui::TestAppContext) {
10881        init_test(cx);
10882
10883        let fs = FakeFs::new(cx.executor());
10884        let project = Project::test(fs, [], cx).await;
10885        let (workspace, cx) =
10886            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10887        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10888
10889        let item = cx.new(|cx| {
10890            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10891        });
10892        let item_id = item.entity_id();
10893        workspace.update_in(cx, |workspace, window, cx| {
10894            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10895        });
10896
10897        // Autosave on window change.
10898        item.update(cx, |item, cx| {
10899            SettingsStore::update_global(cx, |settings, cx| {
10900                settings.update_user_settings(cx, |settings| {
10901                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10902                })
10903            });
10904            item.is_dirty = true;
10905        });
10906
10907        // Deactivating the window saves the file.
10908        cx.deactivate_window();
10909        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10910
10911        // Re-activating the window doesn't save the file.
10912        cx.update(|window, _| window.activate_window());
10913        cx.executor().run_until_parked();
10914        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10915
10916        // Autosave on focus change.
10917        item.update_in(cx, |item, window, cx| {
10918            cx.focus_self(window);
10919            SettingsStore::update_global(cx, |settings, cx| {
10920                settings.update_user_settings(cx, |settings| {
10921                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10922                })
10923            });
10924            item.is_dirty = true;
10925        });
10926        // Blurring the item saves the file.
10927        item.update_in(cx, |_, window, _| window.blur());
10928        cx.executor().run_until_parked();
10929        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10930
10931        // Deactivating the window still saves the file.
10932        item.update_in(cx, |item, window, cx| {
10933            cx.focus_self(window);
10934            item.is_dirty = true;
10935        });
10936        cx.deactivate_window();
10937        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10938
10939        // Autosave after delay.
10940        item.update(cx, |item, cx| {
10941            SettingsStore::update_global(cx, |settings, cx| {
10942                settings.update_user_settings(cx, |settings| {
10943                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10944                        milliseconds: 500.into(),
10945                    });
10946                })
10947            });
10948            item.is_dirty = true;
10949            cx.emit(ItemEvent::Edit);
10950        });
10951
10952        // Delay hasn't fully expired, so the file is still dirty and unsaved.
10953        cx.executor().advance_clock(Duration::from_millis(250));
10954        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10955
10956        // After delay expires, the file is saved.
10957        cx.executor().advance_clock(Duration::from_millis(250));
10958        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10959
10960        // Autosave after delay, should save earlier than delay if tab is closed
10961        item.update(cx, |item, cx| {
10962            item.is_dirty = true;
10963            cx.emit(ItemEvent::Edit);
10964        });
10965        cx.executor().advance_clock(Duration::from_millis(250));
10966        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10967
10968        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10969        pane.update_in(cx, |pane, window, cx| {
10970            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10971        })
10972        .await
10973        .unwrap();
10974        assert!(!cx.has_pending_prompt());
10975        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10976
10977        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10978        workspace.update_in(cx, |workspace, window, cx| {
10979            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10980        });
10981        item.update_in(cx, |item, _window, cx| {
10982            item.is_dirty = true;
10983            for project_item in &mut item.project_items {
10984                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10985            }
10986        });
10987        cx.run_until_parked();
10988        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10989
10990        // Autosave on focus change, ensuring closing the tab counts as such.
10991        item.update(cx, |item, cx| {
10992            SettingsStore::update_global(cx, |settings, cx| {
10993                settings.update_user_settings(cx, |settings| {
10994                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10995                })
10996            });
10997            item.is_dirty = true;
10998            for project_item in &mut item.project_items {
10999                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11000            }
11001        });
11002
11003        pane.update_in(cx, |pane, window, cx| {
11004            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11005        })
11006        .await
11007        .unwrap();
11008        assert!(!cx.has_pending_prompt());
11009        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11010
11011        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11012        workspace.update_in(cx, |workspace, window, cx| {
11013            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11014        });
11015        item.update_in(cx, |item, window, cx| {
11016            item.project_items[0].update(cx, |item, _| {
11017                item.entry_id = None;
11018            });
11019            item.is_dirty = true;
11020            window.blur();
11021        });
11022        cx.run_until_parked();
11023        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11024
11025        // Ensure autosave is prevented for deleted files also when closing the buffer.
11026        let _close_items = pane.update_in(cx, |pane, window, cx| {
11027            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11028        });
11029        cx.run_until_parked();
11030        assert!(cx.has_pending_prompt());
11031        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11032    }
11033
11034    #[gpui::test]
11035    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11036        init_test(cx);
11037
11038        let fs = FakeFs::new(cx.executor());
11039        let project = Project::test(fs, [], cx).await;
11040        let (workspace, cx) =
11041            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11042
11043        // Create a multibuffer-like item with two child focus handles,
11044        // simulating individual buffer editors within a multibuffer.
11045        let item = cx.new(|cx| {
11046            TestItem::new(cx)
11047                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11048                .with_child_focus_handles(2, cx)
11049        });
11050        workspace.update_in(cx, |workspace, window, cx| {
11051            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11052        });
11053
11054        // Set autosave to OnFocusChange and focus the first child handle,
11055        // simulating the user's cursor being inside one of the multibuffer's excerpts.
11056        item.update_in(cx, |item, window, cx| {
11057            SettingsStore::update_global(cx, |settings, cx| {
11058                settings.update_user_settings(cx, |settings| {
11059                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11060                })
11061            });
11062            item.is_dirty = true;
11063            window.focus(&item.child_focus_handles[0], cx);
11064        });
11065        cx.executor().run_until_parked();
11066        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11067
11068        // Moving focus from one child to another within the same item should
11069        // NOT trigger autosave — focus is still within the item's focus hierarchy.
11070        item.update_in(cx, |item, window, cx| {
11071            window.focus(&item.child_focus_handles[1], cx);
11072        });
11073        cx.executor().run_until_parked();
11074        item.read_with(cx, |item, _| {
11075            assert_eq!(
11076                item.save_count, 0,
11077                "Switching focus between children within the same item should not autosave"
11078            );
11079        });
11080
11081        // Blurring the item saves the file. This is the core regression scenario:
11082        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11083        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11084        // the leaf is always a child focus handle, so `on_blur` never detected
11085        // focus leaving the item.
11086        item.update_in(cx, |_, window, _| window.blur());
11087        cx.executor().run_until_parked();
11088        item.read_with(cx, |item, _| {
11089            assert_eq!(
11090                item.save_count, 1,
11091                "Blurring should trigger autosave when focus was on a child of the item"
11092            );
11093        });
11094
11095        // Deactivating the window should also trigger autosave when a child of
11096        // the multibuffer item currently owns focus.
11097        item.update_in(cx, |item, window, cx| {
11098            item.is_dirty = true;
11099            window.focus(&item.child_focus_handles[0], cx);
11100        });
11101        cx.executor().run_until_parked();
11102        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11103
11104        cx.deactivate_window();
11105        item.read_with(cx, |item, _| {
11106            assert_eq!(
11107                item.save_count, 2,
11108                "Deactivating window should trigger autosave when focus was on a child"
11109            );
11110        });
11111    }
11112
11113    #[gpui::test]
11114    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11115        init_test(cx);
11116
11117        let fs = FakeFs::new(cx.executor());
11118
11119        let project = Project::test(fs, [], cx).await;
11120        let (workspace, cx) =
11121            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11122
11123        let item = cx.new(|cx| {
11124            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11125        });
11126        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11127        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11128        let toolbar_notify_count = Rc::new(RefCell::new(0));
11129
11130        workspace.update_in(cx, |workspace, window, cx| {
11131            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11132            let toolbar_notification_count = toolbar_notify_count.clone();
11133            cx.observe_in(&toolbar, window, move |_, _, _, _| {
11134                *toolbar_notification_count.borrow_mut() += 1
11135            })
11136            .detach();
11137        });
11138
11139        pane.read_with(cx, |pane, _| {
11140            assert!(!pane.can_navigate_backward());
11141            assert!(!pane.can_navigate_forward());
11142        });
11143
11144        item.update_in(cx, |item, _, cx| {
11145            item.set_state("one".to_string(), cx);
11146        });
11147
11148        // Toolbar must be notified to re-render the navigation buttons
11149        assert_eq!(*toolbar_notify_count.borrow(), 1);
11150
11151        pane.read_with(cx, |pane, _| {
11152            assert!(pane.can_navigate_backward());
11153            assert!(!pane.can_navigate_forward());
11154        });
11155
11156        workspace
11157            .update_in(cx, |workspace, window, cx| {
11158                workspace.go_back(pane.downgrade(), window, cx)
11159            })
11160            .await
11161            .unwrap();
11162
11163        assert_eq!(*toolbar_notify_count.borrow(), 2);
11164        pane.read_with(cx, |pane, _| {
11165            assert!(!pane.can_navigate_backward());
11166            assert!(pane.can_navigate_forward());
11167        });
11168    }
11169
11170    #[gpui::test]
11171    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11172        init_test(cx);
11173        let fs = FakeFs::new(cx.executor());
11174        let project = Project::test(fs, [], cx).await;
11175        let (multi_workspace, cx) =
11176            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11177        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11178
11179        workspace.update_in(cx, |workspace, window, cx| {
11180            let first_item = cx.new(|cx| {
11181                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11182            });
11183            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11184            workspace.split_pane(
11185                workspace.active_pane().clone(),
11186                SplitDirection::Right,
11187                window,
11188                cx,
11189            );
11190            workspace.split_pane(
11191                workspace.active_pane().clone(),
11192                SplitDirection::Right,
11193                window,
11194                cx,
11195            );
11196        });
11197
11198        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11199            let panes = workspace.center.panes();
11200            assert!(panes.len() >= 2);
11201            (
11202                panes.first().expect("at least one pane").entity_id(),
11203                panes.last().expect("at least one pane").entity_id(),
11204            )
11205        });
11206
11207        workspace.update_in(cx, |workspace, window, cx| {
11208            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11209        });
11210        workspace.update(cx, |workspace, _| {
11211            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11212            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11213        });
11214
11215        cx.dispatch_action(ActivateLastPane);
11216
11217        workspace.update(cx, |workspace, _| {
11218            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11219        });
11220    }
11221
11222    #[gpui::test]
11223    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11224        init_test(cx);
11225        let fs = FakeFs::new(cx.executor());
11226
11227        let project = Project::test(fs, [], cx).await;
11228        let (workspace, cx) =
11229            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11230
11231        let panel = workspace.update_in(cx, |workspace, window, cx| {
11232            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11233            workspace.add_panel(panel.clone(), window, cx);
11234
11235            workspace
11236                .right_dock()
11237                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11238
11239            panel
11240        });
11241
11242        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11243        pane.update_in(cx, |pane, window, cx| {
11244            let item = cx.new(TestItem::new);
11245            pane.add_item(Box::new(item), true, true, None, window, cx);
11246        });
11247
11248        // Transfer focus from center to panel
11249        workspace.update_in(cx, |workspace, window, cx| {
11250            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11251        });
11252
11253        workspace.update_in(cx, |workspace, window, cx| {
11254            assert!(workspace.right_dock().read(cx).is_open());
11255            assert!(!panel.is_zoomed(window, cx));
11256            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11257        });
11258
11259        // Transfer focus from panel to center
11260        workspace.update_in(cx, |workspace, window, cx| {
11261            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11262        });
11263
11264        workspace.update_in(cx, |workspace, window, cx| {
11265            assert!(workspace.right_dock().read(cx).is_open());
11266            assert!(!panel.is_zoomed(window, cx));
11267            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11268        });
11269
11270        // Close the dock
11271        workspace.update_in(cx, |workspace, window, cx| {
11272            workspace.toggle_dock(DockPosition::Right, window, cx);
11273        });
11274
11275        workspace.update_in(cx, |workspace, window, cx| {
11276            assert!(!workspace.right_dock().read(cx).is_open());
11277            assert!(!panel.is_zoomed(window, cx));
11278            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11279        });
11280
11281        // Open the dock
11282        workspace.update_in(cx, |workspace, window, cx| {
11283            workspace.toggle_dock(DockPosition::Right, window, cx);
11284        });
11285
11286        workspace.update_in(cx, |workspace, window, cx| {
11287            assert!(workspace.right_dock().read(cx).is_open());
11288            assert!(!panel.is_zoomed(window, cx));
11289            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11290        });
11291
11292        // Focus and zoom panel
11293        panel.update_in(cx, |panel, window, cx| {
11294            cx.focus_self(window);
11295            panel.set_zoomed(true, window, cx)
11296        });
11297
11298        workspace.update_in(cx, |workspace, window, cx| {
11299            assert!(workspace.right_dock().read(cx).is_open());
11300            assert!(panel.is_zoomed(window, cx));
11301            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11302        });
11303
11304        // Transfer focus to the center closes the dock
11305        workspace.update_in(cx, |workspace, window, cx| {
11306            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11307        });
11308
11309        workspace.update_in(cx, |workspace, window, cx| {
11310            assert!(!workspace.right_dock().read(cx).is_open());
11311            assert!(panel.is_zoomed(window, cx));
11312            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11313        });
11314
11315        // Transferring focus back to the panel keeps it zoomed
11316        workspace.update_in(cx, |workspace, window, cx| {
11317            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11318        });
11319
11320        workspace.update_in(cx, |workspace, window, cx| {
11321            assert!(workspace.right_dock().read(cx).is_open());
11322            assert!(panel.is_zoomed(window, cx));
11323            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11324        });
11325
11326        // Close the dock while it is zoomed
11327        workspace.update_in(cx, |workspace, window, cx| {
11328            workspace.toggle_dock(DockPosition::Right, window, cx)
11329        });
11330
11331        workspace.update_in(cx, |workspace, window, cx| {
11332            assert!(!workspace.right_dock().read(cx).is_open());
11333            assert!(panel.is_zoomed(window, cx));
11334            assert!(workspace.zoomed.is_none());
11335            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11336        });
11337
11338        // Opening the dock, when it's zoomed, retains focus
11339        workspace.update_in(cx, |workspace, window, cx| {
11340            workspace.toggle_dock(DockPosition::Right, window, cx)
11341        });
11342
11343        workspace.update_in(cx, |workspace, window, cx| {
11344            assert!(workspace.right_dock().read(cx).is_open());
11345            assert!(panel.is_zoomed(window, cx));
11346            assert!(workspace.zoomed.is_some());
11347            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11348        });
11349
11350        // Unzoom and close the panel, zoom the active pane.
11351        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11352        workspace.update_in(cx, |workspace, window, cx| {
11353            workspace.toggle_dock(DockPosition::Right, window, cx)
11354        });
11355        pane.update_in(cx, |pane, window, cx| {
11356            pane.toggle_zoom(&Default::default(), window, cx)
11357        });
11358
11359        // Opening a dock unzooms the pane.
11360        workspace.update_in(cx, |workspace, window, cx| {
11361            workspace.toggle_dock(DockPosition::Right, window, cx)
11362        });
11363        workspace.update_in(cx, |workspace, window, cx| {
11364            let pane = pane.read(cx);
11365            assert!(!pane.is_zoomed());
11366            assert!(!pane.focus_handle(cx).is_focused(window));
11367            assert!(workspace.right_dock().read(cx).is_open());
11368            assert!(workspace.zoomed.is_none());
11369        });
11370    }
11371
11372    #[gpui::test]
11373    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11374        init_test(cx);
11375        let fs = FakeFs::new(cx.executor());
11376
11377        let project = Project::test(fs, [], cx).await;
11378        let (workspace, cx) =
11379            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11380
11381        let panel = workspace.update_in(cx, |workspace, window, cx| {
11382            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11383            workspace.add_panel(panel.clone(), window, cx);
11384            panel
11385        });
11386
11387        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11388        pane.update_in(cx, |pane, window, cx| {
11389            let item = cx.new(TestItem::new);
11390            pane.add_item(Box::new(item), true, true, None, window, cx);
11391        });
11392
11393        // Enable close_panel_on_toggle
11394        cx.update_global(|store: &mut SettingsStore, cx| {
11395            store.update_user_settings(cx, |settings| {
11396                settings.workspace.close_panel_on_toggle = Some(true);
11397            });
11398        });
11399
11400        // Panel starts closed. Toggling should open and focus it.
11401        workspace.update_in(cx, |workspace, window, cx| {
11402            assert!(!workspace.right_dock().read(cx).is_open());
11403            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11404        });
11405
11406        workspace.update_in(cx, |workspace, window, cx| {
11407            assert!(
11408                workspace.right_dock().read(cx).is_open(),
11409                "Dock should be open after toggling from center"
11410            );
11411            assert!(
11412                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11413                "Panel should be focused after toggling from center"
11414            );
11415        });
11416
11417        // Panel is open and focused. Toggling should close the panel and
11418        // return focus to the center.
11419        workspace.update_in(cx, |workspace, window, cx| {
11420            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11421        });
11422
11423        workspace.update_in(cx, |workspace, window, cx| {
11424            assert!(
11425                !workspace.right_dock().read(cx).is_open(),
11426                "Dock should be closed after toggling from focused panel"
11427            );
11428            assert!(
11429                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11430                "Panel should not be focused after toggling from focused panel"
11431            );
11432        });
11433
11434        // Open the dock and focus something else so the panel is open but not
11435        // focused. Toggling should focus the panel (not close it).
11436        workspace.update_in(cx, |workspace, window, cx| {
11437            workspace
11438                .right_dock()
11439                .update(cx, |dock, cx| dock.set_open(true, window, cx));
11440            window.focus(&pane.read(cx).focus_handle(cx), cx);
11441        });
11442
11443        workspace.update_in(cx, |workspace, window, cx| {
11444            assert!(workspace.right_dock().read(cx).is_open());
11445            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11446            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11447        });
11448
11449        workspace.update_in(cx, |workspace, window, cx| {
11450            assert!(
11451                workspace.right_dock().read(cx).is_open(),
11452                "Dock should remain open when toggling focuses an open-but-unfocused panel"
11453            );
11454            assert!(
11455                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11456                "Panel should be focused after toggling an open-but-unfocused panel"
11457            );
11458        });
11459
11460        // Now disable the setting and verify the original behavior: toggling
11461        // from a focused panel moves focus to center but leaves the dock open.
11462        cx.update_global(|store: &mut SettingsStore, cx| {
11463            store.update_user_settings(cx, |settings| {
11464                settings.workspace.close_panel_on_toggle = Some(false);
11465            });
11466        });
11467
11468        workspace.update_in(cx, |workspace, window, cx| {
11469            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11470        });
11471
11472        workspace.update_in(cx, |workspace, window, cx| {
11473            assert!(
11474                workspace.right_dock().read(cx).is_open(),
11475                "Dock should remain open when setting is disabled"
11476            );
11477            assert!(
11478                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11479                "Panel should not be focused after toggling with setting disabled"
11480            );
11481        });
11482    }
11483
11484    #[gpui::test]
11485    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11486        init_test(cx);
11487        let fs = FakeFs::new(cx.executor());
11488
11489        let project = Project::test(fs, [], cx).await;
11490        let (workspace, cx) =
11491            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11492
11493        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11494            workspace.active_pane().clone()
11495        });
11496
11497        // Add an item to the pane so it can be zoomed
11498        workspace.update_in(cx, |workspace, window, cx| {
11499            let item = cx.new(TestItem::new);
11500            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11501        });
11502
11503        // Initially not zoomed
11504        workspace.update_in(cx, |workspace, _window, cx| {
11505            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11506            assert!(
11507                workspace.zoomed.is_none(),
11508                "Workspace should track no zoomed pane"
11509            );
11510            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11511        });
11512
11513        // Zoom In
11514        pane.update_in(cx, |pane, window, cx| {
11515            pane.zoom_in(&crate::ZoomIn, window, cx);
11516        });
11517
11518        workspace.update_in(cx, |workspace, window, cx| {
11519            assert!(
11520                pane.read(cx).is_zoomed(),
11521                "Pane should be zoomed after ZoomIn"
11522            );
11523            assert!(
11524                workspace.zoomed.is_some(),
11525                "Workspace should track the zoomed pane"
11526            );
11527            assert!(
11528                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11529                "ZoomIn should focus the pane"
11530            );
11531        });
11532
11533        // Zoom In again is a no-op
11534        pane.update_in(cx, |pane, window, cx| {
11535            pane.zoom_in(&crate::ZoomIn, window, cx);
11536        });
11537
11538        workspace.update_in(cx, |workspace, window, cx| {
11539            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11540            assert!(
11541                workspace.zoomed.is_some(),
11542                "Workspace still tracks zoomed pane"
11543            );
11544            assert!(
11545                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11546                "Pane remains focused after repeated ZoomIn"
11547            );
11548        });
11549
11550        // Zoom Out
11551        pane.update_in(cx, |pane, window, cx| {
11552            pane.zoom_out(&crate::ZoomOut, window, cx);
11553        });
11554
11555        workspace.update_in(cx, |workspace, _window, cx| {
11556            assert!(
11557                !pane.read(cx).is_zoomed(),
11558                "Pane should unzoom after ZoomOut"
11559            );
11560            assert!(
11561                workspace.zoomed.is_none(),
11562                "Workspace clears zoom tracking after ZoomOut"
11563            );
11564        });
11565
11566        // Zoom Out again is a no-op
11567        pane.update_in(cx, |pane, window, cx| {
11568            pane.zoom_out(&crate::ZoomOut, window, cx);
11569        });
11570
11571        workspace.update_in(cx, |workspace, _window, cx| {
11572            assert!(
11573                !pane.read(cx).is_zoomed(),
11574                "Second ZoomOut keeps pane unzoomed"
11575            );
11576            assert!(
11577                workspace.zoomed.is_none(),
11578                "Workspace remains without zoomed pane"
11579            );
11580        });
11581    }
11582
11583    #[gpui::test]
11584    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11585        init_test(cx);
11586        let fs = FakeFs::new(cx.executor());
11587
11588        let project = Project::test(fs, [], cx).await;
11589        let (workspace, cx) =
11590            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11591        workspace.update_in(cx, |workspace, window, cx| {
11592            // Open two docks
11593            let left_dock = workspace.dock_at_position(DockPosition::Left);
11594            let right_dock = workspace.dock_at_position(DockPosition::Right);
11595
11596            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11597            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11598
11599            assert!(left_dock.read(cx).is_open());
11600            assert!(right_dock.read(cx).is_open());
11601        });
11602
11603        workspace.update_in(cx, |workspace, window, cx| {
11604            // Toggle all docks - should close both
11605            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11606
11607            let left_dock = workspace.dock_at_position(DockPosition::Left);
11608            let right_dock = workspace.dock_at_position(DockPosition::Right);
11609            assert!(!left_dock.read(cx).is_open());
11610            assert!(!right_dock.read(cx).is_open());
11611        });
11612
11613        workspace.update_in(cx, |workspace, window, cx| {
11614            // Toggle again - should reopen both
11615            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11616
11617            let left_dock = workspace.dock_at_position(DockPosition::Left);
11618            let right_dock = workspace.dock_at_position(DockPosition::Right);
11619            assert!(left_dock.read(cx).is_open());
11620            assert!(right_dock.read(cx).is_open());
11621        });
11622    }
11623
11624    #[gpui::test]
11625    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11626        init_test(cx);
11627        let fs = FakeFs::new(cx.executor());
11628
11629        let project = Project::test(fs, [], cx).await;
11630        let (workspace, cx) =
11631            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11632        workspace.update_in(cx, |workspace, window, cx| {
11633            // Open two docks
11634            let left_dock = workspace.dock_at_position(DockPosition::Left);
11635            let right_dock = workspace.dock_at_position(DockPosition::Right);
11636
11637            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11638            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11639
11640            assert!(left_dock.read(cx).is_open());
11641            assert!(right_dock.read(cx).is_open());
11642        });
11643
11644        workspace.update_in(cx, |workspace, window, cx| {
11645            // Close them manually
11646            workspace.toggle_dock(DockPosition::Left, window, cx);
11647            workspace.toggle_dock(DockPosition::Right, window, cx);
11648
11649            let left_dock = workspace.dock_at_position(DockPosition::Left);
11650            let right_dock = workspace.dock_at_position(DockPosition::Right);
11651            assert!(!left_dock.read(cx).is_open());
11652            assert!(!right_dock.read(cx).is_open());
11653        });
11654
11655        workspace.update_in(cx, |workspace, window, cx| {
11656            // Toggle all docks - only last closed (right dock) should reopen
11657            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11658
11659            let left_dock = workspace.dock_at_position(DockPosition::Left);
11660            let right_dock = workspace.dock_at_position(DockPosition::Right);
11661            assert!(!left_dock.read(cx).is_open());
11662            assert!(right_dock.read(cx).is_open());
11663        });
11664    }
11665
11666    #[gpui::test]
11667    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11668        init_test(cx);
11669        let fs = FakeFs::new(cx.executor());
11670        let project = Project::test(fs, [], cx).await;
11671        let (multi_workspace, cx) =
11672            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11673        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11674
11675        // Open two docks (left and right) with one panel each
11676        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11677            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11678            workspace.add_panel(left_panel.clone(), window, cx);
11679
11680            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11681            workspace.add_panel(right_panel.clone(), window, cx);
11682
11683            workspace.toggle_dock(DockPosition::Left, window, cx);
11684            workspace.toggle_dock(DockPosition::Right, window, cx);
11685
11686            // Verify initial state
11687            assert!(
11688                workspace.left_dock().read(cx).is_open(),
11689                "Left dock should be open"
11690            );
11691            assert_eq!(
11692                workspace
11693                    .left_dock()
11694                    .read(cx)
11695                    .visible_panel()
11696                    .unwrap()
11697                    .panel_id(),
11698                left_panel.panel_id(),
11699                "Left panel should be visible in left dock"
11700            );
11701            assert!(
11702                workspace.right_dock().read(cx).is_open(),
11703                "Right dock should be open"
11704            );
11705            assert_eq!(
11706                workspace
11707                    .right_dock()
11708                    .read(cx)
11709                    .visible_panel()
11710                    .unwrap()
11711                    .panel_id(),
11712                right_panel.panel_id(),
11713                "Right panel should be visible in right dock"
11714            );
11715            assert!(
11716                !workspace.bottom_dock().read(cx).is_open(),
11717                "Bottom dock should be closed"
11718            );
11719
11720            (left_panel, right_panel)
11721        });
11722
11723        // Focus the left panel and move it to the next position (bottom dock)
11724        workspace.update_in(cx, |workspace, window, cx| {
11725            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11726            assert!(
11727                left_panel.read(cx).focus_handle(cx).is_focused(window),
11728                "Left panel should be focused"
11729            );
11730        });
11731
11732        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11733
11734        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11735        workspace.update(cx, |workspace, cx| {
11736            assert!(
11737                !workspace.left_dock().read(cx).is_open(),
11738                "Left dock should be closed"
11739            );
11740            assert!(
11741                workspace.bottom_dock().read(cx).is_open(),
11742                "Bottom dock should now be open"
11743            );
11744            assert_eq!(
11745                left_panel.read(cx).position,
11746                DockPosition::Bottom,
11747                "Left panel should now be in the bottom dock"
11748            );
11749            assert_eq!(
11750                workspace
11751                    .bottom_dock()
11752                    .read(cx)
11753                    .visible_panel()
11754                    .unwrap()
11755                    .panel_id(),
11756                left_panel.panel_id(),
11757                "Left panel should be the visible panel in the bottom dock"
11758            );
11759        });
11760
11761        // Toggle all docks off
11762        workspace.update_in(cx, |workspace, window, cx| {
11763            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11764            assert!(
11765                !workspace.left_dock().read(cx).is_open(),
11766                "Left dock should be closed"
11767            );
11768            assert!(
11769                !workspace.right_dock().read(cx).is_open(),
11770                "Right dock should be closed"
11771            );
11772            assert!(
11773                !workspace.bottom_dock().read(cx).is_open(),
11774                "Bottom dock should be closed"
11775            );
11776        });
11777
11778        // Toggle all docks back on and verify positions are restored
11779        workspace.update_in(cx, |workspace, window, cx| {
11780            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11781            assert!(
11782                !workspace.left_dock().read(cx).is_open(),
11783                "Left dock should remain closed"
11784            );
11785            assert!(
11786                workspace.right_dock().read(cx).is_open(),
11787                "Right dock should remain open"
11788            );
11789            assert!(
11790                workspace.bottom_dock().read(cx).is_open(),
11791                "Bottom dock should remain open"
11792            );
11793            assert_eq!(
11794                left_panel.read(cx).position,
11795                DockPosition::Bottom,
11796                "Left panel should remain in the bottom dock"
11797            );
11798            assert_eq!(
11799                right_panel.read(cx).position,
11800                DockPosition::Right,
11801                "Right panel should remain in the right dock"
11802            );
11803            assert_eq!(
11804                workspace
11805                    .bottom_dock()
11806                    .read(cx)
11807                    .visible_panel()
11808                    .unwrap()
11809                    .panel_id(),
11810                left_panel.panel_id(),
11811                "Left panel should be the visible panel in the right dock"
11812            );
11813        });
11814    }
11815
11816    #[gpui::test]
11817    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11818        init_test(cx);
11819
11820        let fs = FakeFs::new(cx.executor());
11821
11822        let project = Project::test(fs, None, cx).await;
11823        let (workspace, cx) =
11824            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11825
11826        // Let's arrange the panes like this:
11827        //
11828        // +-----------------------+
11829        // |         top           |
11830        // +------+--------+-------+
11831        // | left | center | right |
11832        // +------+--------+-------+
11833        // |        bottom         |
11834        // +-----------------------+
11835
11836        let top_item = cx.new(|cx| {
11837            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11838        });
11839        let bottom_item = cx.new(|cx| {
11840            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11841        });
11842        let left_item = cx.new(|cx| {
11843            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11844        });
11845        let right_item = cx.new(|cx| {
11846            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11847        });
11848        let center_item = cx.new(|cx| {
11849            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11850        });
11851
11852        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11853            let top_pane_id = workspace.active_pane().entity_id();
11854            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11855            workspace.split_pane(
11856                workspace.active_pane().clone(),
11857                SplitDirection::Down,
11858                window,
11859                cx,
11860            );
11861            top_pane_id
11862        });
11863        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11864            let bottom_pane_id = workspace.active_pane().entity_id();
11865            workspace.add_item_to_active_pane(
11866                Box::new(bottom_item.clone()),
11867                None,
11868                false,
11869                window,
11870                cx,
11871            );
11872            workspace.split_pane(
11873                workspace.active_pane().clone(),
11874                SplitDirection::Up,
11875                window,
11876                cx,
11877            );
11878            bottom_pane_id
11879        });
11880        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11881            let left_pane_id = workspace.active_pane().entity_id();
11882            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11883            workspace.split_pane(
11884                workspace.active_pane().clone(),
11885                SplitDirection::Right,
11886                window,
11887                cx,
11888            );
11889            left_pane_id
11890        });
11891        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11892            let right_pane_id = workspace.active_pane().entity_id();
11893            workspace.add_item_to_active_pane(
11894                Box::new(right_item.clone()),
11895                None,
11896                false,
11897                window,
11898                cx,
11899            );
11900            workspace.split_pane(
11901                workspace.active_pane().clone(),
11902                SplitDirection::Left,
11903                window,
11904                cx,
11905            );
11906            right_pane_id
11907        });
11908        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11909            let center_pane_id = workspace.active_pane().entity_id();
11910            workspace.add_item_to_active_pane(
11911                Box::new(center_item.clone()),
11912                None,
11913                false,
11914                window,
11915                cx,
11916            );
11917            center_pane_id
11918        });
11919        cx.executor().run_until_parked();
11920
11921        workspace.update_in(cx, |workspace, window, cx| {
11922            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11923
11924            // Join into next from center pane into right
11925            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11926        });
11927
11928        workspace.update_in(cx, |workspace, window, cx| {
11929            let active_pane = workspace.active_pane();
11930            assert_eq!(right_pane_id, active_pane.entity_id());
11931            assert_eq!(2, active_pane.read(cx).items_len());
11932            let item_ids_in_pane =
11933                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11934            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11935            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11936
11937            // Join into next from right pane into bottom
11938            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11939        });
11940
11941        workspace.update_in(cx, |workspace, window, cx| {
11942            let active_pane = workspace.active_pane();
11943            assert_eq!(bottom_pane_id, active_pane.entity_id());
11944            assert_eq!(3, active_pane.read(cx).items_len());
11945            let item_ids_in_pane =
11946                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11947            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11948            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11949            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11950
11951            // Join into next from bottom pane into left
11952            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11953        });
11954
11955        workspace.update_in(cx, |workspace, window, cx| {
11956            let active_pane = workspace.active_pane();
11957            assert_eq!(left_pane_id, active_pane.entity_id());
11958            assert_eq!(4, active_pane.read(cx).items_len());
11959            let item_ids_in_pane =
11960                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11961            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11962            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11963            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11964            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11965
11966            // Join into next from left pane into top
11967            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11968        });
11969
11970        workspace.update_in(cx, |workspace, window, cx| {
11971            let active_pane = workspace.active_pane();
11972            assert_eq!(top_pane_id, active_pane.entity_id());
11973            assert_eq!(5, active_pane.read(cx).items_len());
11974            let item_ids_in_pane =
11975                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11976            assert!(item_ids_in_pane.contains(&center_item.item_id()));
11977            assert!(item_ids_in_pane.contains(&right_item.item_id()));
11978            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11979            assert!(item_ids_in_pane.contains(&left_item.item_id()));
11980            assert!(item_ids_in_pane.contains(&top_item.item_id()));
11981
11982            // Single pane left: no-op
11983            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11984        });
11985
11986        workspace.update(cx, |workspace, _cx| {
11987            let active_pane = workspace.active_pane();
11988            assert_eq!(top_pane_id, active_pane.entity_id());
11989        });
11990    }
11991
11992    fn add_an_item_to_active_pane(
11993        cx: &mut VisualTestContext,
11994        workspace: &Entity<Workspace>,
11995        item_id: u64,
11996    ) -> Entity<TestItem> {
11997        let item = cx.new(|cx| {
11998            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11999                item_id,
12000                "item{item_id}.txt",
12001                cx,
12002            )])
12003        });
12004        workspace.update_in(cx, |workspace, window, cx| {
12005            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12006        });
12007        item
12008    }
12009
12010    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12011        workspace.update_in(cx, |workspace, window, cx| {
12012            workspace.split_pane(
12013                workspace.active_pane().clone(),
12014                SplitDirection::Right,
12015                window,
12016                cx,
12017            )
12018        })
12019    }
12020
12021    #[gpui::test]
12022    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12023        init_test(cx);
12024        let fs = FakeFs::new(cx.executor());
12025        let project = Project::test(fs, None, cx).await;
12026        let (workspace, cx) =
12027            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12028
12029        add_an_item_to_active_pane(cx, &workspace, 1);
12030        split_pane(cx, &workspace);
12031        add_an_item_to_active_pane(cx, &workspace, 2);
12032        split_pane(cx, &workspace); // empty pane
12033        split_pane(cx, &workspace);
12034        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12035
12036        cx.executor().run_until_parked();
12037
12038        workspace.update(cx, |workspace, cx| {
12039            let num_panes = workspace.panes().len();
12040            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12041            let active_item = workspace
12042                .active_pane()
12043                .read(cx)
12044                .active_item()
12045                .expect("item is in focus");
12046
12047            assert_eq!(num_panes, 4);
12048            assert_eq!(num_items_in_current_pane, 1);
12049            assert_eq!(active_item.item_id(), last_item.item_id());
12050        });
12051
12052        workspace.update_in(cx, |workspace, window, cx| {
12053            workspace.join_all_panes(window, cx);
12054        });
12055
12056        workspace.update(cx, |workspace, cx| {
12057            let num_panes = workspace.panes().len();
12058            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12059            let active_item = workspace
12060                .active_pane()
12061                .read(cx)
12062                .active_item()
12063                .expect("item is in focus");
12064
12065            assert_eq!(num_panes, 1);
12066            assert_eq!(num_items_in_current_pane, 3);
12067            assert_eq!(active_item.item_id(), last_item.item_id());
12068        });
12069    }
12070    struct TestModal(FocusHandle);
12071
12072    impl TestModal {
12073        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12074            Self(cx.focus_handle())
12075        }
12076    }
12077
12078    impl EventEmitter<DismissEvent> for TestModal {}
12079
12080    impl Focusable for TestModal {
12081        fn focus_handle(&self, _cx: &App) -> FocusHandle {
12082            self.0.clone()
12083        }
12084    }
12085
12086    impl ModalView for TestModal {}
12087
12088    impl Render for TestModal {
12089        fn render(
12090            &mut self,
12091            _window: &mut Window,
12092            _cx: &mut Context<TestModal>,
12093        ) -> impl IntoElement {
12094            div().track_focus(&self.0)
12095        }
12096    }
12097
12098    #[gpui::test]
12099    async fn test_panels(cx: &mut gpui::TestAppContext) {
12100        init_test(cx);
12101        let fs = FakeFs::new(cx.executor());
12102
12103        let project = Project::test(fs, [], cx).await;
12104        let (multi_workspace, cx) =
12105            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12106        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12107
12108        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12109            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12110            workspace.add_panel(panel_1.clone(), window, cx);
12111            workspace.toggle_dock(DockPosition::Left, window, cx);
12112            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12113            workspace.add_panel(panel_2.clone(), window, cx);
12114            workspace.toggle_dock(DockPosition::Right, window, cx);
12115
12116            let left_dock = workspace.left_dock();
12117            assert_eq!(
12118                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12119                panel_1.panel_id()
12120            );
12121            assert_eq!(
12122                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
12123                panel_1.size(window, cx)
12124            );
12125
12126            left_dock.update(cx, |left_dock, cx| {
12127                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
12128            });
12129            assert_eq!(
12130                workspace
12131                    .right_dock()
12132                    .read(cx)
12133                    .visible_panel()
12134                    .unwrap()
12135                    .panel_id(),
12136                panel_2.panel_id(),
12137            );
12138
12139            (panel_1, panel_2)
12140        });
12141
12142        // Move panel_1 to the right
12143        panel_1.update_in(cx, |panel_1, window, cx| {
12144            panel_1.set_position(DockPosition::Right, window, cx)
12145        });
12146
12147        workspace.update_in(cx, |workspace, window, cx| {
12148            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12149            // Since it was the only panel on the left, the left dock should now be closed.
12150            assert!(!workspace.left_dock().read(cx).is_open());
12151            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12152            let right_dock = workspace.right_dock();
12153            assert_eq!(
12154                right_dock.read(cx).visible_panel().unwrap().panel_id(),
12155                panel_1.panel_id()
12156            );
12157            assert_eq!(
12158                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
12159                px(1337.)
12160            );
12161
12162            // Now we move panel_2 to the left
12163            panel_2.set_position(DockPosition::Left, window, cx);
12164        });
12165
12166        workspace.update(cx, |workspace, cx| {
12167            // Since panel_2 was not visible on the right, we don't open the left dock.
12168            assert!(!workspace.left_dock().read(cx).is_open());
12169            // And the right dock is unaffected in its displaying of panel_1
12170            assert!(workspace.right_dock().read(cx).is_open());
12171            assert_eq!(
12172                workspace
12173                    .right_dock()
12174                    .read(cx)
12175                    .visible_panel()
12176                    .unwrap()
12177                    .panel_id(),
12178                panel_1.panel_id(),
12179            );
12180        });
12181
12182        // Move panel_1 back to the left
12183        panel_1.update_in(cx, |panel_1, window, cx| {
12184            panel_1.set_position(DockPosition::Left, window, cx)
12185        });
12186
12187        workspace.update_in(cx, |workspace, window, cx| {
12188            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12189            let left_dock = workspace.left_dock();
12190            assert!(left_dock.read(cx).is_open());
12191            assert_eq!(
12192                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12193                panel_1.panel_id()
12194            );
12195            assert_eq!(
12196                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
12197                px(1337.)
12198            );
12199            // And the right dock should be closed as it no longer has any panels.
12200            assert!(!workspace.right_dock().read(cx).is_open());
12201
12202            // Now we move panel_1 to the bottom
12203            panel_1.set_position(DockPosition::Bottom, window, cx);
12204        });
12205
12206        workspace.update_in(cx, |workspace, window, cx| {
12207            // Since panel_1 was visible on the left, we close the left dock.
12208            assert!(!workspace.left_dock().read(cx).is_open());
12209            // The bottom dock is sized based on the panel's default size,
12210            // since the panel orientation changed from vertical to horizontal.
12211            let bottom_dock = workspace.bottom_dock();
12212            assert_eq!(
12213                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
12214                panel_1.size(window, cx),
12215            );
12216            // Close bottom dock and move panel_1 back to the left.
12217            bottom_dock.update(cx, |bottom_dock, cx| {
12218                bottom_dock.set_open(false, window, cx)
12219            });
12220            panel_1.set_position(DockPosition::Left, window, cx);
12221        });
12222
12223        // Emit activated event on panel 1
12224        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12225
12226        // Now the left dock is open and panel_1 is active and focused.
12227        workspace.update_in(cx, |workspace, window, cx| {
12228            let left_dock = workspace.left_dock();
12229            assert!(left_dock.read(cx).is_open());
12230            assert_eq!(
12231                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12232                panel_1.panel_id(),
12233            );
12234            assert!(panel_1.focus_handle(cx).is_focused(window));
12235        });
12236
12237        // Emit closed event on panel 2, which is not active
12238        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12239
12240        // Wo don't close the left dock, because panel_2 wasn't the active panel
12241        workspace.update(cx, |workspace, cx| {
12242            let left_dock = workspace.left_dock();
12243            assert!(left_dock.read(cx).is_open());
12244            assert_eq!(
12245                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12246                panel_1.panel_id(),
12247            );
12248        });
12249
12250        // Emitting a ZoomIn event shows the panel as zoomed.
12251        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12252        workspace.read_with(cx, |workspace, _| {
12253            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12254            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12255        });
12256
12257        // Move panel to another dock while it is zoomed
12258        panel_1.update_in(cx, |panel, window, cx| {
12259            panel.set_position(DockPosition::Right, window, cx)
12260        });
12261        workspace.read_with(cx, |workspace, _| {
12262            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12263
12264            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12265        });
12266
12267        // This is a helper for getting a:
12268        // - valid focus on an element,
12269        // - that isn't a part of the panes and panels system of the Workspace,
12270        // - and doesn't trigger the 'on_focus_lost' API.
12271        let focus_other_view = {
12272            let workspace = workspace.clone();
12273            move |cx: &mut VisualTestContext| {
12274                workspace.update_in(cx, |workspace, window, cx| {
12275                    if workspace.active_modal::<TestModal>(cx).is_some() {
12276                        workspace.toggle_modal(window, cx, TestModal::new);
12277                        workspace.toggle_modal(window, cx, TestModal::new);
12278                    } else {
12279                        workspace.toggle_modal(window, cx, TestModal::new);
12280                    }
12281                })
12282            }
12283        };
12284
12285        // If focus is transferred to another view that's not a panel or another pane, we still show
12286        // the panel as zoomed.
12287        focus_other_view(cx);
12288        workspace.read_with(cx, |workspace, _| {
12289            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12290            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12291        });
12292
12293        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12294        workspace.update_in(cx, |_workspace, window, cx| {
12295            cx.focus_self(window);
12296        });
12297        workspace.read_with(cx, |workspace, _| {
12298            assert_eq!(workspace.zoomed, None);
12299            assert_eq!(workspace.zoomed_position, None);
12300        });
12301
12302        // If focus is transferred again to another view that's not a panel or a pane, we won't
12303        // show the panel as zoomed because it wasn't zoomed before.
12304        focus_other_view(cx);
12305        workspace.read_with(cx, |workspace, _| {
12306            assert_eq!(workspace.zoomed, None);
12307            assert_eq!(workspace.zoomed_position, None);
12308        });
12309
12310        // When the panel is activated, it is zoomed again.
12311        cx.dispatch_action(ToggleRightDock);
12312        workspace.read_with(cx, |workspace, _| {
12313            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12314            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12315        });
12316
12317        // Emitting a ZoomOut event unzooms the panel.
12318        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12319        workspace.read_with(cx, |workspace, _| {
12320            assert_eq!(workspace.zoomed, None);
12321            assert_eq!(workspace.zoomed_position, None);
12322        });
12323
12324        // Emit closed event on panel 1, which is active
12325        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12326
12327        // Now the left dock is closed, because panel_1 was the active panel
12328        workspace.update(cx, |workspace, cx| {
12329            let right_dock = workspace.right_dock();
12330            assert!(!right_dock.read(cx).is_open());
12331        });
12332    }
12333
12334    #[gpui::test]
12335    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12336        init_test(cx);
12337
12338        let fs = FakeFs::new(cx.background_executor.clone());
12339        let project = Project::test(fs, [], cx).await;
12340        let (workspace, cx) =
12341            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12342        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12343
12344        let dirty_regular_buffer = cx.new(|cx| {
12345            TestItem::new(cx)
12346                .with_dirty(true)
12347                .with_label("1.txt")
12348                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12349        });
12350        let dirty_regular_buffer_2 = cx.new(|cx| {
12351            TestItem::new(cx)
12352                .with_dirty(true)
12353                .with_label("2.txt")
12354                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12355        });
12356        let dirty_multi_buffer_with_both = cx.new(|cx| {
12357            TestItem::new(cx)
12358                .with_dirty(true)
12359                .with_buffer_kind(ItemBufferKind::Multibuffer)
12360                .with_label("Fake Project Search")
12361                .with_project_items(&[
12362                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12363                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12364                ])
12365        });
12366        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12367        workspace.update_in(cx, |workspace, window, cx| {
12368            workspace.add_item(
12369                pane.clone(),
12370                Box::new(dirty_regular_buffer.clone()),
12371                None,
12372                false,
12373                false,
12374                window,
12375                cx,
12376            );
12377            workspace.add_item(
12378                pane.clone(),
12379                Box::new(dirty_regular_buffer_2.clone()),
12380                None,
12381                false,
12382                false,
12383                window,
12384                cx,
12385            );
12386            workspace.add_item(
12387                pane.clone(),
12388                Box::new(dirty_multi_buffer_with_both.clone()),
12389                None,
12390                false,
12391                false,
12392                window,
12393                cx,
12394            );
12395        });
12396
12397        pane.update_in(cx, |pane, window, cx| {
12398            pane.activate_item(2, true, true, window, cx);
12399            assert_eq!(
12400                pane.active_item().unwrap().item_id(),
12401                multi_buffer_with_both_files_id,
12402                "Should select the multi buffer in the pane"
12403            );
12404        });
12405        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12406            pane.close_other_items(
12407                &CloseOtherItems {
12408                    save_intent: Some(SaveIntent::Save),
12409                    close_pinned: true,
12410                },
12411                None,
12412                window,
12413                cx,
12414            )
12415        });
12416        cx.background_executor.run_until_parked();
12417        assert!(!cx.has_pending_prompt());
12418        close_all_but_multi_buffer_task
12419            .await
12420            .expect("Closing all buffers but the multi buffer failed");
12421        pane.update(cx, |pane, cx| {
12422            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12423            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12424            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12425            assert_eq!(pane.items_len(), 1);
12426            assert_eq!(
12427                pane.active_item().unwrap().item_id(),
12428                multi_buffer_with_both_files_id,
12429                "Should have only the multi buffer left in the pane"
12430            );
12431            assert!(
12432                dirty_multi_buffer_with_both.read(cx).is_dirty,
12433                "The multi buffer containing the unsaved buffer should still be dirty"
12434            );
12435        });
12436
12437        dirty_regular_buffer.update(cx, |buffer, cx| {
12438            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12439        });
12440
12441        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12442            pane.close_active_item(
12443                &CloseActiveItem {
12444                    save_intent: Some(SaveIntent::Close),
12445                    close_pinned: false,
12446                },
12447                window,
12448                cx,
12449            )
12450        });
12451        cx.background_executor.run_until_parked();
12452        assert!(
12453            cx.has_pending_prompt(),
12454            "Dirty multi buffer should prompt a save dialog"
12455        );
12456        cx.simulate_prompt_answer("Save");
12457        cx.background_executor.run_until_parked();
12458        close_multi_buffer_task
12459            .await
12460            .expect("Closing the multi buffer failed");
12461        pane.update(cx, |pane, cx| {
12462            assert_eq!(
12463                dirty_multi_buffer_with_both.read(cx).save_count,
12464                1,
12465                "Multi buffer item should get be saved"
12466            );
12467            // Test impl does not save inner items, so we do not assert them
12468            assert_eq!(
12469                pane.items_len(),
12470                0,
12471                "No more items should be left in the pane"
12472            );
12473            assert!(pane.active_item().is_none());
12474        });
12475    }
12476
12477    #[gpui::test]
12478    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12479        cx: &mut TestAppContext,
12480    ) {
12481        init_test(cx);
12482
12483        let fs = FakeFs::new(cx.background_executor.clone());
12484        let project = Project::test(fs, [], cx).await;
12485        let (workspace, cx) =
12486            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12487        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12488
12489        let dirty_regular_buffer = cx.new(|cx| {
12490            TestItem::new(cx)
12491                .with_dirty(true)
12492                .with_label("1.txt")
12493                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12494        });
12495        let dirty_regular_buffer_2 = cx.new(|cx| {
12496            TestItem::new(cx)
12497                .with_dirty(true)
12498                .with_label("2.txt")
12499                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12500        });
12501        let clear_regular_buffer = cx.new(|cx| {
12502            TestItem::new(cx)
12503                .with_label("3.txt")
12504                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12505        });
12506
12507        let dirty_multi_buffer_with_both = cx.new(|cx| {
12508            TestItem::new(cx)
12509                .with_dirty(true)
12510                .with_buffer_kind(ItemBufferKind::Multibuffer)
12511                .with_label("Fake Project Search")
12512                .with_project_items(&[
12513                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12514                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12515                    clear_regular_buffer.read(cx).project_items[0].clone(),
12516                ])
12517        });
12518        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12519        workspace.update_in(cx, |workspace, window, cx| {
12520            workspace.add_item(
12521                pane.clone(),
12522                Box::new(dirty_regular_buffer.clone()),
12523                None,
12524                false,
12525                false,
12526                window,
12527                cx,
12528            );
12529            workspace.add_item(
12530                pane.clone(),
12531                Box::new(dirty_multi_buffer_with_both.clone()),
12532                None,
12533                false,
12534                false,
12535                window,
12536                cx,
12537            );
12538        });
12539
12540        pane.update_in(cx, |pane, window, cx| {
12541            pane.activate_item(1, true, true, window, cx);
12542            assert_eq!(
12543                pane.active_item().unwrap().item_id(),
12544                multi_buffer_with_both_files_id,
12545                "Should select the multi buffer in the pane"
12546            );
12547        });
12548        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12549            pane.close_active_item(
12550                &CloseActiveItem {
12551                    save_intent: None,
12552                    close_pinned: false,
12553                },
12554                window,
12555                cx,
12556            )
12557        });
12558        cx.background_executor.run_until_parked();
12559        assert!(
12560            cx.has_pending_prompt(),
12561            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12562        );
12563    }
12564
12565    /// Tests that when `close_on_file_delete` is enabled, files are automatically
12566    /// closed when they are deleted from disk.
12567    #[gpui::test]
12568    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12569        init_test(cx);
12570
12571        // Enable the close_on_disk_deletion setting
12572        cx.update_global(|store: &mut SettingsStore, cx| {
12573            store.update_user_settings(cx, |settings| {
12574                settings.workspace.close_on_file_delete = Some(true);
12575            });
12576        });
12577
12578        let fs = FakeFs::new(cx.background_executor.clone());
12579        let project = Project::test(fs, [], cx).await;
12580        let (workspace, cx) =
12581            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12582        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12583
12584        // Create a test item that simulates a file
12585        let item = cx.new(|cx| {
12586            TestItem::new(cx)
12587                .with_label("test.txt")
12588                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12589        });
12590
12591        // Add item to workspace
12592        workspace.update_in(cx, |workspace, window, cx| {
12593            workspace.add_item(
12594                pane.clone(),
12595                Box::new(item.clone()),
12596                None,
12597                false,
12598                false,
12599                window,
12600                cx,
12601            );
12602        });
12603
12604        // Verify the item is in the pane
12605        pane.read_with(cx, |pane, _| {
12606            assert_eq!(pane.items().count(), 1);
12607        });
12608
12609        // Simulate file deletion by setting the item's deleted state
12610        item.update(cx, |item, _| {
12611            item.set_has_deleted_file(true);
12612        });
12613
12614        // Emit UpdateTab event to trigger the close behavior
12615        cx.run_until_parked();
12616        item.update(cx, |_, cx| {
12617            cx.emit(ItemEvent::UpdateTab);
12618        });
12619
12620        // Allow the close operation to complete
12621        cx.run_until_parked();
12622
12623        // Verify the item was automatically closed
12624        pane.read_with(cx, |pane, _| {
12625            assert_eq!(
12626                pane.items().count(),
12627                0,
12628                "Item should be automatically closed when file is deleted"
12629            );
12630        });
12631    }
12632
12633    /// Tests that when `close_on_file_delete` is disabled (default), files remain
12634    /// open with a strikethrough when they are deleted from disk.
12635    #[gpui::test]
12636    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12637        init_test(cx);
12638
12639        // Ensure close_on_disk_deletion is disabled (default)
12640        cx.update_global(|store: &mut SettingsStore, cx| {
12641            store.update_user_settings(cx, |settings| {
12642                settings.workspace.close_on_file_delete = Some(false);
12643            });
12644        });
12645
12646        let fs = FakeFs::new(cx.background_executor.clone());
12647        let project = Project::test(fs, [], cx).await;
12648        let (workspace, cx) =
12649            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12650        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12651
12652        // Create a test item that simulates a file
12653        let item = cx.new(|cx| {
12654            TestItem::new(cx)
12655                .with_label("test.txt")
12656                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12657        });
12658
12659        // Add item to workspace
12660        workspace.update_in(cx, |workspace, window, cx| {
12661            workspace.add_item(
12662                pane.clone(),
12663                Box::new(item.clone()),
12664                None,
12665                false,
12666                false,
12667                window,
12668                cx,
12669            );
12670        });
12671
12672        // Verify the item is in the pane
12673        pane.read_with(cx, |pane, _| {
12674            assert_eq!(pane.items().count(), 1);
12675        });
12676
12677        // Simulate file deletion
12678        item.update(cx, |item, _| {
12679            item.set_has_deleted_file(true);
12680        });
12681
12682        // Emit UpdateTab event
12683        cx.run_until_parked();
12684        item.update(cx, |_, cx| {
12685            cx.emit(ItemEvent::UpdateTab);
12686        });
12687
12688        // Allow any potential close operation to complete
12689        cx.run_until_parked();
12690
12691        // Verify the item remains open (with strikethrough)
12692        pane.read_with(cx, |pane, _| {
12693            assert_eq!(
12694                pane.items().count(),
12695                1,
12696                "Item should remain open when close_on_disk_deletion is disabled"
12697            );
12698        });
12699
12700        // Verify the item shows as deleted
12701        item.read_with(cx, |item, _| {
12702            assert!(
12703                item.has_deleted_file,
12704                "Item should be marked as having deleted file"
12705            );
12706        });
12707    }
12708
12709    /// Tests that dirty files are not automatically closed when deleted from disk,
12710    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12711    /// unsaved changes without being prompted.
12712    #[gpui::test]
12713    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12714        init_test(cx);
12715
12716        // Enable the close_on_file_delete setting
12717        cx.update_global(|store: &mut SettingsStore, cx| {
12718            store.update_user_settings(cx, |settings| {
12719                settings.workspace.close_on_file_delete = Some(true);
12720            });
12721        });
12722
12723        let fs = FakeFs::new(cx.background_executor.clone());
12724        let project = Project::test(fs, [], cx).await;
12725        let (workspace, cx) =
12726            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12727        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12728
12729        // Create a dirty test item
12730        let item = cx.new(|cx| {
12731            TestItem::new(cx)
12732                .with_dirty(true)
12733                .with_label("test.txt")
12734                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12735        });
12736
12737        // Add item to workspace
12738        workspace.update_in(cx, |workspace, window, cx| {
12739            workspace.add_item(
12740                pane.clone(),
12741                Box::new(item.clone()),
12742                None,
12743                false,
12744                false,
12745                window,
12746                cx,
12747            );
12748        });
12749
12750        // Simulate file deletion
12751        item.update(cx, |item, _| {
12752            item.set_has_deleted_file(true);
12753        });
12754
12755        // Emit UpdateTab event to trigger the close behavior
12756        cx.run_until_parked();
12757        item.update(cx, |_, cx| {
12758            cx.emit(ItemEvent::UpdateTab);
12759        });
12760
12761        // Allow any potential close operation to complete
12762        cx.run_until_parked();
12763
12764        // Verify the item remains open (dirty files are not auto-closed)
12765        pane.read_with(cx, |pane, _| {
12766            assert_eq!(
12767                pane.items().count(),
12768                1,
12769                "Dirty items should not be automatically closed even when file is deleted"
12770            );
12771        });
12772
12773        // Verify the item is marked as deleted and still dirty
12774        item.read_with(cx, |item, _| {
12775            assert!(
12776                item.has_deleted_file,
12777                "Item should be marked as having deleted file"
12778            );
12779            assert!(item.is_dirty, "Item should still be dirty");
12780        });
12781    }
12782
12783    /// Tests that navigation history is cleaned up when files are auto-closed
12784    /// due to deletion from disk.
12785    #[gpui::test]
12786    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12787        init_test(cx);
12788
12789        // Enable the close_on_file_delete setting
12790        cx.update_global(|store: &mut SettingsStore, cx| {
12791            store.update_user_settings(cx, |settings| {
12792                settings.workspace.close_on_file_delete = Some(true);
12793            });
12794        });
12795
12796        let fs = FakeFs::new(cx.background_executor.clone());
12797        let project = Project::test(fs, [], cx).await;
12798        let (workspace, cx) =
12799            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12800        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12801
12802        // Create test items
12803        let item1 = cx.new(|cx| {
12804            TestItem::new(cx)
12805                .with_label("test1.txt")
12806                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12807        });
12808        let item1_id = item1.item_id();
12809
12810        let item2 = cx.new(|cx| {
12811            TestItem::new(cx)
12812                .with_label("test2.txt")
12813                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12814        });
12815
12816        // Add items to workspace
12817        workspace.update_in(cx, |workspace, window, cx| {
12818            workspace.add_item(
12819                pane.clone(),
12820                Box::new(item1.clone()),
12821                None,
12822                false,
12823                false,
12824                window,
12825                cx,
12826            );
12827            workspace.add_item(
12828                pane.clone(),
12829                Box::new(item2.clone()),
12830                None,
12831                false,
12832                false,
12833                window,
12834                cx,
12835            );
12836        });
12837
12838        // Activate item1 to ensure it gets navigation entries
12839        pane.update_in(cx, |pane, window, cx| {
12840            pane.activate_item(0, true, true, window, cx);
12841        });
12842
12843        // Switch to item2 and back to create navigation history
12844        pane.update_in(cx, |pane, window, cx| {
12845            pane.activate_item(1, true, true, window, cx);
12846        });
12847        cx.run_until_parked();
12848
12849        pane.update_in(cx, |pane, window, cx| {
12850            pane.activate_item(0, true, true, window, cx);
12851        });
12852        cx.run_until_parked();
12853
12854        // Simulate file deletion for item1
12855        item1.update(cx, |item, _| {
12856            item.set_has_deleted_file(true);
12857        });
12858
12859        // Emit UpdateTab event to trigger the close behavior
12860        item1.update(cx, |_, cx| {
12861            cx.emit(ItemEvent::UpdateTab);
12862        });
12863        cx.run_until_parked();
12864
12865        // Verify item1 was closed
12866        pane.read_with(cx, |pane, _| {
12867            assert_eq!(
12868                pane.items().count(),
12869                1,
12870                "Should have 1 item remaining after auto-close"
12871            );
12872        });
12873
12874        // Check navigation history after close
12875        let has_item = pane.read_with(cx, |pane, cx| {
12876            let mut has_item = false;
12877            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12878                if entry.item.id() == item1_id {
12879                    has_item = true;
12880                }
12881            });
12882            has_item
12883        });
12884
12885        assert!(
12886            !has_item,
12887            "Navigation history should not contain closed item entries"
12888        );
12889    }
12890
12891    #[gpui::test]
12892    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12893        cx: &mut TestAppContext,
12894    ) {
12895        init_test(cx);
12896
12897        let fs = FakeFs::new(cx.background_executor.clone());
12898        let project = Project::test(fs, [], cx).await;
12899        let (workspace, cx) =
12900            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12901        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12902
12903        let dirty_regular_buffer = cx.new(|cx| {
12904            TestItem::new(cx)
12905                .with_dirty(true)
12906                .with_label("1.txt")
12907                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12908        });
12909        let dirty_regular_buffer_2 = cx.new(|cx| {
12910            TestItem::new(cx)
12911                .with_dirty(true)
12912                .with_label("2.txt")
12913                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12914        });
12915        let clear_regular_buffer = cx.new(|cx| {
12916            TestItem::new(cx)
12917                .with_label("3.txt")
12918                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12919        });
12920
12921        let dirty_multi_buffer = cx.new(|cx| {
12922            TestItem::new(cx)
12923                .with_dirty(true)
12924                .with_buffer_kind(ItemBufferKind::Multibuffer)
12925                .with_label("Fake Project Search")
12926                .with_project_items(&[
12927                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12928                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12929                    clear_regular_buffer.read(cx).project_items[0].clone(),
12930                ])
12931        });
12932        workspace.update_in(cx, |workspace, window, cx| {
12933            workspace.add_item(
12934                pane.clone(),
12935                Box::new(dirty_regular_buffer.clone()),
12936                None,
12937                false,
12938                false,
12939                window,
12940                cx,
12941            );
12942            workspace.add_item(
12943                pane.clone(),
12944                Box::new(dirty_regular_buffer_2.clone()),
12945                None,
12946                false,
12947                false,
12948                window,
12949                cx,
12950            );
12951            workspace.add_item(
12952                pane.clone(),
12953                Box::new(dirty_multi_buffer.clone()),
12954                None,
12955                false,
12956                false,
12957                window,
12958                cx,
12959            );
12960        });
12961
12962        pane.update_in(cx, |pane, window, cx| {
12963            pane.activate_item(2, true, true, window, cx);
12964            assert_eq!(
12965                pane.active_item().unwrap().item_id(),
12966                dirty_multi_buffer.item_id(),
12967                "Should select the multi buffer in the pane"
12968            );
12969        });
12970        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12971            pane.close_active_item(
12972                &CloseActiveItem {
12973                    save_intent: None,
12974                    close_pinned: false,
12975                },
12976                window,
12977                cx,
12978            )
12979        });
12980        cx.background_executor.run_until_parked();
12981        assert!(
12982            !cx.has_pending_prompt(),
12983            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12984        );
12985        close_multi_buffer_task
12986            .await
12987            .expect("Closing multi buffer failed");
12988        pane.update(cx, |pane, cx| {
12989            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12990            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12991            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12992            assert_eq!(
12993                pane.items()
12994                    .map(|item| item.item_id())
12995                    .sorted()
12996                    .collect::<Vec<_>>(),
12997                vec![
12998                    dirty_regular_buffer.item_id(),
12999                    dirty_regular_buffer_2.item_id(),
13000                ],
13001                "Should have no multi buffer left in the pane"
13002            );
13003            assert!(dirty_regular_buffer.read(cx).is_dirty);
13004            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13005        });
13006    }
13007
13008    #[gpui::test]
13009    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13010        init_test(cx);
13011        let fs = FakeFs::new(cx.executor());
13012        let project = Project::test(fs, [], cx).await;
13013        let (multi_workspace, cx) =
13014            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13015        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13016
13017        // Add a new panel to the right dock, opening the dock and setting the
13018        // focus to the new panel.
13019        let panel = workspace.update_in(cx, |workspace, window, cx| {
13020            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13021            workspace.add_panel(panel.clone(), window, cx);
13022
13023            workspace
13024                .right_dock()
13025                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13026
13027            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13028
13029            panel
13030        });
13031
13032        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13033        // panel to the next valid position which, in this case, is the left
13034        // dock.
13035        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13036        workspace.update(cx, |workspace, cx| {
13037            assert!(workspace.left_dock().read(cx).is_open());
13038            assert_eq!(panel.read(cx).position, DockPosition::Left);
13039        });
13040
13041        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13042        // panel to the next valid position which, in this case, is the bottom
13043        // dock.
13044        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13045        workspace.update(cx, |workspace, cx| {
13046            assert!(workspace.bottom_dock().read(cx).is_open());
13047            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13048        });
13049
13050        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13051        // around moving the panel to its initial position, the right dock.
13052        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13053        workspace.update(cx, |workspace, cx| {
13054            assert!(workspace.right_dock().read(cx).is_open());
13055            assert_eq!(panel.read(cx).position, DockPosition::Right);
13056        });
13057
13058        // Remove focus from the panel, ensuring that, if the panel is not
13059        // focused, the `MoveFocusedPanelToNextPosition` action does not update
13060        // the panel's position, so the panel is still in the right dock.
13061        workspace.update_in(cx, |workspace, window, cx| {
13062            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13063        });
13064
13065        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13066        workspace.update(cx, |workspace, cx| {
13067            assert!(workspace.right_dock().read(cx).is_open());
13068            assert_eq!(panel.read(cx).position, DockPosition::Right);
13069        });
13070    }
13071
13072    #[gpui::test]
13073    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13074        init_test(cx);
13075
13076        let fs = FakeFs::new(cx.executor());
13077        let project = Project::test(fs, [], cx).await;
13078        let (workspace, cx) =
13079            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13080
13081        let item_1 = cx.new(|cx| {
13082            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13083        });
13084        workspace.update_in(cx, |workspace, window, cx| {
13085            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13086            workspace.move_item_to_pane_in_direction(
13087                &MoveItemToPaneInDirection {
13088                    direction: SplitDirection::Right,
13089                    focus: true,
13090                    clone: false,
13091                },
13092                window,
13093                cx,
13094            );
13095            workspace.move_item_to_pane_at_index(
13096                &MoveItemToPane {
13097                    destination: 3,
13098                    focus: true,
13099                    clone: false,
13100                },
13101                window,
13102                cx,
13103            );
13104
13105            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13106            assert_eq!(
13107                pane_items_paths(&workspace.active_pane, cx),
13108                vec!["first.txt".to_string()],
13109                "Single item was not moved anywhere"
13110            );
13111        });
13112
13113        let item_2 = cx.new(|cx| {
13114            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13115        });
13116        workspace.update_in(cx, |workspace, window, cx| {
13117            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13118            assert_eq!(
13119                pane_items_paths(&workspace.panes[0], cx),
13120                vec!["first.txt".to_string(), "second.txt".to_string()],
13121            );
13122            workspace.move_item_to_pane_in_direction(
13123                &MoveItemToPaneInDirection {
13124                    direction: SplitDirection::Right,
13125                    focus: true,
13126                    clone: false,
13127                },
13128                window,
13129                cx,
13130            );
13131
13132            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13133            assert_eq!(
13134                pane_items_paths(&workspace.panes[0], cx),
13135                vec!["first.txt".to_string()],
13136                "After moving, one item should be left in the original pane"
13137            );
13138            assert_eq!(
13139                pane_items_paths(&workspace.panes[1], cx),
13140                vec!["second.txt".to_string()],
13141                "New item should have been moved to the new pane"
13142            );
13143        });
13144
13145        let item_3 = cx.new(|cx| {
13146            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13147        });
13148        workspace.update_in(cx, |workspace, window, cx| {
13149            let original_pane = workspace.panes[0].clone();
13150            workspace.set_active_pane(&original_pane, window, cx);
13151            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13152            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13153            assert_eq!(
13154                pane_items_paths(&workspace.active_pane, cx),
13155                vec!["first.txt".to_string(), "third.txt".to_string()],
13156                "New pane should be ready to move one item out"
13157            );
13158
13159            workspace.move_item_to_pane_at_index(
13160                &MoveItemToPane {
13161                    destination: 3,
13162                    focus: true,
13163                    clone: false,
13164                },
13165                window,
13166                cx,
13167            );
13168            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13169            assert_eq!(
13170                pane_items_paths(&workspace.active_pane, cx),
13171                vec!["first.txt".to_string()],
13172                "After moving, one item should be left in the original pane"
13173            );
13174            assert_eq!(
13175                pane_items_paths(&workspace.panes[1], cx),
13176                vec!["second.txt".to_string()],
13177                "Previously created pane should be unchanged"
13178            );
13179            assert_eq!(
13180                pane_items_paths(&workspace.panes[2], cx),
13181                vec!["third.txt".to_string()],
13182                "New item should have been moved to the new pane"
13183            );
13184        });
13185    }
13186
13187    #[gpui::test]
13188    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13189        init_test(cx);
13190
13191        let fs = FakeFs::new(cx.executor());
13192        let project = Project::test(fs, [], cx).await;
13193        let (workspace, cx) =
13194            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13195
13196        let item_1 = cx.new(|cx| {
13197            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13198        });
13199        workspace.update_in(cx, |workspace, window, cx| {
13200            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13201            workspace.move_item_to_pane_in_direction(
13202                &MoveItemToPaneInDirection {
13203                    direction: SplitDirection::Right,
13204                    focus: true,
13205                    clone: true,
13206                },
13207                window,
13208                cx,
13209            );
13210        });
13211        cx.run_until_parked();
13212        workspace.update_in(cx, |workspace, window, cx| {
13213            workspace.move_item_to_pane_at_index(
13214                &MoveItemToPane {
13215                    destination: 3,
13216                    focus: true,
13217                    clone: true,
13218                },
13219                window,
13220                cx,
13221            );
13222        });
13223        cx.run_until_parked();
13224
13225        workspace.update(cx, |workspace, cx| {
13226            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13227            for pane in workspace.panes() {
13228                assert_eq!(
13229                    pane_items_paths(pane, cx),
13230                    vec!["first.txt".to_string()],
13231                    "Single item exists in all panes"
13232                );
13233            }
13234        });
13235
13236        // verify that the active pane has been updated after waiting for the
13237        // pane focus event to fire and resolve
13238        workspace.read_with(cx, |workspace, _app| {
13239            assert_eq!(
13240                workspace.active_pane(),
13241                &workspace.panes[2],
13242                "The third pane should be the active one: {:?}",
13243                workspace.panes
13244            );
13245        })
13246    }
13247
13248    #[gpui::test]
13249    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13250        init_test(cx);
13251
13252        let fs = FakeFs::new(cx.executor());
13253        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13254
13255        let project = Project::test(fs, ["root".as_ref()], cx).await;
13256        let (workspace, cx) =
13257            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13258
13259        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13260        // Add item to pane A with project path
13261        let item_a = cx.new(|cx| {
13262            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13263        });
13264        workspace.update_in(cx, |workspace, window, cx| {
13265            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13266        });
13267
13268        // Split to create pane B
13269        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13270            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13271        });
13272
13273        // Add item with SAME project path to pane B, and pin it
13274        let item_b = cx.new(|cx| {
13275            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13276        });
13277        pane_b.update_in(cx, |pane, window, cx| {
13278            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13279            pane.set_pinned_count(1);
13280        });
13281
13282        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13283        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13284
13285        // close_pinned: false should only close the unpinned copy
13286        workspace.update_in(cx, |workspace, window, cx| {
13287            workspace.close_item_in_all_panes(
13288                &CloseItemInAllPanes {
13289                    save_intent: Some(SaveIntent::Close),
13290                    close_pinned: false,
13291                },
13292                window,
13293                cx,
13294            )
13295        });
13296        cx.executor().run_until_parked();
13297
13298        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13299        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13300        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13301        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13302
13303        // Split again, seeing as closing the previous item also closed its
13304        // pane, so only pane remains, which does not allow us to properly test
13305        // that both items close when `close_pinned: true`.
13306        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13307            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13308        });
13309
13310        // Add an item with the same project path to pane C so that
13311        // close_item_in_all_panes can determine what to close across all panes
13312        // (it reads the active item from the active pane, and split_pane
13313        // creates an empty pane).
13314        let item_c = cx.new(|cx| {
13315            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13316        });
13317        pane_c.update_in(cx, |pane, window, cx| {
13318            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13319        });
13320
13321        // close_pinned: true should close the pinned copy too
13322        workspace.update_in(cx, |workspace, window, cx| {
13323            let panes_count = workspace.panes().len();
13324            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13325
13326            workspace.close_item_in_all_panes(
13327                &CloseItemInAllPanes {
13328                    save_intent: Some(SaveIntent::Close),
13329                    close_pinned: true,
13330                },
13331                window,
13332                cx,
13333            )
13334        });
13335        cx.executor().run_until_parked();
13336
13337        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13338        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13339        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13340        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13341    }
13342
13343    mod register_project_item_tests {
13344
13345        use super::*;
13346
13347        // View
13348        struct TestPngItemView {
13349            focus_handle: FocusHandle,
13350        }
13351        // Model
13352        struct TestPngItem {}
13353
13354        impl project::ProjectItem for TestPngItem {
13355            fn try_open(
13356                _project: &Entity<Project>,
13357                path: &ProjectPath,
13358                cx: &mut App,
13359            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13360                if path.path.extension().unwrap() == "png" {
13361                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13362                } else {
13363                    None
13364                }
13365            }
13366
13367            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13368                None
13369            }
13370
13371            fn project_path(&self, _: &App) -> Option<ProjectPath> {
13372                None
13373            }
13374
13375            fn is_dirty(&self) -> bool {
13376                false
13377            }
13378        }
13379
13380        impl Item for TestPngItemView {
13381            type Event = ();
13382            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13383                "".into()
13384            }
13385        }
13386        impl EventEmitter<()> for TestPngItemView {}
13387        impl Focusable for TestPngItemView {
13388            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13389                self.focus_handle.clone()
13390            }
13391        }
13392
13393        impl Render for TestPngItemView {
13394            fn render(
13395                &mut self,
13396                _window: &mut Window,
13397                _cx: &mut Context<Self>,
13398            ) -> impl IntoElement {
13399                Empty
13400            }
13401        }
13402
13403        impl ProjectItem for TestPngItemView {
13404            type Item = TestPngItem;
13405
13406            fn for_project_item(
13407                _project: Entity<Project>,
13408                _pane: Option<&Pane>,
13409                _item: Entity<Self::Item>,
13410                _: &mut Window,
13411                cx: &mut Context<Self>,
13412            ) -> Self
13413            where
13414                Self: Sized,
13415            {
13416                Self {
13417                    focus_handle: cx.focus_handle(),
13418                }
13419            }
13420        }
13421
13422        // View
13423        struct TestIpynbItemView {
13424            focus_handle: FocusHandle,
13425        }
13426        // Model
13427        struct TestIpynbItem {}
13428
13429        impl project::ProjectItem for TestIpynbItem {
13430            fn try_open(
13431                _project: &Entity<Project>,
13432                path: &ProjectPath,
13433                cx: &mut App,
13434            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13435                if path.path.extension().unwrap() == "ipynb" {
13436                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13437                } else {
13438                    None
13439                }
13440            }
13441
13442            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13443                None
13444            }
13445
13446            fn project_path(&self, _: &App) -> Option<ProjectPath> {
13447                None
13448            }
13449
13450            fn is_dirty(&self) -> bool {
13451                false
13452            }
13453        }
13454
13455        impl Item for TestIpynbItemView {
13456            type Event = ();
13457            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13458                "".into()
13459            }
13460        }
13461        impl EventEmitter<()> for TestIpynbItemView {}
13462        impl Focusable for TestIpynbItemView {
13463            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13464                self.focus_handle.clone()
13465            }
13466        }
13467
13468        impl Render for TestIpynbItemView {
13469            fn render(
13470                &mut self,
13471                _window: &mut Window,
13472                _cx: &mut Context<Self>,
13473            ) -> impl IntoElement {
13474                Empty
13475            }
13476        }
13477
13478        impl ProjectItem for TestIpynbItemView {
13479            type Item = TestIpynbItem;
13480
13481            fn for_project_item(
13482                _project: Entity<Project>,
13483                _pane: Option<&Pane>,
13484                _item: Entity<Self::Item>,
13485                _: &mut Window,
13486                cx: &mut Context<Self>,
13487            ) -> Self
13488            where
13489                Self: Sized,
13490            {
13491                Self {
13492                    focus_handle: cx.focus_handle(),
13493                }
13494            }
13495        }
13496
13497        struct TestAlternatePngItemView {
13498            focus_handle: FocusHandle,
13499        }
13500
13501        impl Item for TestAlternatePngItemView {
13502            type Event = ();
13503            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13504                "".into()
13505            }
13506        }
13507
13508        impl EventEmitter<()> for TestAlternatePngItemView {}
13509        impl Focusable for TestAlternatePngItemView {
13510            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13511                self.focus_handle.clone()
13512            }
13513        }
13514
13515        impl Render for TestAlternatePngItemView {
13516            fn render(
13517                &mut self,
13518                _window: &mut Window,
13519                _cx: &mut Context<Self>,
13520            ) -> impl IntoElement {
13521                Empty
13522            }
13523        }
13524
13525        impl ProjectItem for TestAlternatePngItemView {
13526            type Item = TestPngItem;
13527
13528            fn for_project_item(
13529                _project: Entity<Project>,
13530                _pane: Option<&Pane>,
13531                _item: Entity<Self::Item>,
13532                _: &mut Window,
13533                cx: &mut Context<Self>,
13534            ) -> Self
13535            where
13536                Self: Sized,
13537            {
13538                Self {
13539                    focus_handle: cx.focus_handle(),
13540                }
13541            }
13542        }
13543
13544        #[gpui::test]
13545        async fn test_register_project_item(cx: &mut TestAppContext) {
13546            init_test(cx);
13547
13548            cx.update(|cx| {
13549                register_project_item::<TestPngItemView>(cx);
13550                register_project_item::<TestIpynbItemView>(cx);
13551            });
13552
13553            let fs = FakeFs::new(cx.executor());
13554            fs.insert_tree(
13555                "/root1",
13556                json!({
13557                    "one.png": "BINARYDATAHERE",
13558                    "two.ipynb": "{ totally a notebook }",
13559                    "three.txt": "editing text, sure why not?"
13560                }),
13561            )
13562            .await;
13563
13564            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13565            let (workspace, cx) =
13566                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13567
13568            let worktree_id = project.update(cx, |project, cx| {
13569                project.worktrees(cx).next().unwrap().read(cx).id()
13570            });
13571
13572            let handle = workspace
13573                .update_in(cx, |workspace, window, cx| {
13574                    let project_path = (worktree_id, rel_path("one.png"));
13575                    workspace.open_path(project_path, None, true, window, cx)
13576                })
13577                .await
13578                .unwrap();
13579
13580            // Now we can check if the handle we got back errored or not
13581            assert_eq!(
13582                handle.to_any_view().entity_type(),
13583                TypeId::of::<TestPngItemView>()
13584            );
13585
13586            let handle = workspace
13587                .update_in(cx, |workspace, window, cx| {
13588                    let project_path = (worktree_id, rel_path("two.ipynb"));
13589                    workspace.open_path(project_path, None, true, window, cx)
13590                })
13591                .await
13592                .unwrap();
13593
13594            assert_eq!(
13595                handle.to_any_view().entity_type(),
13596                TypeId::of::<TestIpynbItemView>()
13597            );
13598
13599            let handle = workspace
13600                .update_in(cx, |workspace, window, cx| {
13601                    let project_path = (worktree_id, rel_path("three.txt"));
13602                    workspace.open_path(project_path, None, true, window, cx)
13603                })
13604                .await;
13605            assert!(handle.is_err());
13606        }
13607
13608        #[gpui::test]
13609        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13610            init_test(cx);
13611
13612            cx.update(|cx| {
13613                register_project_item::<TestPngItemView>(cx);
13614                register_project_item::<TestAlternatePngItemView>(cx);
13615            });
13616
13617            let fs = FakeFs::new(cx.executor());
13618            fs.insert_tree(
13619                "/root1",
13620                json!({
13621                    "one.png": "BINARYDATAHERE",
13622                    "two.ipynb": "{ totally a notebook }",
13623                    "three.txt": "editing text, sure why not?"
13624                }),
13625            )
13626            .await;
13627            let project = Project::test(fs, ["root1".as_ref()], cx).await;
13628            let (workspace, cx) =
13629                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13630            let worktree_id = project.update(cx, |project, cx| {
13631                project.worktrees(cx).next().unwrap().read(cx).id()
13632            });
13633
13634            let handle = workspace
13635                .update_in(cx, |workspace, window, cx| {
13636                    let project_path = (worktree_id, rel_path("one.png"));
13637                    workspace.open_path(project_path, None, true, window, cx)
13638                })
13639                .await
13640                .unwrap();
13641
13642            // This _must_ be the second item registered
13643            assert_eq!(
13644                handle.to_any_view().entity_type(),
13645                TypeId::of::<TestAlternatePngItemView>()
13646            );
13647
13648            let handle = workspace
13649                .update_in(cx, |workspace, window, cx| {
13650                    let project_path = (worktree_id, rel_path("three.txt"));
13651                    workspace.open_path(project_path, None, true, window, cx)
13652                })
13653                .await;
13654            assert!(handle.is_err());
13655        }
13656    }
13657
13658    #[gpui::test]
13659    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13660        init_test(cx);
13661
13662        let fs = FakeFs::new(cx.executor());
13663        let project = Project::test(fs, [], cx).await;
13664        let (workspace, _cx) =
13665            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13666
13667        // Test with status bar shown (default)
13668        workspace.read_with(cx, |workspace, cx| {
13669            let visible = workspace.status_bar_visible(cx);
13670            assert!(visible, "Status bar should be visible by default");
13671        });
13672
13673        // Test with status bar hidden
13674        cx.update_global(|store: &mut SettingsStore, cx| {
13675            store.update_user_settings(cx, |settings| {
13676                settings.status_bar.get_or_insert_default().show = Some(false);
13677            });
13678        });
13679
13680        workspace.read_with(cx, |workspace, cx| {
13681            let visible = workspace.status_bar_visible(cx);
13682            assert!(!visible, "Status bar should be hidden when show is false");
13683        });
13684
13685        // Test with status bar shown explicitly
13686        cx.update_global(|store: &mut SettingsStore, cx| {
13687            store.update_user_settings(cx, |settings| {
13688                settings.status_bar.get_or_insert_default().show = Some(true);
13689            });
13690        });
13691
13692        workspace.read_with(cx, |workspace, cx| {
13693            let visible = workspace.status_bar_visible(cx);
13694            assert!(visible, "Status bar should be visible when show is true");
13695        });
13696    }
13697
13698    #[gpui::test]
13699    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13700        init_test(cx);
13701
13702        let fs = FakeFs::new(cx.executor());
13703        let project = Project::test(fs, [], cx).await;
13704        let (multi_workspace, cx) =
13705            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13706        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13707        let panel = workspace.update_in(cx, |workspace, window, cx| {
13708            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13709            workspace.add_panel(panel.clone(), window, cx);
13710
13711            workspace
13712                .right_dock()
13713                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13714
13715            panel
13716        });
13717
13718        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13719        let item_a = cx.new(TestItem::new);
13720        let item_b = cx.new(TestItem::new);
13721        let item_a_id = item_a.entity_id();
13722        let item_b_id = item_b.entity_id();
13723
13724        pane.update_in(cx, |pane, window, cx| {
13725            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13726            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13727        });
13728
13729        pane.read_with(cx, |pane, _| {
13730            assert_eq!(pane.items_len(), 2);
13731            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13732        });
13733
13734        workspace.update_in(cx, |workspace, window, cx| {
13735            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13736        });
13737
13738        workspace.update_in(cx, |_, window, cx| {
13739            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13740        });
13741
13742        // Assert that the `pane::CloseActiveItem` action is handled at the
13743        // workspace level when one of the dock panels is focused and, in that
13744        // case, the center pane's active item is closed but the focus is not
13745        // moved.
13746        cx.dispatch_action(pane::CloseActiveItem::default());
13747        cx.run_until_parked();
13748
13749        pane.read_with(cx, |pane, _| {
13750            assert_eq!(pane.items_len(), 1);
13751            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13752        });
13753
13754        workspace.update_in(cx, |workspace, window, cx| {
13755            assert!(workspace.right_dock().read(cx).is_open());
13756            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13757        });
13758    }
13759
13760    #[gpui::test]
13761    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13762        init_test(cx);
13763        let fs = FakeFs::new(cx.executor());
13764
13765        let project_a = Project::test(fs.clone(), [], cx).await;
13766        let project_b = Project::test(fs, [], cx).await;
13767
13768        let multi_workspace_handle =
13769            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13770        cx.run_until_parked();
13771
13772        let workspace_a = multi_workspace_handle
13773            .read_with(cx, |mw, _| mw.workspace().clone())
13774            .unwrap();
13775
13776        let _workspace_b = multi_workspace_handle
13777            .update(cx, |mw, window, cx| {
13778                mw.test_add_workspace(project_b, window, cx)
13779            })
13780            .unwrap();
13781
13782        // Switch to workspace A
13783        multi_workspace_handle
13784            .update(cx, |mw, window, cx| {
13785                mw.activate_index(0, window, cx);
13786            })
13787            .unwrap();
13788
13789        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13790
13791        // Add a panel to workspace A's right dock and open the dock
13792        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13793            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13794            workspace.add_panel(panel.clone(), window, cx);
13795            workspace
13796                .right_dock()
13797                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13798            panel
13799        });
13800
13801        // Focus the panel through the workspace (matching existing test pattern)
13802        workspace_a.update_in(cx, |workspace, window, cx| {
13803            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13804        });
13805
13806        // Zoom the panel
13807        panel.update_in(cx, |panel, window, cx| {
13808            panel.set_zoomed(true, window, cx);
13809        });
13810
13811        // Verify the panel is zoomed and the dock is open
13812        workspace_a.update_in(cx, |workspace, window, cx| {
13813            assert!(
13814                workspace.right_dock().read(cx).is_open(),
13815                "dock should be open before switch"
13816            );
13817            assert!(
13818                panel.is_zoomed(window, cx),
13819                "panel should be zoomed before switch"
13820            );
13821            assert!(
13822                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13823                "panel should be focused before switch"
13824            );
13825        });
13826
13827        // Switch to workspace B
13828        multi_workspace_handle
13829            .update(cx, |mw, window, cx| {
13830                mw.activate_index(1, window, cx);
13831            })
13832            .unwrap();
13833        cx.run_until_parked();
13834
13835        // Switch back to workspace A
13836        multi_workspace_handle
13837            .update(cx, |mw, window, cx| {
13838                mw.activate_index(0, window, cx);
13839            })
13840            .unwrap();
13841        cx.run_until_parked();
13842
13843        // Verify the panel is still zoomed and the dock is still open
13844        workspace_a.update_in(cx, |workspace, window, cx| {
13845            assert!(
13846                workspace.right_dock().read(cx).is_open(),
13847                "dock should still be open after switching back"
13848            );
13849            assert!(
13850                panel.is_zoomed(window, cx),
13851                "panel should still be zoomed after switching back"
13852            );
13853        });
13854    }
13855
13856    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13857        pane.read(cx)
13858            .items()
13859            .flat_map(|item| {
13860                item.project_paths(cx)
13861                    .into_iter()
13862                    .map(|path| path.path.display(PathStyle::local()).into_owned())
13863            })
13864            .collect()
13865    }
13866
13867    pub fn init_test(cx: &mut TestAppContext) {
13868        cx.update(|cx| {
13869            let settings_store = SettingsStore::test(cx);
13870            cx.set_global(settings_store);
13871            cx.set_global(db::AppDatabase::test_new());
13872            theme::init(theme::LoadThemes::JustBase, cx);
13873        });
13874    }
13875
13876    #[gpui::test]
13877    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
13878        use settings::{ThemeName, ThemeSelection};
13879        use theme::SystemAppearance;
13880        use zed_actions::theme::ToggleMode;
13881
13882        init_test(cx);
13883
13884        let fs = FakeFs::new(cx.executor());
13885        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
13886
13887        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
13888            .await;
13889
13890        // Build a test project and workspace view so the test can invoke
13891        // the workspace action handler the same way the UI would.
13892        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
13893        let (workspace, cx) =
13894            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13895
13896        // Seed the settings file with a plain static light theme so the
13897        // first toggle always starts from a known persisted state.
13898        workspace.update_in(cx, |_workspace, _window, cx| {
13899            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
13900            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
13901                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
13902            });
13903        });
13904        cx.executor().advance_clock(Duration::from_millis(200));
13905        cx.run_until_parked();
13906
13907        // Confirm the initial persisted settings contain the static theme
13908        // we just wrote before any toggling happens.
13909        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13910        assert!(settings_text.contains(r#""theme": "One Light""#));
13911
13912        // Toggle once. This should migrate the persisted theme settings
13913        // into light/dark slots and enable system mode.
13914        workspace.update_in(cx, |workspace, window, cx| {
13915            workspace.toggle_theme_mode(&ToggleMode, window, cx);
13916        });
13917        cx.executor().advance_clock(Duration::from_millis(200));
13918        cx.run_until_parked();
13919
13920        // 1. Static -> Dynamic
13921        // this assertion checks theme changed from static to dynamic.
13922        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13923        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
13924        assert_eq!(
13925            parsed["theme"],
13926            serde_json::json!({
13927                "mode": "system",
13928                "light": "One Light",
13929                "dark": "One Dark"
13930            })
13931        );
13932
13933        // 2. Toggle again, suppose it will change the mode to light
13934        workspace.update_in(cx, |workspace, window, cx| {
13935            workspace.toggle_theme_mode(&ToggleMode, window, cx);
13936        });
13937        cx.executor().advance_clock(Duration::from_millis(200));
13938        cx.run_until_parked();
13939
13940        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13941        assert!(settings_text.contains(r#""mode": "light""#));
13942    }
13943
13944    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13945        let item = TestProjectItem::new(id, path, cx);
13946        item.update(cx, |item, _| {
13947            item.is_dirty = true;
13948        });
13949        item
13950    }
13951
13952    #[gpui::test]
13953    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13954        cx: &mut gpui::TestAppContext,
13955    ) {
13956        init_test(cx);
13957        let fs = FakeFs::new(cx.executor());
13958
13959        let project = Project::test(fs, [], cx).await;
13960        let (workspace, cx) =
13961            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13962
13963        let panel = workspace.update_in(cx, |workspace, window, cx| {
13964            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13965            workspace.add_panel(panel.clone(), window, cx);
13966            workspace
13967                .right_dock()
13968                .update(cx, |dock, cx| dock.set_open(true, window, cx));
13969            panel
13970        });
13971
13972        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13973        pane.update_in(cx, |pane, window, cx| {
13974            let item = cx.new(TestItem::new);
13975            pane.add_item(Box::new(item), true, true, None, window, cx);
13976        });
13977
13978        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13979        // mirrors the real-world flow and avoids side effects from directly
13980        // focusing the panel while the center pane is active.
13981        workspace.update_in(cx, |workspace, window, cx| {
13982            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13983        });
13984
13985        panel.update_in(cx, |panel, window, cx| {
13986            panel.set_zoomed(true, window, cx);
13987        });
13988
13989        workspace.update_in(cx, |workspace, window, cx| {
13990            assert!(workspace.right_dock().read(cx).is_open());
13991            assert!(panel.is_zoomed(window, cx));
13992            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13993        });
13994
13995        // Simulate a spurious pane::Event::Focus on the center pane while the
13996        // panel still has focus. This mirrors what happens during macOS window
13997        // activation: the center pane fires a focus event even though actual
13998        // focus remains on the dock panel.
13999        pane.update_in(cx, |_, _, cx| {
14000            cx.emit(pane::Event::Focus);
14001        });
14002
14003        // The dock must remain open because the panel had focus at the time the
14004        // event was processed. Before the fix, dock_to_preserve was None for
14005        // panels that don't implement pane(), causing the dock to close.
14006        workspace.update_in(cx, |workspace, window, cx| {
14007            assert!(
14008                workspace.right_dock().read(cx).is_open(),
14009                "Dock should stay open when its zoomed panel (without pane()) still has focus"
14010            );
14011            assert!(panel.is_zoomed(window, cx));
14012        });
14013    }
14014}