workspace.rs

    1pub mod active_file_name;
    2pub mod dock;
    3pub mod history_manager;
    4pub mod invalid_item_view;
    5pub mod item;
    6mod modal_layer;
    7mod multi_workspace;
    8#[cfg(test)]
    9mod multi_workspace_tests;
   10pub mod notifications;
   11pub mod pane;
   12pub mod pane_group;
   13pub mod path_list {
   14    pub use util::path_list::{PathList, SerializedPathList};
   15}
   16mod persistence;
   17pub mod searchable;
   18mod security_modal;
   19pub mod shared_screen;
   20use db::smol::future::yield_now;
   21pub use shared_screen::SharedScreen;
   22mod status_bar;
   23pub mod tasks;
   24mod theme_preview;
   25mod toast_layer;
   26mod toolbar;
   27pub mod welcome;
   28mod workspace_settings;
   29
   30pub use crate::notifications::NotificationFrame;
   31pub use dock::Panel;
   32pub use multi_workspace::{
   33    CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
   34    MultiWorkspaceEvent, NextWorkspace, PreviousWorkspace, Sidebar, SidebarEvent, SidebarHandle,
   35    SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar, sidebar_side_context_menu,
   36};
   37pub use path_list::{PathList, SerializedPathList};
   38pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   39
   40use anyhow::{Context as _, Result, anyhow};
   41use client::{
   42    ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
   43    proto::{self, ErrorCode, PanelId, PeerId},
   44};
   45use collections::{HashMap, HashSet, hash_map};
   46use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   47use fs::Fs;
   48use futures::{
   49    Future, FutureExt, StreamExt,
   50    channel::{
   51        mpsc::{self, UnboundedReceiver, UnboundedSender},
   52        oneshot,
   53    },
   54    future::{Shared, try_join_all},
   55};
   56use gpui::{
   57    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
   58    Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   59    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   60    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   61    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   62    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   63};
   64pub use history_manager::*;
   65pub use item::{
   66    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   67    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   68};
   69use itertools::Itertools;
   70use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   71pub use modal_layer::*;
   72use node_runtime::NodeRuntime;
   73use notifications::{
   74    DetachAndPromptErr, Notifications, dismiss_app_notification,
   75    simple_message_notification::MessageNotification,
   76};
   77pub use pane::*;
   78pub use pane_group::{
   79    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   80    SplitDirection,
   81};
   82use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
   83pub use persistence::{
   84    WorkspaceDb, delete_unloaded_items,
   85    model::{
   86        DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
   87        SessionWorkspace,
   88    },
   89    read_serialized_multi_workspaces, resolve_worktree_workspaces,
   90};
   91use postage::stream::Stream;
   92use project::{
   93    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
   94    WorktreeSettings,
   95    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   96    project_settings::ProjectSettings,
   97    toolchain_store::ToolchainStoreEvent,
   98    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
   99};
  100use remote::{
  101    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
  102    remote_client::ConnectionIdentifier,
  103};
  104use schemars::JsonSchema;
  105use serde::Deserialize;
  106use session::AppSession;
  107use settings::{
  108    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  109};
  110
  111use sqlez::{
  112    bindable::{Bind, Column, StaticColumnCount},
  113    statement::Statement,
  114};
  115use status_bar::StatusBar;
  116pub use status_bar::StatusItemView;
  117use std::{
  118    any::TypeId,
  119    borrow::Cow,
  120    cell::RefCell,
  121    cmp,
  122    collections::VecDeque,
  123    env,
  124    hash::Hash,
  125    path::{Path, PathBuf},
  126    process::ExitStatus,
  127    rc::Rc,
  128    sync::{
  129        Arc, LazyLock,
  130        atomic::{AtomicBool, AtomicUsize},
  131    },
  132    time::Duration,
  133};
  134use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  135use theme::{ActiveTheme, SystemAppearance};
  136use theme_settings::ThemeSettings;
  137pub use toolbar::{
  138    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  139};
  140pub use ui;
  141use ui::{Window, prelude::*};
  142use util::{
  143    ResultExt, TryFutureExt,
  144    paths::{PathStyle, SanitizedPath},
  145    rel_path::RelPath,
  146    serde::default_true,
  147};
  148use uuid::Uuid;
  149pub use workspace_settings::{
  150    AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
  151    WorkspaceSettings,
  152};
  153use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
  154
  155use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::NotificationId};
  156use crate::{
  157    persistence::{
  158        SerializedAxis,
  159        model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
  160    },
  161    security_modal::SecurityModal,
  162};
  163
  164pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  165
  166static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  167    env::var("ZED_WINDOW_SIZE")
  168        .ok()
  169        .as_deref()
  170        .and_then(parse_pixel_size_env_var)
  171});
  172
  173static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  174    env::var("ZED_WINDOW_POSITION")
  175        .ok()
  176        .as_deref()
  177        .and_then(parse_pixel_position_env_var)
  178});
  179
  180pub trait TerminalProvider {
  181    fn spawn(
  182        &self,
  183        task: SpawnInTerminal,
  184        window: &mut Window,
  185        cx: &mut App,
  186    ) -> Task<Option<Result<ExitStatus>>>;
  187}
  188
  189pub trait DebuggerProvider {
  190    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  191    fn start_session(
  192        &self,
  193        definition: DebugScenario,
  194        task_context: SharedTaskContext,
  195        active_buffer: Option<Entity<Buffer>>,
  196        worktree_id: Option<WorktreeId>,
  197        window: &mut Window,
  198        cx: &mut App,
  199    );
  200
  201    fn spawn_task_or_modal(
  202        &self,
  203        workspace: &mut Workspace,
  204        action: &Spawn,
  205        window: &mut Window,
  206        cx: &mut Context<Workspace>,
  207    );
  208
  209    fn task_scheduled(&self, cx: &mut App);
  210    fn debug_scenario_scheduled(&self, cx: &mut App);
  211    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  212
  213    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  214}
  215
  216/// Opens a file or directory.
  217#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  218#[action(namespace = workspace)]
  219pub struct Open {
  220    /// When true, opens in a new window. When false, adds to the current
  221    /// window as a new workspace (multi-workspace).
  222    #[serde(default = "Open::default_create_new_window")]
  223    pub create_new_window: bool,
  224}
  225
  226impl Open {
  227    pub const DEFAULT: Self = Self {
  228        create_new_window: true,
  229    };
  230
  231    /// Used by `#[serde(default)]` on the `create_new_window` field so that
  232    /// the serde default and `Open::DEFAULT` stay in sync.
  233    fn default_create_new_window() -> bool {
  234        Self::DEFAULT.create_new_window
  235    }
  236}
  237
  238impl Default for Open {
  239    fn default() -> Self {
  240        Self::DEFAULT
  241    }
  242}
  243
  244actions!(
  245    workspace,
  246    [
  247        /// Activates the next pane in the workspace.
  248        ActivateNextPane,
  249        /// Activates the previous pane in the workspace.
  250        ActivatePreviousPane,
  251        /// Activates the last pane in the workspace.
  252        ActivateLastPane,
  253        /// Switches to the next window.
  254        ActivateNextWindow,
  255        /// Switches to the previous window.
  256        ActivatePreviousWindow,
  257        /// Adds a folder to the current project.
  258        AddFolderToProject,
  259        /// Clears all notifications.
  260        ClearAllNotifications,
  261        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  262        ClearNavigationHistory,
  263        /// Closes the active dock.
  264        CloseActiveDock,
  265        /// Closes all docks.
  266        CloseAllDocks,
  267        /// Toggles all docks.
  268        ToggleAllDocks,
  269        /// Closes the current window.
  270        CloseWindow,
  271        /// Closes the current project.
  272        CloseProject,
  273        /// Opens the feedback dialog.
  274        Feedback,
  275        /// Follows the next collaborator in the session.
  276        FollowNextCollaborator,
  277        /// Moves the focused panel to the next position.
  278        MoveFocusedPanelToNextPosition,
  279        /// Creates a new file.
  280        NewFile,
  281        /// Creates a new file in a vertical split.
  282        NewFileSplitVertical,
  283        /// Creates a new file in a horizontal split.
  284        NewFileSplitHorizontal,
  285        /// Opens a new search.
  286        NewSearch,
  287        /// Opens a new window.
  288        NewWindow,
  289        /// Opens multiple files.
  290        OpenFiles,
  291        /// Opens the current location in terminal.
  292        OpenInTerminal,
  293        /// Opens the component preview.
  294        OpenComponentPreview,
  295        /// Reloads the active item.
  296        ReloadActiveItem,
  297        /// Resets the active dock to its default size.
  298        ResetActiveDockSize,
  299        /// Resets all open docks to their default sizes.
  300        ResetOpenDocksSize,
  301        /// Reloads the application
  302        Reload,
  303        /// Saves the current file with a new name.
  304        SaveAs,
  305        /// Saves without formatting.
  306        SaveWithoutFormat,
  307        /// Shuts down all debug adapters.
  308        ShutdownDebugAdapters,
  309        /// Suppresses the current notification.
  310        SuppressNotification,
  311        /// Toggles the bottom dock.
  312        ToggleBottomDock,
  313        /// Toggles centered layout mode.
  314        ToggleCenteredLayout,
  315        /// Toggles edit prediction feature globally for all files.
  316        ToggleEditPrediction,
  317        /// Toggles the left dock.
  318        ToggleLeftDock,
  319        /// Toggles the right dock.
  320        ToggleRightDock,
  321        /// Toggles zoom on the active pane.
  322        ToggleZoom,
  323        /// Toggles read-only mode for the active item (if supported by that item).
  324        ToggleReadOnlyFile,
  325        /// Zooms in on the active pane.
  326        ZoomIn,
  327        /// Zooms out of the active pane.
  328        ZoomOut,
  329        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  330        /// If the modal is shown already, closes it without trusting any worktree.
  331        ToggleWorktreeSecurity,
  332        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  333        /// Requires restart to take effect on already opened projects.
  334        ClearTrustedWorktrees,
  335        /// Stops following a collaborator.
  336        Unfollow,
  337        /// Restores the banner.
  338        RestoreBanner,
  339        /// Toggles expansion of the selected item.
  340        ToggleExpandItem,
  341    ]
  342);
  343
  344/// Activates a specific pane by its index.
  345#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  346#[action(namespace = workspace)]
  347pub struct ActivatePane(pub usize);
  348
  349/// Moves an item to a specific pane by index.
  350#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  351#[action(namespace = workspace)]
  352#[serde(deny_unknown_fields)]
  353pub struct MoveItemToPane {
  354    #[serde(default = "default_1")]
  355    pub destination: usize,
  356    #[serde(default = "default_true")]
  357    pub focus: bool,
  358    #[serde(default)]
  359    pub clone: bool,
  360}
  361
  362fn default_1() -> usize {
  363    1
  364}
  365
  366/// Moves an item to a pane in the specified direction.
  367#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  368#[action(namespace = workspace)]
  369#[serde(deny_unknown_fields)]
  370pub struct MoveItemToPaneInDirection {
  371    #[serde(default = "default_right")]
  372    pub direction: SplitDirection,
  373    #[serde(default = "default_true")]
  374    pub focus: bool,
  375    #[serde(default)]
  376    pub clone: bool,
  377}
  378
  379/// Creates a new file in a split of the desired direction.
  380#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  381#[action(namespace = workspace)]
  382#[serde(deny_unknown_fields)]
  383pub struct NewFileSplit(pub SplitDirection);
  384
  385fn default_right() -> SplitDirection {
  386    SplitDirection::Right
  387}
  388
  389/// Saves all open files in the workspace.
  390#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  391#[action(namespace = workspace)]
  392#[serde(deny_unknown_fields)]
  393pub struct SaveAll {
  394    #[serde(default)]
  395    pub save_intent: Option<SaveIntent>,
  396}
  397
  398/// Saves the current file with the specified options.
  399#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  400#[action(namespace = workspace)]
  401#[serde(deny_unknown_fields)]
  402pub struct Save {
  403    #[serde(default)]
  404    pub save_intent: Option<SaveIntent>,
  405}
  406
  407/// Moves Focus to the central panes in the workspace.
  408#[derive(Clone, Debug, PartialEq, Eq, Action)]
  409#[action(namespace = workspace)]
  410pub struct FocusCenterPane;
  411
  412///  Closes all items and panes in the workspace.
  413#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  414#[action(namespace = workspace)]
  415#[serde(deny_unknown_fields)]
  416pub struct CloseAllItemsAndPanes {
  417    #[serde(default)]
  418    pub save_intent: Option<SaveIntent>,
  419}
  420
  421/// Closes all inactive tabs and panes in the workspace.
  422#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  423#[action(namespace = workspace)]
  424#[serde(deny_unknown_fields)]
  425pub struct CloseInactiveTabsAndPanes {
  426    #[serde(default)]
  427    pub save_intent: Option<SaveIntent>,
  428}
  429
  430/// Closes the active item across all panes.
  431#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  432#[action(namespace = workspace)]
  433#[serde(deny_unknown_fields)]
  434pub struct CloseItemInAllPanes {
  435    #[serde(default)]
  436    pub save_intent: Option<SaveIntent>,
  437    #[serde(default)]
  438    pub close_pinned: bool,
  439}
  440
  441/// Sends a sequence of keystrokes to the active element.
  442#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  443#[action(namespace = workspace)]
  444pub struct SendKeystrokes(pub String);
  445
  446actions!(
  447    project_symbols,
  448    [
  449        /// Toggles the project symbols search.
  450        #[action(name = "Toggle")]
  451        ToggleProjectSymbols
  452    ]
  453);
  454
  455/// Toggles the file finder interface.
  456#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  457#[action(namespace = file_finder, name = "Toggle")]
  458#[serde(deny_unknown_fields)]
  459pub struct ToggleFileFinder {
  460    #[serde(default)]
  461    pub separate_history: bool,
  462}
  463
  464/// Opens a new terminal in the center.
  465#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  466#[action(namespace = workspace)]
  467#[serde(deny_unknown_fields)]
  468pub struct NewCenterTerminal {
  469    /// If true, creates a local terminal even in remote projects.
  470    #[serde(default)]
  471    pub local: bool,
  472}
  473
  474/// Opens a new terminal.
  475#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  476#[action(namespace = workspace)]
  477#[serde(deny_unknown_fields)]
  478pub struct NewTerminal {
  479    /// If true, creates a local terminal even in remote projects.
  480    #[serde(default)]
  481    pub local: bool,
  482}
  483
  484/// Increases size of a currently focused dock by a given amount of pixels.
  485#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  486#[action(namespace = workspace)]
  487#[serde(deny_unknown_fields)]
  488pub struct IncreaseActiveDockSize {
  489    /// For 0px parameter, uses UI font size value.
  490    #[serde(default)]
  491    pub px: u32,
  492}
  493
  494/// Decreases size of a currently focused dock by a given amount of pixels.
  495#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  496#[action(namespace = workspace)]
  497#[serde(deny_unknown_fields)]
  498pub struct DecreaseActiveDockSize {
  499    /// For 0px parameter, uses UI font size value.
  500    #[serde(default)]
  501    pub px: u32,
  502}
  503
  504/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  505#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  506#[action(namespace = workspace)]
  507#[serde(deny_unknown_fields)]
  508pub struct IncreaseOpenDocksSize {
  509    /// For 0px parameter, uses UI font size value.
  510    #[serde(default)]
  511    pub px: u32,
  512}
  513
  514/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  515#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  516#[action(namespace = workspace)]
  517#[serde(deny_unknown_fields)]
  518pub struct DecreaseOpenDocksSize {
  519    /// For 0px parameter, uses UI font size value.
  520    #[serde(default)]
  521    pub px: u32,
  522}
  523
  524actions!(
  525    workspace,
  526    [
  527        /// Activates the pane to the left.
  528        ActivatePaneLeft,
  529        /// Activates the pane to the right.
  530        ActivatePaneRight,
  531        /// Activates the pane above.
  532        ActivatePaneUp,
  533        /// Activates the pane below.
  534        ActivatePaneDown,
  535        /// Swaps the current pane with the one to the left.
  536        SwapPaneLeft,
  537        /// Swaps the current pane with the one to the right.
  538        SwapPaneRight,
  539        /// Swaps the current pane with the one above.
  540        SwapPaneUp,
  541        /// Swaps the current pane with the one below.
  542        SwapPaneDown,
  543        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  544        SwapPaneAdjacent,
  545        /// Move the current pane to be at the far left.
  546        MovePaneLeft,
  547        /// Move the current pane to be at the far right.
  548        MovePaneRight,
  549        /// Move the current pane to be at the very top.
  550        MovePaneUp,
  551        /// Move the current pane to be at the very bottom.
  552        MovePaneDown,
  553    ]
  554);
  555
  556#[derive(PartialEq, Eq, Debug)]
  557pub enum CloseIntent {
  558    /// Quit the program entirely.
  559    Quit,
  560    /// Close a window.
  561    CloseWindow,
  562    /// Replace the workspace in an existing window.
  563    ReplaceWindow,
  564}
  565
  566#[derive(Clone)]
  567pub struct Toast {
  568    id: NotificationId,
  569    msg: Cow<'static, str>,
  570    autohide: bool,
  571    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  572}
  573
  574impl Toast {
  575    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  576        Toast {
  577            id,
  578            msg: msg.into(),
  579            on_click: None,
  580            autohide: false,
  581        }
  582    }
  583
  584    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  585    where
  586        M: Into<Cow<'static, str>>,
  587        F: Fn(&mut Window, &mut App) + 'static,
  588    {
  589        self.on_click = Some((message.into(), Arc::new(on_click)));
  590        self
  591    }
  592
  593    pub fn autohide(mut self) -> Self {
  594        self.autohide = true;
  595        self
  596    }
  597}
  598
  599impl PartialEq for Toast {
  600    fn eq(&self, other: &Self) -> bool {
  601        self.id == other.id
  602            && self.msg == other.msg
  603            && self.on_click.is_some() == other.on_click.is_some()
  604    }
  605}
  606
  607/// Opens a new terminal with the specified working directory.
  608#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  609#[action(namespace = workspace)]
  610#[serde(deny_unknown_fields)]
  611pub struct OpenTerminal {
  612    pub working_directory: PathBuf,
  613    /// If true, creates a local terminal even in remote projects.
  614    #[serde(default)]
  615    pub local: bool,
  616}
  617
  618#[derive(
  619    Clone,
  620    Copy,
  621    Debug,
  622    Default,
  623    Hash,
  624    PartialEq,
  625    Eq,
  626    PartialOrd,
  627    Ord,
  628    serde::Serialize,
  629    serde::Deserialize,
  630)]
  631pub struct WorkspaceId(i64);
  632
  633impl WorkspaceId {
  634    pub fn from_i64(value: i64) -> Self {
  635        Self(value)
  636    }
  637}
  638
  639impl StaticColumnCount for WorkspaceId {}
  640impl Bind for WorkspaceId {
  641    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  642        self.0.bind(statement, start_index)
  643    }
  644}
  645impl Column for WorkspaceId {
  646    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  647        i64::column(statement, start_index)
  648            .map(|(i, next_index)| (Self(i), next_index))
  649            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  650    }
  651}
  652impl From<WorkspaceId> for i64 {
  653    fn from(val: WorkspaceId) -> Self {
  654        val.0
  655    }
  656}
  657
  658fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
  659    if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
  660        workspace_window
  661            .update(cx, |multi_workspace, window, cx| {
  662                let workspace = multi_workspace.workspace().clone();
  663                workspace.update(cx, |workspace, cx| {
  664                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  665                });
  666            })
  667            .ok();
  668    } else {
  669        let task = Workspace::new_local(
  670            Vec::new(),
  671            app_state.clone(),
  672            None,
  673            None,
  674            None,
  675            OpenMode::Replace,
  676            cx,
  677        );
  678        cx.spawn(async move |cx| {
  679            let OpenResult { window, .. } = task.await?;
  680            window.update(cx, |multi_workspace, window, cx| {
  681                window.activate_window();
  682                let workspace = multi_workspace.workspace().clone();
  683                workspace.update(cx, |workspace, cx| {
  684                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  685                });
  686            })?;
  687            anyhow::Ok(())
  688        })
  689        .detach_and_log_err(cx);
  690    }
  691}
  692
  693pub fn prompt_for_open_path_and_open(
  694    workspace: &mut Workspace,
  695    app_state: Arc<AppState>,
  696    options: PathPromptOptions,
  697    create_new_window: bool,
  698    window: &mut Window,
  699    cx: &mut Context<Workspace>,
  700) {
  701    let paths = workspace.prompt_for_open_path(
  702        options,
  703        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  704        window,
  705        cx,
  706    );
  707    let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
  708    cx.spawn_in(window, async move |this, cx| {
  709        let Some(paths) = paths.await.log_err().flatten() else {
  710            return;
  711        };
  712        if !create_new_window {
  713            if let Some(handle) = multi_workspace_handle {
  714                if let Some(task) = handle
  715                    .update(cx, |multi_workspace, window, cx| {
  716                        multi_workspace.open_project(paths, OpenMode::Replace, window, cx)
  717                    })
  718                    .log_err()
  719                {
  720                    task.await.log_err();
  721                }
  722                return;
  723            }
  724        }
  725        if let Some(task) = this
  726            .update_in(cx, |this, window, cx| {
  727                this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
  728            })
  729            .log_err()
  730        {
  731            task.await.log_err();
  732        }
  733    })
  734    .detach();
  735}
  736
  737pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  738    component::init();
  739    theme_preview::init(cx);
  740    toast_layer::init(cx);
  741    history_manager::init(app_state.fs.clone(), cx);
  742
  743    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  744        .on_action(|_: &Reload, cx| reload(cx))
  745        .on_action(|_: &Open, cx: &mut App| {
  746            let app_state = AppState::global(cx);
  747            prompt_and_open_paths(
  748                app_state,
  749                PathPromptOptions {
  750                    files: true,
  751                    directories: true,
  752                    multiple: true,
  753                    prompt: None,
  754                },
  755                cx,
  756            );
  757        })
  758        .on_action(|_: &OpenFiles, cx: &mut App| {
  759            let directories = cx.can_select_mixed_files_and_dirs();
  760            let app_state = AppState::global(cx);
  761            prompt_and_open_paths(
  762                app_state,
  763                PathPromptOptions {
  764                    files: true,
  765                    directories,
  766                    multiple: true,
  767                    prompt: None,
  768                },
  769                cx,
  770            );
  771        });
  772}
  773
  774type BuildProjectItemFn =
  775    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  776
  777type BuildProjectItemForPathFn =
  778    fn(
  779        &Entity<Project>,
  780        &ProjectPath,
  781        &mut Window,
  782        &mut App,
  783    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  784
  785#[derive(Clone, Default)]
  786struct ProjectItemRegistry {
  787    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  788    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  789}
  790
  791impl ProjectItemRegistry {
  792    fn register<T: ProjectItem>(&mut self) {
  793        self.build_project_item_fns_by_type.insert(
  794            TypeId::of::<T::Item>(),
  795            |item, project, pane, window, cx| {
  796                let item = item.downcast().unwrap();
  797                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  798                    as Box<dyn ItemHandle>
  799            },
  800        );
  801        self.build_project_item_for_path_fns
  802            .push(|project, project_path, window, cx| {
  803                let project_path = project_path.clone();
  804                let is_file = project
  805                    .read(cx)
  806                    .entry_for_path(&project_path, cx)
  807                    .is_some_and(|entry| entry.is_file());
  808                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  809                let is_local = project.read(cx).is_local();
  810                let project_item =
  811                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  812                let project = project.clone();
  813                Some(window.spawn(cx, async move |cx| {
  814                    match project_item.await.with_context(|| {
  815                        format!(
  816                            "opening project path {:?}",
  817                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  818                        )
  819                    }) {
  820                        Ok(project_item) => {
  821                            let project_item = project_item;
  822                            let project_entry_id: Option<ProjectEntryId> =
  823                                project_item.read_with(cx, project::ProjectItem::entry_id);
  824                            let build_workspace_item = Box::new(
  825                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  826                                    Box::new(cx.new(|cx| {
  827                                        T::for_project_item(
  828                                            project,
  829                                            Some(pane),
  830                                            project_item,
  831                                            window,
  832                                            cx,
  833                                        )
  834                                    })) as Box<dyn ItemHandle>
  835                                },
  836                            ) as Box<_>;
  837                            Ok((project_entry_id, build_workspace_item))
  838                        }
  839                        Err(e) => {
  840                            log::warn!("Failed to open a project item: {e:#}");
  841                            if e.error_code() == ErrorCode::Internal {
  842                                if let Some(abs_path) =
  843                                    entry_abs_path.as_deref().filter(|_| is_file)
  844                                {
  845                                    if let Some(broken_project_item_view) =
  846                                        cx.update(|window, cx| {
  847                                            T::for_broken_project_item(
  848                                                abs_path, is_local, &e, window, cx,
  849                                            )
  850                                        })?
  851                                    {
  852                                        let build_workspace_item = Box::new(
  853                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  854                                                cx.new(|_| broken_project_item_view).boxed_clone()
  855                                            },
  856                                        )
  857                                        as Box<_>;
  858                                        return Ok((None, build_workspace_item));
  859                                    }
  860                                }
  861                            }
  862                            Err(e)
  863                        }
  864                    }
  865                }))
  866            });
  867    }
  868
  869    fn open_path(
  870        &self,
  871        project: &Entity<Project>,
  872        path: &ProjectPath,
  873        window: &mut Window,
  874        cx: &mut App,
  875    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  876        let Some(open_project_item) = self
  877            .build_project_item_for_path_fns
  878            .iter()
  879            .rev()
  880            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  881        else {
  882            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  883        };
  884        open_project_item
  885    }
  886
  887    fn build_item<T: project::ProjectItem>(
  888        &self,
  889        item: Entity<T>,
  890        project: Entity<Project>,
  891        pane: Option<&Pane>,
  892        window: &mut Window,
  893        cx: &mut App,
  894    ) -> Option<Box<dyn ItemHandle>> {
  895        let build = self
  896            .build_project_item_fns_by_type
  897            .get(&TypeId::of::<T>())?;
  898        Some(build(item.into_any(), project, pane, window, cx))
  899    }
  900}
  901
  902type WorkspaceItemBuilder =
  903    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  904
  905impl Global for ProjectItemRegistry {}
  906
  907/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  908/// items will get a chance to open the file, starting from the project item that
  909/// was added last.
  910pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  911    cx.default_global::<ProjectItemRegistry>().register::<I>();
  912}
  913
  914#[derive(Default)]
  915pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  916
  917struct FollowableViewDescriptor {
  918    from_state_proto: fn(
  919        Entity<Workspace>,
  920        ViewId,
  921        &mut Option<proto::view::Variant>,
  922        &mut Window,
  923        &mut App,
  924    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  925    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  926}
  927
  928impl Global for FollowableViewRegistry {}
  929
  930impl FollowableViewRegistry {
  931    pub fn register<I: FollowableItem>(cx: &mut App) {
  932        cx.default_global::<Self>().0.insert(
  933            TypeId::of::<I>(),
  934            FollowableViewDescriptor {
  935                from_state_proto: |workspace, id, state, window, cx| {
  936                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  937                        cx.foreground_executor()
  938                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  939                    })
  940                },
  941                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  942            },
  943        );
  944    }
  945
  946    pub fn from_state_proto(
  947        workspace: Entity<Workspace>,
  948        view_id: ViewId,
  949        mut state: Option<proto::view::Variant>,
  950        window: &mut Window,
  951        cx: &mut App,
  952    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  953        cx.update_default_global(|this: &mut Self, cx| {
  954            this.0.values().find_map(|descriptor| {
  955                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  956            })
  957        })
  958    }
  959
  960    pub fn to_followable_view(
  961        view: impl Into<AnyView>,
  962        cx: &App,
  963    ) -> Option<Box<dyn FollowableItemHandle>> {
  964        let this = cx.try_global::<Self>()?;
  965        let view = view.into();
  966        let descriptor = this.0.get(&view.entity_type())?;
  967        Some((descriptor.to_followable_view)(&view))
  968    }
  969}
  970
  971#[derive(Copy, Clone)]
  972struct SerializableItemDescriptor {
  973    deserialize: fn(
  974        Entity<Project>,
  975        WeakEntity<Workspace>,
  976        WorkspaceId,
  977        ItemId,
  978        &mut Window,
  979        &mut Context<Pane>,
  980    ) -> Task<Result<Box<dyn ItemHandle>>>,
  981    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  982    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  983}
  984
  985#[derive(Default)]
  986struct SerializableItemRegistry {
  987    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  988    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  989}
  990
  991impl Global for SerializableItemRegistry {}
  992
  993impl SerializableItemRegistry {
  994    fn deserialize(
  995        item_kind: &str,
  996        project: Entity<Project>,
  997        workspace: WeakEntity<Workspace>,
  998        workspace_id: WorkspaceId,
  999        item_item: ItemId,
 1000        window: &mut Window,
 1001        cx: &mut Context<Pane>,
 1002    ) -> Task<Result<Box<dyn ItemHandle>>> {
 1003        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1004            return Task::ready(Err(anyhow!(
 1005                "cannot deserialize {}, descriptor not found",
 1006                item_kind
 1007            )));
 1008        };
 1009
 1010        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
 1011    }
 1012
 1013    fn cleanup(
 1014        item_kind: &str,
 1015        workspace_id: WorkspaceId,
 1016        loaded_items: Vec<ItemId>,
 1017        window: &mut Window,
 1018        cx: &mut App,
 1019    ) -> Task<Result<()>> {
 1020        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1021            return Task::ready(Err(anyhow!(
 1022                "cannot cleanup {}, descriptor not found",
 1023                item_kind
 1024            )));
 1025        };
 1026
 1027        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
 1028    }
 1029
 1030    fn view_to_serializable_item_handle(
 1031        view: AnyView,
 1032        cx: &App,
 1033    ) -> Option<Box<dyn SerializableItemHandle>> {
 1034        let this = cx.try_global::<Self>()?;
 1035        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
 1036        Some((descriptor.view_to_serializable_item)(view))
 1037    }
 1038
 1039    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
 1040        let this = cx.try_global::<Self>()?;
 1041        this.descriptors_by_kind.get(item_kind).copied()
 1042    }
 1043}
 1044
 1045pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
 1046    let serialized_item_kind = I::serialized_item_kind();
 1047
 1048    let registry = cx.default_global::<SerializableItemRegistry>();
 1049    let descriptor = SerializableItemDescriptor {
 1050        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
 1051            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
 1052            cx.foreground_executor()
 1053                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 1054        },
 1055        cleanup: |workspace_id, loaded_items, window, cx| {
 1056            I::cleanup(workspace_id, loaded_items, window, cx)
 1057        },
 1058        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1059    };
 1060    registry
 1061        .descriptors_by_kind
 1062        .insert(Arc::from(serialized_item_kind), descriptor);
 1063    registry
 1064        .descriptors_by_type
 1065        .insert(TypeId::of::<I>(), descriptor);
 1066}
 1067
 1068pub struct AppState {
 1069    pub languages: Arc<LanguageRegistry>,
 1070    pub client: Arc<Client>,
 1071    pub user_store: Entity<UserStore>,
 1072    pub workspace_store: Entity<WorkspaceStore>,
 1073    pub fs: Arc<dyn fs::Fs>,
 1074    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1075    pub node_runtime: NodeRuntime,
 1076    pub session: Entity<AppSession>,
 1077}
 1078
 1079struct GlobalAppState(Arc<AppState>);
 1080
 1081impl Global for GlobalAppState {}
 1082
 1083pub struct WorkspaceStore {
 1084    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1085    client: Arc<Client>,
 1086    _subscriptions: Vec<client::Subscription>,
 1087}
 1088
 1089#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1090pub enum CollaboratorId {
 1091    PeerId(PeerId),
 1092    Agent,
 1093}
 1094
 1095impl From<PeerId> for CollaboratorId {
 1096    fn from(peer_id: PeerId) -> Self {
 1097        CollaboratorId::PeerId(peer_id)
 1098    }
 1099}
 1100
 1101impl From<&PeerId> for CollaboratorId {
 1102    fn from(peer_id: &PeerId) -> Self {
 1103        CollaboratorId::PeerId(*peer_id)
 1104    }
 1105}
 1106
 1107#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1108struct Follower {
 1109    project_id: Option<u64>,
 1110    peer_id: PeerId,
 1111}
 1112
 1113impl AppState {
 1114    #[track_caller]
 1115    pub fn global(cx: &App) -> Arc<Self> {
 1116        cx.global::<GlobalAppState>().0.clone()
 1117    }
 1118    pub fn try_global(cx: &App) -> Option<Arc<Self>> {
 1119        cx.try_global::<GlobalAppState>()
 1120            .map(|state| state.0.clone())
 1121    }
 1122    pub fn set_global(state: Arc<AppState>, cx: &mut App) {
 1123        cx.set_global(GlobalAppState(state));
 1124    }
 1125
 1126    #[cfg(any(test, feature = "test-support"))]
 1127    pub fn test(cx: &mut App) -> Arc<Self> {
 1128        use fs::Fs;
 1129        use node_runtime::NodeRuntime;
 1130        use session::Session;
 1131        use settings::SettingsStore;
 1132
 1133        if !cx.has_global::<SettingsStore>() {
 1134            let settings_store = SettingsStore::test(cx);
 1135            cx.set_global(settings_store);
 1136        }
 1137
 1138        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1139        <dyn Fs>::set_global(fs.clone(), cx);
 1140        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1141        let clock = Arc::new(clock::FakeSystemClock::new());
 1142        let http_client = http_client::FakeHttpClient::with_404_response();
 1143        let client = Client::new(clock, http_client, cx);
 1144        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1145        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1146        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1147
 1148        theme_settings::init(theme::LoadThemes::JustBase, cx);
 1149        client::init(&client, cx);
 1150
 1151        Arc::new(Self {
 1152            client,
 1153            fs,
 1154            languages,
 1155            user_store,
 1156            workspace_store,
 1157            node_runtime: NodeRuntime::unavailable(),
 1158            build_window_options: |_, _| Default::default(),
 1159            session,
 1160        })
 1161    }
 1162}
 1163
 1164struct DelayedDebouncedEditAction {
 1165    task: Option<Task<()>>,
 1166    cancel_channel: Option<oneshot::Sender<()>>,
 1167}
 1168
 1169impl DelayedDebouncedEditAction {
 1170    fn new() -> DelayedDebouncedEditAction {
 1171        DelayedDebouncedEditAction {
 1172            task: None,
 1173            cancel_channel: None,
 1174        }
 1175    }
 1176
 1177    fn fire_new<F>(
 1178        &mut self,
 1179        delay: Duration,
 1180        window: &mut Window,
 1181        cx: &mut Context<Workspace>,
 1182        func: F,
 1183    ) where
 1184        F: 'static
 1185            + Send
 1186            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1187    {
 1188        if let Some(channel) = self.cancel_channel.take() {
 1189            _ = channel.send(());
 1190        }
 1191
 1192        let (sender, mut receiver) = oneshot::channel::<()>();
 1193        self.cancel_channel = Some(sender);
 1194
 1195        let previous_task = self.task.take();
 1196        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1197            let mut timer = cx.background_executor().timer(delay).fuse();
 1198            if let Some(previous_task) = previous_task {
 1199                previous_task.await;
 1200            }
 1201
 1202            futures::select_biased! {
 1203                _ = receiver => return,
 1204                    _ = timer => {}
 1205            }
 1206
 1207            if let Some(result) = workspace
 1208                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1209                .log_err()
 1210            {
 1211                result.await.log_err();
 1212            }
 1213        }));
 1214    }
 1215}
 1216
 1217pub enum Event {
 1218    PaneAdded(Entity<Pane>),
 1219    PaneRemoved,
 1220    ItemAdded {
 1221        item: Box<dyn ItemHandle>,
 1222    },
 1223    ActiveItemChanged,
 1224    ItemRemoved {
 1225        item_id: EntityId,
 1226    },
 1227    UserSavedItem {
 1228        pane: WeakEntity<Pane>,
 1229        item: Box<dyn WeakItemHandle>,
 1230        save_intent: SaveIntent,
 1231    },
 1232    ContactRequestedJoin(u64),
 1233    WorkspaceCreated(WeakEntity<Workspace>),
 1234    OpenBundledFile {
 1235        text: Cow<'static, str>,
 1236        title: &'static str,
 1237        language: &'static str,
 1238    },
 1239    ZoomChanged,
 1240    ModalOpened,
 1241    Activate,
 1242    PanelAdded(AnyView),
 1243}
 1244
 1245#[derive(Debug, Clone)]
 1246pub enum OpenVisible {
 1247    All,
 1248    None,
 1249    OnlyFiles,
 1250    OnlyDirectories,
 1251}
 1252
 1253enum WorkspaceLocation {
 1254    // Valid local paths or SSH project to serialize
 1255    Location(SerializedWorkspaceLocation, PathList),
 1256    // No valid location found hence clear session id
 1257    DetachFromSession,
 1258    // No valid location found to serialize
 1259    None,
 1260}
 1261
 1262type PromptForNewPath = Box<
 1263    dyn Fn(
 1264        &mut Workspace,
 1265        DirectoryLister,
 1266        Option<String>,
 1267        &mut Window,
 1268        &mut Context<Workspace>,
 1269    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1270>;
 1271
 1272type PromptForOpenPath = Box<
 1273    dyn Fn(
 1274        &mut Workspace,
 1275        DirectoryLister,
 1276        &mut Window,
 1277        &mut Context<Workspace>,
 1278    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1279>;
 1280
 1281#[derive(Default)]
 1282struct DispatchingKeystrokes {
 1283    dispatched: HashSet<Vec<Keystroke>>,
 1284    queue: VecDeque<Keystroke>,
 1285    task: Option<Shared<Task<()>>>,
 1286}
 1287
 1288/// Collects everything project-related for a certain window opened.
 1289/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1290///
 1291/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1292/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1293/// that can be used to register a global action to be triggered from any place in the window.
 1294pub struct Workspace {
 1295    weak_self: WeakEntity<Self>,
 1296    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1297    zoomed: Option<AnyWeakView>,
 1298    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1299    zoomed_position: Option<DockPosition>,
 1300    center: PaneGroup,
 1301    left_dock: Entity<Dock>,
 1302    bottom_dock: Entity<Dock>,
 1303    right_dock: Entity<Dock>,
 1304    panes: Vec<Entity<Pane>>,
 1305    active_worktree_override: Option<WorktreeId>,
 1306    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1307    active_pane: Entity<Pane>,
 1308    last_active_center_pane: Option<WeakEntity<Pane>>,
 1309    last_active_view_id: Option<proto::ViewId>,
 1310    status_bar: Entity<StatusBar>,
 1311    pub(crate) modal_layer: Entity<ModalLayer>,
 1312    toast_layer: Entity<ToastLayer>,
 1313    titlebar_item: Option<AnyView>,
 1314    notifications: Notifications,
 1315    suppressed_notifications: HashSet<NotificationId>,
 1316    project: Entity<Project>,
 1317    follower_states: HashMap<CollaboratorId, FollowerState>,
 1318    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1319    window_edited: bool,
 1320    last_window_title: Option<String>,
 1321    dirty_items: HashMap<EntityId, Subscription>,
 1322    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1323    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1324    database_id: Option<WorkspaceId>,
 1325    app_state: Arc<AppState>,
 1326    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1327    _subscriptions: Vec<Subscription>,
 1328    _apply_leader_updates: Task<Result<()>>,
 1329    _observe_current_user: Task<Result<()>>,
 1330    _schedule_serialize_workspace: Option<Task<()>>,
 1331    _serialize_workspace_task: Option<Task<()>>,
 1332    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1333    pane_history_timestamp: Arc<AtomicUsize>,
 1334    bounds: Bounds<Pixels>,
 1335    pub centered_layout: bool,
 1336    bounds_save_task_queued: Option<Task<()>>,
 1337    on_prompt_for_new_path: Option<PromptForNewPath>,
 1338    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1339    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1340    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1341    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1342    _items_serializer: Task<Result<()>>,
 1343    session_id: Option<String>,
 1344    scheduled_tasks: Vec<Task<()>>,
 1345    last_open_dock_positions: Vec<DockPosition>,
 1346    removing: bool,
 1347    open_in_dev_container: bool,
 1348    _dev_container_task: Option<Task<Result<()>>>,
 1349    _panels_task: Option<Task<Result<()>>>,
 1350    sidebar_focus_handle: Option<FocusHandle>,
 1351    multi_workspace: Option<WeakEntity<MultiWorkspace>>,
 1352}
 1353
 1354impl EventEmitter<Event> for Workspace {}
 1355
 1356#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1357pub struct ViewId {
 1358    pub creator: CollaboratorId,
 1359    pub id: u64,
 1360}
 1361
 1362pub struct FollowerState {
 1363    center_pane: Entity<Pane>,
 1364    dock_pane: Option<Entity<Pane>>,
 1365    active_view_id: Option<ViewId>,
 1366    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1367}
 1368
 1369struct FollowerView {
 1370    view: Box<dyn FollowableItemHandle>,
 1371    location: Option<proto::PanelId>,
 1372}
 1373
 1374#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
 1375pub enum OpenMode {
 1376    /// Open the workspace in a new window.
 1377    NewWindow,
 1378    /// Add to the window's multi workspace without activating it (used during deserialization).
 1379    Add,
 1380    /// Add to the window's multi workspace and activate it.
 1381    #[default]
 1382    Activate,
 1383    /// Replace the currently active workspace, and any of it's linked workspaces
 1384    Replace,
 1385}
 1386
 1387impl Workspace {
 1388    pub fn new(
 1389        workspace_id: Option<WorkspaceId>,
 1390        project: Entity<Project>,
 1391        app_state: Arc<AppState>,
 1392        window: &mut Window,
 1393        cx: &mut Context<Self>,
 1394    ) -> Self {
 1395        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1396            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1397                if let TrustedWorktreesEvent::Trusted(..) = e {
 1398                    // Do not persist auto trusted worktrees
 1399                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1400                        worktrees_store.update(cx, |worktrees_store, cx| {
 1401                            worktrees_store.schedule_serialization(
 1402                                cx,
 1403                                |new_trusted_worktrees, cx| {
 1404                                    let timeout =
 1405                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1406                                    let db = WorkspaceDb::global(cx);
 1407                                    cx.background_spawn(async move {
 1408                                        timeout.await;
 1409                                        db.save_trusted_worktrees(new_trusted_worktrees)
 1410                                            .await
 1411                                            .log_err();
 1412                                    })
 1413                                },
 1414                            )
 1415                        });
 1416                    }
 1417                }
 1418            })
 1419            .detach();
 1420
 1421            cx.observe_global::<SettingsStore>(|_, cx| {
 1422                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1423                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1424                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1425                            trusted_worktrees.auto_trust_all(cx);
 1426                        })
 1427                    }
 1428                }
 1429            })
 1430            .detach();
 1431        }
 1432
 1433        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1434            match event {
 1435                project::Event::RemoteIdChanged(_) => {
 1436                    this.update_window_title(window, cx);
 1437                }
 1438
 1439                project::Event::CollaboratorLeft(peer_id) => {
 1440                    this.collaborator_left(*peer_id, window, cx);
 1441                }
 1442
 1443                &project::Event::WorktreeRemoved(_) => {
 1444                    this.update_window_title(window, cx);
 1445                    this.serialize_workspace(window, cx);
 1446                    this.update_history(cx);
 1447                }
 1448
 1449                &project::Event::WorktreeAdded(id) => {
 1450                    this.update_window_title(window, cx);
 1451                    if this
 1452                        .project()
 1453                        .read(cx)
 1454                        .worktree_for_id(id, cx)
 1455                        .is_some_and(|wt| wt.read(cx).is_visible())
 1456                    {
 1457                        this.serialize_workspace(window, cx);
 1458                        this.update_history(cx);
 1459                    }
 1460                }
 1461                project::Event::WorktreeUpdatedEntries(..) => {
 1462                    this.update_window_title(window, cx);
 1463                    this.serialize_workspace(window, cx);
 1464                }
 1465
 1466                project::Event::DisconnectedFromHost => {
 1467                    this.update_window_edited(window, cx);
 1468                    let leaders_to_unfollow =
 1469                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1470                    for leader_id in leaders_to_unfollow {
 1471                        this.unfollow(leader_id, window, cx);
 1472                    }
 1473                }
 1474
 1475                project::Event::DisconnectedFromRemote {
 1476                    server_not_running: _,
 1477                } => {
 1478                    this.update_window_edited(window, cx);
 1479                }
 1480
 1481                project::Event::Closed => {
 1482                    window.remove_window();
 1483                }
 1484
 1485                project::Event::DeletedEntry(_, entry_id) => {
 1486                    for pane in this.panes.iter() {
 1487                        pane.update(cx, |pane, cx| {
 1488                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1489                        });
 1490                    }
 1491                }
 1492
 1493                project::Event::Toast {
 1494                    notification_id,
 1495                    message,
 1496                    link,
 1497                } => this.show_notification(
 1498                    NotificationId::named(notification_id.clone()),
 1499                    cx,
 1500                    |cx| {
 1501                        let mut notification = MessageNotification::new(message.clone(), cx);
 1502                        if let Some(link) = link {
 1503                            notification = notification
 1504                                .more_info_message(link.label)
 1505                                .more_info_url(link.url);
 1506                        }
 1507
 1508                        cx.new(|_| notification)
 1509                    },
 1510                ),
 1511
 1512                project::Event::HideToast { notification_id } => {
 1513                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1514                }
 1515
 1516                project::Event::LanguageServerPrompt(request) => {
 1517                    struct LanguageServerPrompt;
 1518
 1519                    this.show_notification(
 1520                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1521                        cx,
 1522                        |cx| {
 1523                            cx.new(|cx| {
 1524                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1525                            })
 1526                        },
 1527                    );
 1528                }
 1529
 1530                project::Event::AgentLocationChanged => {
 1531                    this.handle_agent_location_changed(window, cx)
 1532                }
 1533
 1534                _ => {}
 1535            }
 1536            cx.notify()
 1537        })
 1538        .detach();
 1539
 1540        cx.subscribe_in(
 1541            &project.read(cx).breakpoint_store(),
 1542            window,
 1543            |workspace, _, event, window, cx| match event {
 1544                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1545                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1546                    workspace.serialize_workspace(window, cx);
 1547                }
 1548                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1549            },
 1550        )
 1551        .detach();
 1552        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1553            cx.subscribe_in(
 1554                &toolchain_store,
 1555                window,
 1556                |workspace, _, event, window, cx| match event {
 1557                    ToolchainStoreEvent::CustomToolchainsModified => {
 1558                        workspace.serialize_workspace(window, cx);
 1559                    }
 1560                    _ => {}
 1561                },
 1562            )
 1563            .detach();
 1564        }
 1565
 1566        cx.on_focus_lost(window, |this, window, cx| {
 1567            let focus_handle = this.focus_handle(cx);
 1568            window.focus(&focus_handle, cx);
 1569        })
 1570        .detach();
 1571
 1572        let weak_handle = cx.entity().downgrade();
 1573        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1574
 1575        let center_pane = cx.new(|cx| {
 1576            let mut center_pane = Pane::new(
 1577                weak_handle.clone(),
 1578                project.clone(),
 1579                pane_history_timestamp.clone(),
 1580                None,
 1581                NewFile.boxed_clone(),
 1582                true,
 1583                window,
 1584                cx,
 1585            );
 1586            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1587            center_pane.set_should_display_welcome_page(true);
 1588            center_pane
 1589        });
 1590        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1591            .detach();
 1592
 1593        window.focus(&center_pane.focus_handle(cx), cx);
 1594
 1595        cx.emit(Event::PaneAdded(center_pane.clone()));
 1596
 1597        let any_window_handle = window.window_handle();
 1598        app_state.workspace_store.update(cx, |store, _| {
 1599            store
 1600                .workspaces
 1601                .insert((any_window_handle, weak_handle.clone()));
 1602        });
 1603
 1604        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1605        let mut connection_status = app_state.client.status();
 1606        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1607            current_user.next().await;
 1608            connection_status.next().await;
 1609            let mut stream =
 1610                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1611
 1612            while stream.recv().await.is_some() {
 1613                this.update(cx, |_, cx| cx.notify())?;
 1614            }
 1615            anyhow::Ok(())
 1616        });
 1617
 1618        // All leader updates are enqueued and then processed in a single task, so
 1619        // that each asynchronous operation can be run in order.
 1620        let (leader_updates_tx, mut leader_updates_rx) =
 1621            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1622        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1623            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1624                Self::process_leader_update(&this, leader_id, update, cx)
 1625                    .await
 1626                    .log_err();
 1627            }
 1628
 1629            Ok(())
 1630        });
 1631
 1632        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1633        let modal_layer = cx.new(|_| ModalLayer::new());
 1634        let toast_layer = cx.new(|_| ToastLayer::new());
 1635        cx.subscribe(
 1636            &modal_layer,
 1637            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1638                cx.emit(Event::ModalOpened);
 1639            },
 1640        )
 1641        .detach();
 1642
 1643        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1644        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1645        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1646        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1647        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1648        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1649        let multi_workspace = window
 1650            .root::<MultiWorkspace>()
 1651            .flatten()
 1652            .map(|mw| mw.downgrade());
 1653        let status_bar = cx.new(|cx| {
 1654            let mut status_bar =
 1655                StatusBar::new(&center_pane.clone(), multi_workspace.clone(), window, cx);
 1656            status_bar.add_left_item(left_dock_buttons, window, cx);
 1657            status_bar.add_right_item(right_dock_buttons, window, cx);
 1658            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1659            status_bar
 1660        });
 1661
 1662        let session_id = app_state.session.read(cx).id().to_owned();
 1663
 1664        let mut active_call = None;
 1665        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1666            let subscriptions =
 1667                vec![
 1668                    call.0
 1669                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1670                ];
 1671            active_call = Some((call, subscriptions));
 1672        }
 1673
 1674        let (serializable_items_tx, serializable_items_rx) =
 1675            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1676        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1677            Self::serialize_items(&this, serializable_items_rx, cx).await
 1678        });
 1679
 1680        let subscriptions = vec![
 1681            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1682            cx.observe_window_bounds(window, move |this, window, cx| {
 1683                if this.bounds_save_task_queued.is_some() {
 1684                    return;
 1685                }
 1686                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1687                    cx.background_executor()
 1688                        .timer(Duration::from_millis(100))
 1689                        .await;
 1690                    this.update_in(cx, |this, window, cx| {
 1691                        this.save_window_bounds(window, cx).detach();
 1692                        this.bounds_save_task_queued.take();
 1693                    })
 1694                    .ok();
 1695                }));
 1696                cx.notify();
 1697            }),
 1698            cx.observe_window_appearance(window, |_, window, cx| {
 1699                let window_appearance = window.appearance();
 1700
 1701                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1702
 1703                theme_settings::reload_theme(cx);
 1704                theme_settings::reload_icon_theme(cx);
 1705            }),
 1706            cx.on_release({
 1707                let weak_handle = weak_handle.clone();
 1708                move |this, cx| {
 1709                    this.app_state.workspace_store.update(cx, move |store, _| {
 1710                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1711                    })
 1712                }
 1713            }),
 1714        ];
 1715
 1716        cx.defer_in(window, move |this, window, cx| {
 1717            this.update_window_title(window, cx);
 1718            this.show_initial_notifications(cx);
 1719        });
 1720
 1721        let mut center = PaneGroup::new(center_pane.clone());
 1722        center.set_is_center(true);
 1723        center.mark_positions(cx);
 1724
 1725        Workspace {
 1726            weak_self: weak_handle.clone(),
 1727            zoomed: None,
 1728            zoomed_position: None,
 1729            previous_dock_drag_coordinates: None,
 1730            center,
 1731            panes: vec![center_pane.clone()],
 1732            panes_by_item: Default::default(),
 1733            active_pane: center_pane.clone(),
 1734            last_active_center_pane: Some(center_pane.downgrade()),
 1735            last_active_view_id: None,
 1736            status_bar,
 1737            modal_layer,
 1738            toast_layer,
 1739            titlebar_item: None,
 1740            active_worktree_override: None,
 1741            notifications: Notifications::default(),
 1742            suppressed_notifications: HashSet::default(),
 1743            left_dock,
 1744            bottom_dock,
 1745            right_dock,
 1746            _panels_task: None,
 1747            project: project.clone(),
 1748            follower_states: Default::default(),
 1749            last_leaders_by_pane: Default::default(),
 1750            dispatching_keystrokes: Default::default(),
 1751            window_edited: false,
 1752            last_window_title: None,
 1753            dirty_items: Default::default(),
 1754            active_call,
 1755            database_id: workspace_id,
 1756            app_state,
 1757            _observe_current_user,
 1758            _apply_leader_updates,
 1759            _schedule_serialize_workspace: None,
 1760            _serialize_workspace_task: None,
 1761            _schedule_serialize_ssh_paths: None,
 1762            leader_updates_tx,
 1763            _subscriptions: subscriptions,
 1764            pane_history_timestamp,
 1765            workspace_actions: Default::default(),
 1766            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1767            bounds: Default::default(),
 1768            centered_layout: false,
 1769            bounds_save_task_queued: None,
 1770            on_prompt_for_new_path: None,
 1771            on_prompt_for_open_path: None,
 1772            terminal_provider: None,
 1773            debugger_provider: None,
 1774            serializable_items_tx,
 1775            _items_serializer,
 1776            session_id: Some(session_id),
 1777
 1778            scheduled_tasks: Vec::new(),
 1779            last_open_dock_positions: Vec::new(),
 1780            removing: false,
 1781            sidebar_focus_handle: None,
 1782            multi_workspace,
 1783            open_in_dev_container: false,
 1784            _dev_container_task: None,
 1785        }
 1786    }
 1787
 1788    pub fn new_local(
 1789        abs_paths: Vec<PathBuf>,
 1790        app_state: Arc<AppState>,
 1791        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1792        env: Option<HashMap<String, String>>,
 1793        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1794        open_mode: OpenMode,
 1795        cx: &mut App,
 1796    ) -> Task<anyhow::Result<OpenResult>> {
 1797        let project_handle = Project::local(
 1798            app_state.client.clone(),
 1799            app_state.node_runtime.clone(),
 1800            app_state.user_store.clone(),
 1801            app_state.languages.clone(),
 1802            app_state.fs.clone(),
 1803            env,
 1804            Default::default(),
 1805            cx,
 1806        );
 1807
 1808        let db = WorkspaceDb::global(cx);
 1809        let kvp = db::kvp::KeyValueStore::global(cx);
 1810        cx.spawn(async move |cx| {
 1811            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1812            for path in abs_paths.into_iter() {
 1813                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1814                    paths_to_open.push(canonical)
 1815                } else {
 1816                    paths_to_open.push(path)
 1817                }
 1818            }
 1819
 1820            let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
 1821
 1822            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1823                paths_to_open = paths.ordered_paths().cloned().collect();
 1824                if !paths.is_lexicographically_ordered() {
 1825                    project_handle.update(cx, |project, cx| {
 1826                        project.set_worktrees_reordered(true, cx);
 1827                    });
 1828                }
 1829            }
 1830
 1831            // Get project paths for all of the abs_paths
 1832            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1833                Vec::with_capacity(paths_to_open.len());
 1834
 1835            for path in paths_to_open.into_iter() {
 1836                if let Some((_, project_entry)) = cx
 1837                    .update(|cx| {
 1838                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1839                    })
 1840                    .await
 1841                    .log_err()
 1842                {
 1843                    project_paths.push((path, Some(project_entry)));
 1844                } else {
 1845                    project_paths.push((path, None));
 1846                }
 1847            }
 1848
 1849            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1850                serialized_workspace.id
 1851            } else {
 1852                db.next_id().await.unwrap_or_else(|_| Default::default())
 1853            };
 1854
 1855            let toolchains = db.toolchains(workspace_id).await?;
 1856
 1857            for (toolchain, worktree_path, path) in toolchains {
 1858                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1859                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1860                    this.find_worktree(&worktree_path, cx)
 1861                        .and_then(|(worktree, rel_path)| {
 1862                            if rel_path.is_empty() {
 1863                                Some(worktree.read(cx).id())
 1864                            } else {
 1865                                None
 1866                            }
 1867                        })
 1868                }) else {
 1869                    // We did not find a worktree with a given path, but that's whatever.
 1870                    continue;
 1871                };
 1872                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1873                    continue;
 1874                }
 1875
 1876                project_handle
 1877                    .update(cx, |this, cx| {
 1878                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1879                    })
 1880                    .await;
 1881            }
 1882            if let Some(workspace) = serialized_workspace.as_ref() {
 1883                project_handle.update(cx, |this, cx| {
 1884                    for (scope, toolchains) in &workspace.user_toolchains {
 1885                        for toolchain in toolchains {
 1886                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1887                        }
 1888                    }
 1889                });
 1890            }
 1891
 1892            let window_to_replace = match open_mode {
 1893                OpenMode::NewWindow => None,
 1894                _ => requesting_window,
 1895            };
 1896
 1897            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1898                if let Some(window) = window_to_replace {
 1899                    let centered_layout = serialized_workspace
 1900                        .as_ref()
 1901                        .map(|w| w.centered_layout)
 1902                        .unwrap_or(false);
 1903
 1904                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1905                        let workspace = cx.new(|cx| {
 1906                            let mut workspace = Workspace::new(
 1907                                Some(workspace_id),
 1908                                project_handle.clone(),
 1909                                app_state.clone(),
 1910                                window,
 1911                                cx,
 1912                            );
 1913
 1914                            workspace.centered_layout = centered_layout;
 1915
 1916                            // Call init callback to add items before window renders
 1917                            if let Some(init) = init {
 1918                                init(&mut workspace, window, cx);
 1919                            }
 1920
 1921                            workspace
 1922                        });
 1923                        match open_mode {
 1924                            OpenMode::Replace => {
 1925                                multi_workspace.replace(workspace.clone(), &*window, cx);
 1926                            }
 1927                            OpenMode::Activate => {
 1928                                multi_workspace.activate(workspace.clone(), window, cx);
 1929                            }
 1930                            OpenMode::Add => {
 1931                                multi_workspace.add(workspace.clone(), &*window, cx);
 1932                            }
 1933                            OpenMode::NewWindow => {
 1934                                unreachable!()
 1935                            }
 1936                        }
 1937                        workspace
 1938                    })?;
 1939                    (window, workspace)
 1940                } else {
 1941                    let window_bounds_override = window_bounds_env_override();
 1942
 1943                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1944                        (Some(WindowBounds::Windowed(bounds)), None)
 1945                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1946                        && let Some(display) = workspace.display
 1947                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1948                    {
 1949                        // Reopening an existing workspace - restore its saved bounds
 1950                        (Some(bounds.0), Some(display))
 1951                    } else if let Some((display, bounds)) =
 1952                        persistence::read_default_window_bounds(&kvp)
 1953                    {
 1954                        // New or empty workspace - use the last known window bounds
 1955                        (Some(bounds), Some(display))
 1956                    } else {
 1957                        // New window - let GPUI's default_bounds() handle cascading
 1958                        (None, None)
 1959                    };
 1960
 1961                    // Use the serialized workspace to construct the new window
 1962                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1963                    options.window_bounds = window_bounds;
 1964                    let centered_layout = serialized_workspace
 1965                        .as_ref()
 1966                        .map(|w| w.centered_layout)
 1967                        .unwrap_or(false);
 1968                    let window = cx.open_window(options, {
 1969                        let app_state = app_state.clone();
 1970                        let project_handle = project_handle.clone();
 1971                        move |window, cx| {
 1972                            let workspace = cx.new(|cx| {
 1973                                let mut workspace = Workspace::new(
 1974                                    Some(workspace_id),
 1975                                    project_handle,
 1976                                    app_state,
 1977                                    window,
 1978                                    cx,
 1979                                );
 1980                                workspace.centered_layout = centered_layout;
 1981
 1982                                // Call init callback to add items before window renders
 1983                                if let Some(init) = init {
 1984                                    init(&mut workspace, window, cx);
 1985                                }
 1986
 1987                                workspace
 1988                            });
 1989                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 1990                        }
 1991                    })?;
 1992                    let workspace =
 1993                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 1994                            multi_workspace.workspace().clone()
 1995                        })?;
 1996                    (window, workspace)
 1997                };
 1998
 1999            notify_if_database_failed(window, cx);
 2000            // Check if this is an empty workspace (no paths to open)
 2001            // An empty workspace is one where project_paths is empty
 2002            let is_empty_workspace = project_paths.is_empty();
 2003            // Check if serialized workspace has paths before it's moved
 2004            let serialized_workspace_has_paths = serialized_workspace
 2005                .as_ref()
 2006                .map(|ws| !ws.paths.is_empty())
 2007                .unwrap_or(false);
 2008
 2009            let opened_items = window
 2010                .update(cx, |_, window, cx| {
 2011                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 2012                        open_items(serialized_workspace, project_paths, window, cx)
 2013                    })
 2014                })?
 2015                .await
 2016                .unwrap_or_default();
 2017
 2018            // Restore default dock state for empty workspaces
 2019            // Only restore if:
 2020            // 1. This is an empty workspace (no paths), AND
 2021            // 2. The serialized workspace either doesn't exist or has no paths
 2022            if is_empty_workspace && !serialized_workspace_has_paths {
 2023                if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
 2024                    window
 2025                        .update(cx, |_, window, cx| {
 2026                            workspace.update(cx, |workspace, cx| {
 2027                                for (dock, serialized_dock) in [
 2028                                    (&workspace.right_dock, &default_docks.right),
 2029                                    (&workspace.left_dock, &default_docks.left),
 2030                                    (&workspace.bottom_dock, &default_docks.bottom),
 2031                                ] {
 2032                                    dock.update(cx, |dock, cx| {
 2033                                        dock.serialized_dock = Some(serialized_dock.clone());
 2034                                        dock.restore_state(window, cx);
 2035                                    });
 2036                                }
 2037                                cx.notify();
 2038                            });
 2039                        })
 2040                        .log_err();
 2041                }
 2042            }
 2043
 2044            window
 2045                .update(cx, |_, _window, cx| {
 2046                    workspace.update(cx, |this: &mut Workspace, cx| {
 2047                        this.update_history(cx);
 2048                    });
 2049                })
 2050                .log_err();
 2051            Ok(OpenResult {
 2052                window,
 2053                workspace,
 2054                opened_items,
 2055            })
 2056        })
 2057    }
 2058
 2059    pub fn weak_handle(&self) -> WeakEntity<Self> {
 2060        self.weak_self.clone()
 2061    }
 2062
 2063    pub fn left_dock(&self) -> &Entity<Dock> {
 2064        &self.left_dock
 2065    }
 2066
 2067    pub fn bottom_dock(&self) -> &Entity<Dock> {
 2068        &self.bottom_dock
 2069    }
 2070
 2071    pub fn set_bottom_dock_layout(
 2072        &mut self,
 2073        layout: BottomDockLayout,
 2074        window: &mut Window,
 2075        cx: &mut Context<Self>,
 2076    ) {
 2077        let fs = self.project().read(cx).fs();
 2078        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 2079            content.workspace.bottom_dock_layout = Some(layout);
 2080        });
 2081
 2082        cx.notify();
 2083        self.serialize_workspace(window, cx);
 2084    }
 2085
 2086    pub fn right_dock(&self) -> &Entity<Dock> {
 2087        &self.right_dock
 2088    }
 2089
 2090    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 2091        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 2092    }
 2093
 2094    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 2095        let left_dock = self.left_dock.read(cx);
 2096        let left_visible = left_dock.is_open();
 2097        let left_active_panel = left_dock
 2098            .active_panel()
 2099            .map(|panel| panel.persistent_name().to_string());
 2100        // `zoomed_position` is kept in sync with individual panel zoom state
 2101        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2102        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2103
 2104        let right_dock = self.right_dock.read(cx);
 2105        let right_visible = right_dock.is_open();
 2106        let right_active_panel = right_dock
 2107            .active_panel()
 2108            .map(|panel| panel.persistent_name().to_string());
 2109        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2110
 2111        let bottom_dock = self.bottom_dock.read(cx);
 2112        let bottom_visible = bottom_dock.is_open();
 2113        let bottom_active_panel = bottom_dock
 2114            .active_panel()
 2115            .map(|panel| panel.persistent_name().to_string());
 2116        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2117
 2118        DockStructure {
 2119            left: DockData {
 2120                visible: left_visible,
 2121                active_panel: left_active_panel,
 2122                zoom: left_dock_zoom,
 2123            },
 2124            right: DockData {
 2125                visible: right_visible,
 2126                active_panel: right_active_panel,
 2127                zoom: right_dock_zoom,
 2128            },
 2129            bottom: DockData {
 2130                visible: bottom_visible,
 2131                active_panel: bottom_active_panel,
 2132                zoom: bottom_dock_zoom,
 2133            },
 2134        }
 2135    }
 2136
 2137    pub fn set_dock_structure(
 2138        &self,
 2139        docks: DockStructure,
 2140        window: &mut Window,
 2141        cx: &mut Context<Self>,
 2142    ) {
 2143        for (dock, data) in [
 2144            (&self.left_dock, docks.left),
 2145            (&self.bottom_dock, docks.bottom),
 2146            (&self.right_dock, docks.right),
 2147        ] {
 2148            dock.update(cx, |dock, cx| {
 2149                dock.serialized_dock = Some(data);
 2150                dock.restore_state(window, cx);
 2151            });
 2152        }
 2153    }
 2154
 2155    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2156        self.items(cx)
 2157            .filter_map(|item| {
 2158                let project_path = item.project_path(cx)?;
 2159                self.project.read(cx).absolute_path(&project_path, cx)
 2160            })
 2161            .collect()
 2162    }
 2163
 2164    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2165        match position {
 2166            DockPosition::Left => &self.left_dock,
 2167            DockPosition::Bottom => &self.bottom_dock,
 2168            DockPosition::Right => &self.right_dock,
 2169        }
 2170    }
 2171
 2172    pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
 2173        self.all_docks().into_iter().find_map(|dock| {
 2174            let dock = dock.read(cx);
 2175            dock.has_agent_panel(cx).then_some(dock.position())
 2176        })
 2177    }
 2178
 2179    pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
 2180        self.all_docks().into_iter().find_map(|dock| {
 2181            let dock = dock.read(cx);
 2182            let panel = dock.panel::<T>()?;
 2183            dock.stored_panel_size_state(&panel)
 2184        })
 2185    }
 2186
 2187    pub fn persisted_panel_size_state(
 2188        &self,
 2189        panel_key: &'static str,
 2190        cx: &App,
 2191    ) -> Option<dock::PanelSizeState> {
 2192        dock::Dock::load_persisted_size_state(self, panel_key, cx)
 2193    }
 2194
 2195    pub fn persist_panel_size_state(
 2196        &self,
 2197        panel_key: &str,
 2198        size_state: dock::PanelSizeState,
 2199        cx: &mut App,
 2200    ) {
 2201        let Some(workspace_id) = self
 2202            .database_id()
 2203            .map(|id| i64::from(id).to_string())
 2204            .or(self.session_id())
 2205        else {
 2206            return;
 2207        };
 2208
 2209        let kvp = db::kvp::KeyValueStore::global(cx);
 2210        let panel_key = panel_key.to_string();
 2211        cx.background_spawn(async move {
 2212            let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
 2213            scope
 2214                .write(
 2215                    format!("{workspace_id}:{panel_key}"),
 2216                    serde_json::to_string(&size_state)?,
 2217                )
 2218                .await
 2219        })
 2220        .detach_and_log_err(cx);
 2221    }
 2222
 2223    pub fn set_panel_size_state<T: Panel>(
 2224        &mut self,
 2225        size_state: dock::PanelSizeState,
 2226        window: &mut Window,
 2227        cx: &mut Context<Self>,
 2228    ) -> bool {
 2229        let Some(panel) = self.panel::<T>(cx) else {
 2230            return false;
 2231        };
 2232
 2233        let dock = self.dock_at_position(panel.position(window, cx));
 2234        let did_set = dock.update(cx, |dock, cx| {
 2235            dock.set_panel_size_state(&panel, size_state, cx)
 2236        });
 2237
 2238        if did_set {
 2239            self.persist_panel_size_state(T::panel_key(), size_state, cx);
 2240        }
 2241
 2242        did_set
 2243    }
 2244
 2245    pub fn toggle_dock_panel_flexible_size(
 2246        &self,
 2247        dock: &Entity<Dock>,
 2248        panel: &dyn PanelHandle,
 2249        window: &mut Window,
 2250        cx: &mut App,
 2251    ) {
 2252        let position = dock.read(cx).position();
 2253        let current_size = self.dock_size(&dock.read(cx), window, cx);
 2254        let current_flex =
 2255            current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
 2256        dock.update(cx, |dock, cx| {
 2257            dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
 2258        });
 2259    }
 2260
 2261    fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
 2262        let panel = dock.active_panel()?;
 2263        let size_state = dock
 2264            .stored_panel_size_state(panel.as_ref())
 2265            .unwrap_or_default();
 2266        let position = dock.position();
 2267
 2268        let use_flex = panel.has_flexible_size(window, cx);
 2269
 2270        if position.axis() == Axis::Horizontal
 2271            && use_flex
 2272            && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
 2273        {
 2274            let workspace_width = self.bounds.size.width;
 2275            if workspace_width <= Pixels::ZERO {
 2276                return None;
 2277            }
 2278            let flex = flex.max(0.001);
 2279            let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2280            if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2281                // Both docks are flex items sharing the full workspace width.
 2282                let total_flex = flex + 1.0 + opposite_flex;
 2283                return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
 2284            } else {
 2285                // Opposite dock is fixed-width; flex items share (W - fixed).
 2286                let opposite_fixed = opposite
 2287                    .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2288                    .unwrap_or_default();
 2289                let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
 2290                return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
 2291            }
 2292        }
 2293
 2294        Some(
 2295            size_state
 2296                .size
 2297                .unwrap_or_else(|| panel.default_size(window, cx)),
 2298        )
 2299    }
 2300
 2301    pub fn dock_flex_for_size(
 2302        &self,
 2303        position: DockPosition,
 2304        size: Pixels,
 2305        window: &Window,
 2306        cx: &App,
 2307    ) -> Option<f32> {
 2308        if position.axis() != Axis::Horizontal {
 2309            return None;
 2310        }
 2311
 2312        let workspace_width = self.bounds.size.width;
 2313        if workspace_width <= Pixels::ZERO {
 2314            return None;
 2315        }
 2316
 2317        let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2318        if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2319            let size = size.clamp(px(0.), workspace_width - px(1.));
 2320            Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
 2321        } else {
 2322            let opposite_width = opposite
 2323                .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2324                .unwrap_or_default();
 2325            let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
 2326            let remaining = (available - size).max(px(1.));
 2327            Some((size / remaining).max(0.0))
 2328        }
 2329    }
 2330
 2331    fn opposite_dock_panel_and_size_state(
 2332        &self,
 2333        position: DockPosition,
 2334        window: &Window,
 2335        cx: &App,
 2336    ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
 2337        let opposite_position = match position {
 2338            DockPosition::Left => DockPosition::Right,
 2339            DockPosition::Right => DockPosition::Left,
 2340            DockPosition::Bottom => return None,
 2341        };
 2342
 2343        let opposite_dock = self.dock_at_position(opposite_position).read(cx);
 2344        let panel = opposite_dock.visible_panel()?;
 2345        let mut size_state = opposite_dock
 2346            .stored_panel_size_state(panel.as_ref())
 2347            .unwrap_or_default();
 2348        if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
 2349            size_state.flex = self.default_dock_flex(opposite_position);
 2350        }
 2351        Some((panel.clone(), size_state))
 2352    }
 2353
 2354    pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
 2355        if position.axis() != Axis::Horizontal {
 2356            return None;
 2357        }
 2358
 2359        let pane = self.last_active_center_pane.clone()?.upgrade()?;
 2360        Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
 2361    }
 2362
 2363    pub fn is_edited(&self) -> bool {
 2364        self.window_edited
 2365    }
 2366
 2367    pub fn add_panel<T: Panel>(
 2368        &mut self,
 2369        panel: Entity<T>,
 2370        window: &mut Window,
 2371        cx: &mut Context<Self>,
 2372    ) {
 2373        let focus_handle = panel.panel_focus_handle(cx);
 2374        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2375            .detach();
 2376
 2377        let dock_position = panel.position(window, cx);
 2378        let dock = self.dock_at_position(dock_position);
 2379        let any_panel = panel.to_any();
 2380        let persisted_size_state =
 2381            self.persisted_panel_size_state(T::panel_key(), cx)
 2382                .or_else(|| {
 2383                    load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
 2384                        let state = dock::PanelSizeState {
 2385                            size: Some(size),
 2386                            flex: None,
 2387                        };
 2388                        self.persist_panel_size_state(T::panel_key(), state, cx);
 2389                        state
 2390                    })
 2391                });
 2392
 2393        dock.update(cx, |dock, cx| {
 2394            let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
 2395            if let Some(size_state) = persisted_size_state {
 2396                dock.set_panel_size_state(&panel, size_state, cx);
 2397            }
 2398            index
 2399        });
 2400
 2401        cx.emit(Event::PanelAdded(any_panel));
 2402    }
 2403
 2404    pub fn remove_panel<T: Panel>(
 2405        &mut self,
 2406        panel: &Entity<T>,
 2407        window: &mut Window,
 2408        cx: &mut Context<Self>,
 2409    ) {
 2410        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2411            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2412        }
 2413    }
 2414
 2415    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2416        &self.status_bar
 2417    }
 2418
 2419    pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
 2420        self.sidebar_focus_handle = handle;
 2421    }
 2422
 2423    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2424        StatusBarSettings::get_global(cx).show
 2425    }
 2426
 2427    pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
 2428        self.multi_workspace.as_ref()
 2429    }
 2430
 2431    pub fn set_multi_workspace(
 2432        &mut self,
 2433        multi_workspace: WeakEntity<MultiWorkspace>,
 2434        cx: &mut App,
 2435    ) {
 2436        self.status_bar.update(cx, |status_bar, cx| {
 2437            status_bar.set_multi_workspace(multi_workspace.clone(), cx);
 2438        });
 2439        self.multi_workspace = Some(multi_workspace);
 2440    }
 2441
 2442    pub fn app_state(&self) -> &Arc<AppState> {
 2443        &self.app_state
 2444    }
 2445
 2446    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2447        self._panels_task = Some(task);
 2448    }
 2449
 2450    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2451        self._panels_task.take()
 2452    }
 2453
 2454    pub fn user_store(&self) -> &Entity<UserStore> {
 2455        &self.app_state.user_store
 2456    }
 2457
 2458    pub fn project(&self) -> &Entity<Project> {
 2459        &self.project
 2460    }
 2461
 2462    pub fn path_style(&self, cx: &App) -> PathStyle {
 2463        self.project.read(cx).path_style(cx)
 2464    }
 2465
 2466    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2467        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2468
 2469        for pane_handle in &self.panes {
 2470            let pane = pane_handle.read(cx);
 2471
 2472            for entry in pane.activation_history() {
 2473                history.insert(
 2474                    entry.entity_id,
 2475                    history
 2476                        .get(&entry.entity_id)
 2477                        .cloned()
 2478                        .unwrap_or(0)
 2479                        .max(entry.timestamp),
 2480                );
 2481            }
 2482        }
 2483
 2484        history
 2485    }
 2486
 2487    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2488        let mut recent_item: Option<Entity<T>> = None;
 2489        let mut recent_timestamp = 0;
 2490        for pane_handle in &self.panes {
 2491            let pane = pane_handle.read(cx);
 2492            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2493                pane.items().map(|item| (item.item_id(), item)).collect();
 2494            for entry in pane.activation_history() {
 2495                if entry.timestamp > recent_timestamp
 2496                    && let Some(&item) = item_map.get(&entry.entity_id)
 2497                    && let Some(typed_item) = item.act_as::<T>(cx)
 2498                {
 2499                    recent_timestamp = entry.timestamp;
 2500                    recent_item = Some(typed_item);
 2501                }
 2502            }
 2503        }
 2504        recent_item
 2505    }
 2506
 2507    pub fn recent_navigation_history_iter(
 2508        &self,
 2509        cx: &App,
 2510    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2511        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2512        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2513
 2514        for pane in &self.panes {
 2515            let pane = pane.read(cx);
 2516
 2517            pane.nav_history()
 2518                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2519                    if let Some(fs_path) = &fs_path {
 2520                        abs_paths_opened
 2521                            .entry(fs_path.clone())
 2522                            .or_default()
 2523                            .insert(project_path.clone());
 2524                    }
 2525                    let timestamp = entry.timestamp;
 2526                    match history.entry(project_path) {
 2527                        hash_map::Entry::Occupied(mut entry) => {
 2528                            let (_, old_timestamp) = entry.get();
 2529                            if &timestamp > old_timestamp {
 2530                                entry.insert((fs_path, timestamp));
 2531                            }
 2532                        }
 2533                        hash_map::Entry::Vacant(entry) => {
 2534                            entry.insert((fs_path, timestamp));
 2535                        }
 2536                    }
 2537                });
 2538
 2539            if let Some(item) = pane.active_item()
 2540                && let Some(project_path) = item.project_path(cx)
 2541            {
 2542                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2543
 2544                if let Some(fs_path) = &fs_path {
 2545                    abs_paths_opened
 2546                        .entry(fs_path.clone())
 2547                        .or_default()
 2548                        .insert(project_path.clone());
 2549                }
 2550
 2551                history.insert(project_path, (fs_path, std::usize::MAX));
 2552            }
 2553        }
 2554
 2555        history
 2556            .into_iter()
 2557            .sorted_by_key(|(_, (_, order))| *order)
 2558            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2559            .rev()
 2560            .filter(move |(history_path, abs_path)| {
 2561                let latest_project_path_opened = abs_path
 2562                    .as_ref()
 2563                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2564                    .and_then(|project_paths| {
 2565                        project_paths
 2566                            .iter()
 2567                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2568                    });
 2569
 2570                latest_project_path_opened.is_none_or(|path| path == history_path)
 2571            })
 2572    }
 2573
 2574    pub fn recent_navigation_history(
 2575        &self,
 2576        limit: Option<usize>,
 2577        cx: &App,
 2578    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2579        self.recent_navigation_history_iter(cx)
 2580            .take(limit.unwrap_or(usize::MAX))
 2581            .collect()
 2582    }
 2583
 2584    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2585        for pane in &self.panes {
 2586            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2587        }
 2588    }
 2589
 2590    fn navigate_history(
 2591        &mut self,
 2592        pane: WeakEntity<Pane>,
 2593        mode: NavigationMode,
 2594        window: &mut Window,
 2595        cx: &mut Context<Workspace>,
 2596    ) -> Task<Result<()>> {
 2597        self.navigate_history_impl(
 2598            pane,
 2599            mode,
 2600            window,
 2601            &mut |history, cx| history.pop(mode, cx),
 2602            cx,
 2603        )
 2604    }
 2605
 2606    fn navigate_tag_history(
 2607        &mut self,
 2608        pane: WeakEntity<Pane>,
 2609        mode: TagNavigationMode,
 2610        window: &mut Window,
 2611        cx: &mut Context<Workspace>,
 2612    ) -> Task<Result<()>> {
 2613        self.navigate_history_impl(
 2614            pane,
 2615            NavigationMode::Normal,
 2616            window,
 2617            &mut |history, _cx| history.pop_tag(mode),
 2618            cx,
 2619        )
 2620    }
 2621
 2622    fn navigate_history_impl(
 2623        &mut self,
 2624        pane: WeakEntity<Pane>,
 2625        mode: NavigationMode,
 2626        window: &mut Window,
 2627        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2628        cx: &mut Context<Workspace>,
 2629    ) -> Task<Result<()>> {
 2630        let to_load = if let Some(pane) = pane.upgrade() {
 2631            pane.update(cx, |pane, cx| {
 2632                window.focus(&pane.focus_handle(cx), cx);
 2633                loop {
 2634                    // Retrieve the weak item handle from the history.
 2635                    let entry = cb(pane.nav_history_mut(), cx)?;
 2636
 2637                    // If the item is still present in this pane, then activate it.
 2638                    if let Some(index) = entry
 2639                        .item
 2640                        .upgrade()
 2641                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2642                    {
 2643                        let prev_active_item_index = pane.active_item_index();
 2644                        pane.nav_history_mut().set_mode(mode);
 2645                        pane.activate_item(index, true, true, window, cx);
 2646                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2647
 2648                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2649                        if let Some(data) = entry.data {
 2650                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2651                        }
 2652
 2653                        if navigated {
 2654                            break None;
 2655                        }
 2656                    } else {
 2657                        // If the item is no longer present in this pane, then retrieve its
 2658                        // path info in order to reopen it.
 2659                        break pane
 2660                            .nav_history()
 2661                            .path_for_item(entry.item.id())
 2662                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2663                    }
 2664                }
 2665            })
 2666        } else {
 2667            None
 2668        };
 2669
 2670        if let Some((project_path, abs_path, entry)) = to_load {
 2671            // If the item was no longer present, then load it again from its previous path, first try the local path
 2672            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2673
 2674            cx.spawn_in(window, async move  |workspace, cx| {
 2675                let open_by_project_path = open_by_project_path.await;
 2676                let mut navigated = false;
 2677                match open_by_project_path
 2678                    .with_context(|| format!("Navigating to {project_path:?}"))
 2679                {
 2680                    Ok((project_entry_id, build_item)) => {
 2681                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2682                            pane.nav_history_mut().set_mode(mode);
 2683                            pane.active_item().map(|p| p.item_id())
 2684                        })?;
 2685
 2686                        pane.update_in(cx, |pane, window, cx| {
 2687                            let item = pane.open_item(
 2688                                project_entry_id,
 2689                                project_path,
 2690                                true,
 2691                                entry.is_preview,
 2692                                true,
 2693                                None,
 2694                                window, cx,
 2695                                build_item,
 2696                            );
 2697                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2698                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2699                            if let Some(data) = entry.data {
 2700                                navigated |= item.navigate(data, window, cx);
 2701                            }
 2702                        })?;
 2703                    }
 2704                    Err(open_by_project_path_e) => {
 2705                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2706                        // and its worktree is now dropped
 2707                        if let Some(abs_path) = abs_path {
 2708                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2709                                pane.nav_history_mut().set_mode(mode);
 2710                                pane.active_item().map(|p| p.item_id())
 2711                            })?;
 2712                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2713                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2714                            })?;
 2715                            match open_by_abs_path
 2716                                .await
 2717                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2718                            {
 2719                                Ok(item) => {
 2720                                    pane.update_in(cx, |pane, window, cx| {
 2721                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2722                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2723                                        if let Some(data) = entry.data {
 2724                                            navigated |= item.navigate(data, window, cx);
 2725                                        }
 2726                                    })?;
 2727                                }
 2728                                Err(open_by_abs_path_e) => {
 2729                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2730                                }
 2731                            }
 2732                        }
 2733                    }
 2734                }
 2735
 2736                if !navigated {
 2737                    workspace
 2738                        .update_in(cx, |workspace, window, cx| {
 2739                            Self::navigate_history(workspace, pane, mode, window, cx)
 2740                        })?
 2741                        .await?;
 2742                }
 2743
 2744                Ok(())
 2745            })
 2746        } else {
 2747            Task::ready(Ok(()))
 2748        }
 2749    }
 2750
 2751    pub fn go_back(
 2752        &mut self,
 2753        pane: WeakEntity<Pane>,
 2754        window: &mut Window,
 2755        cx: &mut Context<Workspace>,
 2756    ) -> Task<Result<()>> {
 2757        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2758    }
 2759
 2760    pub fn go_forward(
 2761        &mut self,
 2762        pane: WeakEntity<Pane>,
 2763        window: &mut Window,
 2764        cx: &mut Context<Workspace>,
 2765    ) -> Task<Result<()>> {
 2766        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2767    }
 2768
 2769    pub fn reopen_closed_item(
 2770        &mut self,
 2771        window: &mut Window,
 2772        cx: &mut Context<Workspace>,
 2773    ) -> Task<Result<()>> {
 2774        self.navigate_history(
 2775            self.active_pane().downgrade(),
 2776            NavigationMode::ReopeningClosedItem,
 2777            window,
 2778            cx,
 2779        )
 2780    }
 2781
 2782    pub fn client(&self) -> &Arc<Client> {
 2783        &self.app_state.client
 2784    }
 2785
 2786    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2787        self.titlebar_item = Some(item);
 2788        cx.notify();
 2789    }
 2790
 2791    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2792        self.on_prompt_for_new_path = Some(prompt)
 2793    }
 2794
 2795    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2796        self.on_prompt_for_open_path = Some(prompt)
 2797    }
 2798
 2799    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2800        self.terminal_provider = Some(Box::new(provider));
 2801    }
 2802
 2803    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2804        self.debugger_provider = Some(Arc::new(provider));
 2805    }
 2806
 2807    pub fn set_open_in_dev_container(&mut self, value: bool) {
 2808        self.open_in_dev_container = value;
 2809    }
 2810
 2811    pub fn open_in_dev_container(&self) -> bool {
 2812        self.open_in_dev_container
 2813    }
 2814
 2815    pub fn set_dev_container_task(&mut self, task: Task<Result<()>>) {
 2816        self._dev_container_task = Some(task);
 2817    }
 2818
 2819    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2820        self.debugger_provider.clone()
 2821    }
 2822
 2823    pub fn prompt_for_open_path(
 2824        &mut self,
 2825        path_prompt_options: PathPromptOptions,
 2826        lister: DirectoryLister,
 2827        window: &mut Window,
 2828        cx: &mut Context<Self>,
 2829    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2830        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2831            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2832            let rx = prompt(self, lister, window, cx);
 2833            self.on_prompt_for_open_path = Some(prompt);
 2834            rx
 2835        } else {
 2836            let (tx, rx) = oneshot::channel();
 2837            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2838
 2839            cx.spawn_in(window, async move |workspace, cx| {
 2840                let Ok(result) = abs_path.await else {
 2841                    return Ok(());
 2842                };
 2843
 2844                match result {
 2845                    Ok(result) => {
 2846                        tx.send(result).ok();
 2847                    }
 2848                    Err(err) => {
 2849                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2850                            workspace.show_portal_error(err.to_string(), cx);
 2851                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2852                            let rx = prompt(workspace, lister, window, cx);
 2853                            workspace.on_prompt_for_open_path = Some(prompt);
 2854                            rx
 2855                        })?;
 2856                        if let Ok(path) = rx.await {
 2857                            tx.send(path).ok();
 2858                        }
 2859                    }
 2860                };
 2861                anyhow::Ok(())
 2862            })
 2863            .detach();
 2864
 2865            rx
 2866        }
 2867    }
 2868
 2869    pub fn prompt_for_new_path(
 2870        &mut self,
 2871        lister: DirectoryLister,
 2872        suggested_name: Option<String>,
 2873        window: &mut Window,
 2874        cx: &mut Context<Self>,
 2875    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2876        if self.project.read(cx).is_via_collab()
 2877            || self.project.read(cx).is_via_remote_server()
 2878            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2879        {
 2880            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2881            let rx = prompt(self, lister, suggested_name, window, cx);
 2882            self.on_prompt_for_new_path = Some(prompt);
 2883            return rx;
 2884        }
 2885
 2886        let (tx, rx) = oneshot::channel();
 2887        cx.spawn_in(window, async move |workspace, cx| {
 2888            let abs_path = workspace.update(cx, |workspace, cx| {
 2889                let relative_to = workspace
 2890                    .most_recent_active_path(cx)
 2891                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2892                    .or_else(|| {
 2893                        let project = workspace.project.read(cx);
 2894                        project.visible_worktrees(cx).find_map(|worktree| {
 2895                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2896                        })
 2897                    })
 2898                    .or_else(std::env::home_dir)
 2899                    .unwrap_or_else(|| PathBuf::from(""));
 2900                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2901            })?;
 2902            let abs_path = match abs_path.await? {
 2903                Ok(path) => path,
 2904                Err(err) => {
 2905                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2906                        workspace.show_portal_error(err.to_string(), cx);
 2907
 2908                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2909                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2910                        workspace.on_prompt_for_new_path = Some(prompt);
 2911                        rx
 2912                    })?;
 2913                    if let Ok(path) = rx.await {
 2914                        tx.send(path).ok();
 2915                    }
 2916                    return anyhow::Ok(());
 2917                }
 2918            };
 2919
 2920            tx.send(abs_path.map(|path| vec![path])).ok();
 2921            anyhow::Ok(())
 2922        })
 2923        .detach();
 2924
 2925        rx
 2926    }
 2927
 2928    pub fn titlebar_item(&self) -> Option<AnyView> {
 2929        self.titlebar_item.clone()
 2930    }
 2931
 2932    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2933    /// When set, git-related operations should use this worktree instead of deriving
 2934    /// the active worktree from the focused file.
 2935    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2936        self.active_worktree_override
 2937    }
 2938
 2939    pub fn set_active_worktree_override(
 2940        &mut self,
 2941        worktree_id: Option<WorktreeId>,
 2942        cx: &mut Context<Self>,
 2943    ) {
 2944        self.active_worktree_override = worktree_id;
 2945        cx.notify();
 2946    }
 2947
 2948    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2949        self.active_worktree_override = None;
 2950        cx.notify();
 2951    }
 2952
 2953    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2954    ///
 2955    /// If the given workspace has a local project, then it will be passed
 2956    /// to the callback. Otherwise, a new empty window will be created.
 2957    pub fn with_local_workspace<T, F>(
 2958        &mut self,
 2959        window: &mut Window,
 2960        cx: &mut Context<Self>,
 2961        callback: F,
 2962    ) -> Task<Result<T>>
 2963    where
 2964        T: 'static,
 2965        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2966    {
 2967        if self.project.read(cx).is_local() {
 2968            Task::ready(Ok(callback(self, window, cx)))
 2969        } else {
 2970            let env = self.project.read(cx).cli_environment(cx);
 2971            let task = Self::new_local(
 2972                Vec::new(),
 2973                self.app_state.clone(),
 2974                None,
 2975                env,
 2976                None,
 2977                OpenMode::Activate,
 2978                cx,
 2979            );
 2980            cx.spawn_in(window, async move |_vh, cx| {
 2981                let OpenResult {
 2982                    window: multi_workspace_window,
 2983                    ..
 2984                } = task.await?;
 2985                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2986                    let workspace = multi_workspace.workspace().clone();
 2987                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2988                })
 2989            })
 2990        }
 2991    }
 2992
 2993    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2994    ///
 2995    /// If the given workspace has a local project, then it will be passed
 2996    /// to the callback. Otherwise, a new empty window will be created.
 2997    pub fn with_local_or_wsl_workspace<T, F>(
 2998        &mut self,
 2999        window: &mut Window,
 3000        cx: &mut Context<Self>,
 3001        callback: F,
 3002    ) -> Task<Result<T>>
 3003    where
 3004        T: 'static,
 3005        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 3006    {
 3007        let project = self.project.read(cx);
 3008        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 3009            Task::ready(Ok(callback(self, window, cx)))
 3010        } else {
 3011            let env = self.project.read(cx).cli_environment(cx);
 3012            let task = Self::new_local(
 3013                Vec::new(),
 3014                self.app_state.clone(),
 3015                None,
 3016                env,
 3017                None,
 3018                OpenMode::Activate,
 3019                cx,
 3020            );
 3021            cx.spawn_in(window, async move |_vh, cx| {
 3022                let OpenResult {
 3023                    window: multi_workspace_window,
 3024                    ..
 3025                } = task.await?;
 3026                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 3027                    let workspace = multi_workspace.workspace().clone();
 3028                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 3029                })
 3030            })
 3031        }
 3032    }
 3033
 3034    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3035        self.project.read(cx).worktrees(cx)
 3036    }
 3037
 3038    pub fn visible_worktrees<'a>(
 3039        &self,
 3040        cx: &'a App,
 3041    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3042        self.project.read(cx).visible_worktrees(cx)
 3043    }
 3044
 3045    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 3046        let futures = self
 3047            .worktrees(cx)
 3048            .filter_map(|worktree| worktree.read(cx).as_local())
 3049            .map(|worktree| worktree.scan_complete())
 3050            .collect::<Vec<_>>();
 3051        async move {
 3052            for future in futures {
 3053                future.await;
 3054            }
 3055        }
 3056    }
 3057
 3058    pub fn close_global(cx: &mut App) {
 3059        cx.defer(|cx| {
 3060            cx.windows().iter().find(|window| {
 3061                window
 3062                    .update(cx, |_, window, _| {
 3063                        if window.is_window_active() {
 3064                            //This can only get called when the window's project connection has been lost
 3065                            //so we don't need to prompt the user for anything and instead just close the window
 3066                            window.remove_window();
 3067                            true
 3068                        } else {
 3069                            false
 3070                        }
 3071                    })
 3072                    .unwrap_or(false)
 3073            });
 3074        });
 3075    }
 3076
 3077    pub fn move_focused_panel_to_next_position(
 3078        &mut self,
 3079        _: &MoveFocusedPanelToNextPosition,
 3080        window: &mut Window,
 3081        cx: &mut Context<Self>,
 3082    ) {
 3083        let docks = self.all_docks();
 3084        let active_dock = docks
 3085            .into_iter()
 3086            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 3087
 3088        if let Some(dock) = active_dock {
 3089            dock.update(cx, |dock, cx| {
 3090                let active_panel = dock
 3091                    .active_panel()
 3092                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 3093
 3094                if let Some(panel) = active_panel {
 3095                    panel.move_to_next_position(window, cx);
 3096                }
 3097            })
 3098        }
 3099    }
 3100
 3101    pub fn prepare_to_close(
 3102        &mut self,
 3103        close_intent: CloseIntent,
 3104        window: &mut Window,
 3105        cx: &mut Context<Self>,
 3106    ) -> Task<Result<bool>> {
 3107        let active_call = self.active_global_call();
 3108
 3109        cx.spawn_in(window, async move |this, cx| {
 3110            this.update(cx, |this, _| {
 3111                if close_intent == CloseIntent::CloseWindow {
 3112                    this.removing = true;
 3113                }
 3114            })?;
 3115
 3116            let workspace_count = cx.update(|_window, cx| {
 3117                cx.windows()
 3118                    .iter()
 3119                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 3120                    .count()
 3121            })?;
 3122
 3123            #[cfg(target_os = "macos")]
 3124            let save_last_workspace = false;
 3125
 3126            // On Linux and Windows, closing the last window should restore the last workspace.
 3127            #[cfg(not(target_os = "macos"))]
 3128            let save_last_workspace = {
 3129                let remaining_workspaces = cx.update(|_window, cx| {
 3130                    cx.windows()
 3131                        .iter()
 3132                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 3133                        .filter_map(|multi_workspace| {
 3134                            multi_workspace
 3135                                .update(cx, |multi_workspace, _, cx| {
 3136                                    multi_workspace.workspace().read(cx).removing
 3137                                })
 3138                                .ok()
 3139                        })
 3140                        .filter(|removing| !removing)
 3141                        .count()
 3142                })?;
 3143
 3144                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 3145            };
 3146
 3147            if let Some(active_call) = active_call
 3148                && workspace_count == 1
 3149                && cx
 3150                    .update(|_window, cx| active_call.0.is_in_room(cx))
 3151                    .unwrap_or(false)
 3152            {
 3153                if close_intent == CloseIntent::CloseWindow {
 3154                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3155                    let answer = cx.update(|window, cx| {
 3156                        window.prompt(
 3157                            PromptLevel::Warning,
 3158                            "Do you want to leave the current call?",
 3159                            None,
 3160                            &["Close window and hang up", "Cancel"],
 3161                            cx,
 3162                        )
 3163                    })?;
 3164
 3165                    if answer.await.log_err() == Some(1) {
 3166                        return anyhow::Ok(false);
 3167                    } else {
 3168                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 3169                            task.await.log_err();
 3170                        }
 3171                    }
 3172                }
 3173                if close_intent == CloseIntent::ReplaceWindow {
 3174                    _ = cx.update(|_window, cx| {
 3175                        let multi_workspace = cx
 3176                            .windows()
 3177                            .iter()
 3178                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 3179                            .next()
 3180                            .unwrap();
 3181                        let project = multi_workspace
 3182                            .read(cx)?
 3183                            .workspace()
 3184                            .read(cx)
 3185                            .project
 3186                            .clone();
 3187                        if project.read(cx).is_shared() {
 3188                            active_call.0.unshare_project(project, cx)?;
 3189                        }
 3190                        Ok::<_, anyhow::Error>(())
 3191                    });
 3192                }
 3193            }
 3194
 3195            let save_result = this
 3196                .update_in(cx, |this, window, cx| {
 3197                    this.save_all_internal(SaveIntent::Close, window, cx)
 3198                })?
 3199                .await;
 3200
 3201            // If we're not quitting, but closing, we remove the workspace from
 3202            // the current session.
 3203            if close_intent != CloseIntent::Quit
 3204                && !save_last_workspace
 3205                && save_result.as_ref().is_ok_and(|&res| res)
 3206            {
 3207                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 3208                    .await;
 3209            }
 3210
 3211            save_result
 3212        })
 3213    }
 3214
 3215    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 3216        self.save_all_internal(
 3217            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 3218            window,
 3219            cx,
 3220        )
 3221        .detach_and_log_err(cx);
 3222    }
 3223
 3224    fn send_keystrokes(
 3225        &mut self,
 3226        action: &SendKeystrokes,
 3227        window: &mut Window,
 3228        cx: &mut Context<Self>,
 3229    ) {
 3230        let keystrokes: Vec<Keystroke> = action
 3231            .0
 3232            .split(' ')
 3233            .flat_map(|k| Keystroke::parse(k).log_err())
 3234            .map(|k| {
 3235                cx.keyboard_mapper()
 3236                    .map_key_equivalent(k, false)
 3237                    .inner()
 3238                    .clone()
 3239            })
 3240            .collect();
 3241        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 3242    }
 3243
 3244    pub fn send_keystrokes_impl(
 3245        &mut self,
 3246        keystrokes: Vec<Keystroke>,
 3247        window: &mut Window,
 3248        cx: &mut Context<Self>,
 3249    ) -> Shared<Task<()>> {
 3250        let mut state = self.dispatching_keystrokes.borrow_mut();
 3251        if !state.dispatched.insert(keystrokes.clone()) {
 3252            cx.propagate();
 3253            return state.task.clone().unwrap();
 3254        }
 3255
 3256        state.queue.extend(keystrokes);
 3257
 3258        let keystrokes = self.dispatching_keystrokes.clone();
 3259        if state.task.is_none() {
 3260            state.task = Some(
 3261                window
 3262                    .spawn(cx, async move |cx| {
 3263                        // limit to 100 keystrokes to avoid infinite recursion.
 3264                        for _ in 0..100 {
 3265                            let keystroke = {
 3266                                let mut state = keystrokes.borrow_mut();
 3267                                let Some(keystroke) = state.queue.pop_front() else {
 3268                                    state.dispatched.clear();
 3269                                    state.task.take();
 3270                                    return;
 3271                                };
 3272                                keystroke
 3273                            };
 3274                            cx.update(|window, cx| {
 3275                                let focused = window.focused(cx);
 3276                                window.dispatch_keystroke(keystroke.clone(), cx);
 3277                                if window.focused(cx) != focused {
 3278                                    // dispatch_keystroke may cause the focus to change.
 3279                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3280                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 3281                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 3282                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3283                                    // )
 3284                                    window.draw(cx).clear();
 3285                                }
 3286                            })
 3287                            .ok();
 3288
 3289                            // Yield between synthetic keystrokes so deferred focus and
 3290                            // other effects can settle before dispatching the next key.
 3291                            yield_now().await;
 3292                        }
 3293
 3294                        *keystrokes.borrow_mut() = Default::default();
 3295                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3296                    })
 3297                    .shared(),
 3298            );
 3299        }
 3300        state.task.clone().unwrap()
 3301    }
 3302
 3303    fn save_all_internal(
 3304        &mut self,
 3305        mut save_intent: SaveIntent,
 3306        window: &mut Window,
 3307        cx: &mut Context<Self>,
 3308    ) -> Task<Result<bool>> {
 3309        if self.project.read(cx).is_disconnected(cx) {
 3310            return Task::ready(Ok(true));
 3311        }
 3312        let dirty_items = self
 3313            .panes
 3314            .iter()
 3315            .flat_map(|pane| {
 3316                pane.read(cx).items().filter_map(|item| {
 3317                    if item.is_dirty(cx) {
 3318                        item.tab_content_text(0, cx);
 3319                        Some((pane.downgrade(), item.boxed_clone()))
 3320                    } else {
 3321                        None
 3322                    }
 3323                })
 3324            })
 3325            .collect::<Vec<_>>();
 3326
 3327        let project = self.project.clone();
 3328        cx.spawn_in(window, async move |workspace, cx| {
 3329            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3330                let (serialize_tasks, remaining_dirty_items) =
 3331                    workspace.update_in(cx, |workspace, window, cx| {
 3332                        let mut remaining_dirty_items = Vec::new();
 3333                        let mut serialize_tasks = Vec::new();
 3334                        for (pane, item) in dirty_items {
 3335                            if let Some(task) = item
 3336                                .to_serializable_item_handle(cx)
 3337                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3338                            {
 3339                                serialize_tasks.push(task);
 3340                            } else {
 3341                                remaining_dirty_items.push((pane, item));
 3342                            }
 3343                        }
 3344                        (serialize_tasks, remaining_dirty_items)
 3345                    })?;
 3346
 3347                futures::future::try_join_all(serialize_tasks).await?;
 3348
 3349                if !remaining_dirty_items.is_empty() {
 3350                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3351                }
 3352
 3353                if remaining_dirty_items.len() > 1 {
 3354                    let answer = workspace.update_in(cx, |_, window, cx| {
 3355                        let detail = Pane::file_names_for_prompt(
 3356                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3357                            cx,
 3358                        );
 3359                        window.prompt(
 3360                            PromptLevel::Warning,
 3361                            "Do you want to save all changes in the following files?",
 3362                            Some(&detail),
 3363                            &["Save all", "Discard all", "Cancel"],
 3364                            cx,
 3365                        )
 3366                    })?;
 3367                    match answer.await.log_err() {
 3368                        Some(0) => save_intent = SaveIntent::SaveAll,
 3369                        Some(1) => save_intent = SaveIntent::Skip,
 3370                        Some(2) => return Ok(false),
 3371                        _ => {}
 3372                    }
 3373                }
 3374
 3375                remaining_dirty_items
 3376            } else {
 3377                dirty_items
 3378            };
 3379
 3380            for (pane, item) in dirty_items {
 3381                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3382                    (
 3383                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3384                        item.project_entry_ids(cx),
 3385                    )
 3386                })?;
 3387                if (singleton || !project_entry_ids.is_empty())
 3388                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3389                {
 3390                    return Ok(false);
 3391                }
 3392            }
 3393            Ok(true)
 3394        })
 3395    }
 3396
 3397    pub fn open_workspace_for_paths(
 3398        &mut self,
 3399        // replace_current_window: bool,
 3400        mut open_mode: OpenMode,
 3401        paths: Vec<PathBuf>,
 3402        window: &mut Window,
 3403        cx: &mut Context<Self>,
 3404    ) -> Task<Result<Entity<Workspace>>> {
 3405        let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
 3406        let is_remote = self.project.read(cx).is_via_collab();
 3407        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3408        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3409
 3410        let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
 3411        if workspace_is_empty {
 3412            open_mode = OpenMode::Replace;
 3413        }
 3414
 3415        let app_state = self.app_state.clone();
 3416
 3417        cx.spawn(async move |_, cx| {
 3418            let OpenResult { workspace, .. } = cx
 3419                .update(|cx| {
 3420                    open_paths(
 3421                        &paths,
 3422                        app_state,
 3423                        OpenOptions {
 3424                            requesting_window,
 3425                            open_mode,
 3426                            ..Default::default()
 3427                        },
 3428                        cx,
 3429                    )
 3430                })
 3431                .await?;
 3432            Ok(workspace)
 3433        })
 3434    }
 3435
 3436    #[allow(clippy::type_complexity)]
 3437    pub fn open_paths(
 3438        &mut self,
 3439        mut abs_paths: Vec<PathBuf>,
 3440        options: OpenOptions,
 3441        pane: Option<WeakEntity<Pane>>,
 3442        window: &mut Window,
 3443        cx: &mut Context<Self>,
 3444    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3445        let fs = self.app_state.fs.clone();
 3446
 3447        let caller_ordered_abs_paths = abs_paths.clone();
 3448
 3449        // Sort the paths to ensure we add worktrees for parents before their children.
 3450        abs_paths.sort_unstable();
 3451        cx.spawn_in(window, async move |this, cx| {
 3452            let mut tasks = Vec::with_capacity(abs_paths.len());
 3453
 3454            for abs_path in &abs_paths {
 3455                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3456                    OpenVisible::All => Some(true),
 3457                    OpenVisible::None => Some(false),
 3458                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3459                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3460                        Some(None) => Some(true),
 3461                        None => None,
 3462                    },
 3463                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3464                        Some(Some(metadata)) => Some(metadata.is_dir),
 3465                        Some(None) => Some(false),
 3466                        None => None,
 3467                    },
 3468                };
 3469                let project_path = match visible {
 3470                    Some(visible) => match this
 3471                        .update(cx, |this, cx| {
 3472                            Workspace::project_path_for_path(
 3473                                this.project.clone(),
 3474                                abs_path,
 3475                                visible,
 3476                                cx,
 3477                            )
 3478                        })
 3479                        .log_err()
 3480                    {
 3481                        Some(project_path) => project_path.await.log_err(),
 3482                        None => None,
 3483                    },
 3484                    None => None,
 3485                };
 3486
 3487                let this = this.clone();
 3488                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3489                let fs = fs.clone();
 3490                let pane = pane.clone();
 3491                let task = cx.spawn(async move |cx| {
 3492                    let (_worktree, project_path) = project_path?;
 3493                    if fs.is_dir(&abs_path).await {
 3494                        // Opening a directory should not race to update the active entry.
 3495                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3496                        None
 3497                    } else {
 3498                        Some(
 3499                            this.update_in(cx, |this, window, cx| {
 3500                                this.open_path(
 3501                                    project_path,
 3502                                    pane,
 3503                                    options.focus.unwrap_or(true),
 3504                                    window,
 3505                                    cx,
 3506                                )
 3507                            })
 3508                            .ok()?
 3509                            .await,
 3510                        )
 3511                    }
 3512                });
 3513                tasks.push(task);
 3514            }
 3515
 3516            let results = futures::future::join_all(tasks).await;
 3517
 3518            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3519            let mut winner: Option<(PathBuf, bool)> = None;
 3520            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3521                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3522                    if !metadata.is_dir {
 3523                        winner = Some((abs_path, false));
 3524                        break;
 3525                    }
 3526                    if winner.is_none() {
 3527                        winner = Some((abs_path, true));
 3528                    }
 3529                } else if winner.is_none() {
 3530                    winner = Some((abs_path, false));
 3531                }
 3532            }
 3533
 3534            // Compute the winner entry id on the foreground thread and emit once, after all
 3535            // paths finish opening. This avoids races between concurrently-opening paths
 3536            // (directories in particular) and makes the resulting project panel selection
 3537            // deterministic.
 3538            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3539                'emit_winner: {
 3540                    let winner_abs_path: Arc<Path> =
 3541                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3542
 3543                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3544                        OpenVisible::All => true,
 3545                        OpenVisible::None => false,
 3546                        OpenVisible::OnlyFiles => !winner_is_dir,
 3547                        OpenVisible::OnlyDirectories => winner_is_dir,
 3548                    };
 3549
 3550                    let Some(worktree_task) = this
 3551                        .update(cx, |workspace, cx| {
 3552                            workspace.project.update(cx, |project, cx| {
 3553                                project.find_or_create_worktree(
 3554                                    winner_abs_path.as_ref(),
 3555                                    visible,
 3556                                    cx,
 3557                                )
 3558                            })
 3559                        })
 3560                        .ok()
 3561                    else {
 3562                        break 'emit_winner;
 3563                    };
 3564
 3565                    let Ok((worktree, _)) = worktree_task.await else {
 3566                        break 'emit_winner;
 3567                    };
 3568
 3569                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3570                        let worktree = worktree.read(cx);
 3571                        let worktree_abs_path = worktree.abs_path();
 3572                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3573                            worktree.root_entry()
 3574                        } else {
 3575                            winner_abs_path
 3576                                .strip_prefix(worktree_abs_path.as_ref())
 3577                                .ok()
 3578                                .and_then(|relative_path| {
 3579                                    let relative_path =
 3580                                        RelPath::new(relative_path, PathStyle::local())
 3581                                            .log_err()?;
 3582                                    worktree.entry_for_path(&relative_path)
 3583                                })
 3584                        }?;
 3585                        Some(entry.id)
 3586                    }) else {
 3587                        break 'emit_winner;
 3588                    };
 3589
 3590                    this.update(cx, |workspace, cx| {
 3591                        workspace.project.update(cx, |_, cx| {
 3592                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3593                        });
 3594                    })
 3595                    .ok();
 3596                }
 3597            }
 3598
 3599            results
 3600        })
 3601    }
 3602
 3603    pub fn open_resolved_path(
 3604        &mut self,
 3605        path: ResolvedPath,
 3606        window: &mut Window,
 3607        cx: &mut Context<Self>,
 3608    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3609        match path {
 3610            ResolvedPath::ProjectPath { project_path, .. } => {
 3611                self.open_path(project_path, None, true, window, cx)
 3612            }
 3613            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3614                PathBuf::from(path),
 3615                OpenOptions {
 3616                    visible: Some(OpenVisible::None),
 3617                    ..Default::default()
 3618                },
 3619                window,
 3620                cx,
 3621            ),
 3622        }
 3623    }
 3624
 3625    pub fn absolute_path_of_worktree(
 3626        &self,
 3627        worktree_id: WorktreeId,
 3628        cx: &mut Context<Self>,
 3629    ) -> Option<PathBuf> {
 3630        self.project
 3631            .read(cx)
 3632            .worktree_for_id(worktree_id, cx)
 3633            // TODO: use `abs_path` or `root_dir`
 3634            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3635    }
 3636
 3637    pub fn add_folder_to_project(
 3638        &mut self,
 3639        _: &AddFolderToProject,
 3640        window: &mut Window,
 3641        cx: &mut Context<Self>,
 3642    ) {
 3643        let project = self.project.read(cx);
 3644        if project.is_via_collab() {
 3645            self.show_error(
 3646                &anyhow!("You cannot add folders to someone else's project"),
 3647                cx,
 3648            );
 3649            return;
 3650        }
 3651        let paths = self.prompt_for_open_path(
 3652            PathPromptOptions {
 3653                files: false,
 3654                directories: true,
 3655                multiple: true,
 3656                prompt: None,
 3657            },
 3658            DirectoryLister::Project(self.project.clone()),
 3659            window,
 3660            cx,
 3661        );
 3662        cx.spawn_in(window, async move |this, cx| {
 3663            if let Some(paths) = paths.await.log_err().flatten() {
 3664                let results = this
 3665                    .update_in(cx, |this, window, cx| {
 3666                        this.open_paths(
 3667                            paths,
 3668                            OpenOptions {
 3669                                visible: Some(OpenVisible::All),
 3670                                ..Default::default()
 3671                            },
 3672                            None,
 3673                            window,
 3674                            cx,
 3675                        )
 3676                    })?
 3677                    .await;
 3678                for result in results.into_iter().flatten() {
 3679                    result.log_err();
 3680                }
 3681            }
 3682            anyhow::Ok(())
 3683        })
 3684        .detach_and_log_err(cx);
 3685    }
 3686
 3687    pub fn project_path_for_path(
 3688        project: Entity<Project>,
 3689        abs_path: &Path,
 3690        visible: bool,
 3691        cx: &mut App,
 3692    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3693        let entry = project.update(cx, |project, cx| {
 3694            project.find_or_create_worktree(abs_path, visible, cx)
 3695        });
 3696        cx.spawn(async move |cx| {
 3697            let (worktree, path) = entry.await?;
 3698            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3699            Ok((worktree, ProjectPath { worktree_id, path }))
 3700        })
 3701    }
 3702
 3703    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3704        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3705    }
 3706
 3707    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3708        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3709    }
 3710
 3711    pub fn items_of_type<'a, T: Item>(
 3712        &'a self,
 3713        cx: &'a App,
 3714    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3715        self.panes
 3716            .iter()
 3717            .flat_map(|pane| pane.read(cx).items_of_type())
 3718    }
 3719
 3720    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3721        self.active_pane().read(cx).active_item()
 3722    }
 3723
 3724    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3725        let item = self.active_item(cx)?;
 3726        item.to_any_view().downcast::<I>().ok()
 3727    }
 3728
 3729    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3730        self.active_item(cx).and_then(|item| item.project_path(cx))
 3731    }
 3732
 3733    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3734        self.recent_navigation_history_iter(cx)
 3735            .filter_map(|(path, abs_path)| {
 3736                let worktree = self
 3737                    .project
 3738                    .read(cx)
 3739                    .worktree_for_id(path.worktree_id, cx)?;
 3740                if worktree.read(cx).is_visible() {
 3741                    abs_path
 3742                } else {
 3743                    None
 3744                }
 3745            })
 3746            .next()
 3747    }
 3748
 3749    pub fn save_active_item(
 3750        &mut self,
 3751        save_intent: SaveIntent,
 3752        window: &mut Window,
 3753        cx: &mut App,
 3754    ) -> Task<Result<()>> {
 3755        let project = self.project.clone();
 3756        let pane = self.active_pane();
 3757        let item = pane.read(cx).active_item();
 3758        let pane = pane.downgrade();
 3759
 3760        window.spawn(cx, async move |cx| {
 3761            if let Some(item) = item {
 3762                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3763                    .await
 3764                    .map(|_| ())
 3765            } else {
 3766                Ok(())
 3767            }
 3768        })
 3769    }
 3770
 3771    pub fn close_inactive_items_and_panes(
 3772        &mut self,
 3773        action: &CloseInactiveTabsAndPanes,
 3774        window: &mut Window,
 3775        cx: &mut Context<Self>,
 3776    ) {
 3777        if let Some(task) = self.close_all_internal(
 3778            true,
 3779            action.save_intent.unwrap_or(SaveIntent::Close),
 3780            window,
 3781            cx,
 3782        ) {
 3783            task.detach_and_log_err(cx)
 3784        }
 3785    }
 3786
 3787    pub fn close_all_items_and_panes(
 3788        &mut self,
 3789        action: &CloseAllItemsAndPanes,
 3790        window: &mut Window,
 3791        cx: &mut Context<Self>,
 3792    ) {
 3793        if let Some(task) = self.close_all_internal(
 3794            false,
 3795            action.save_intent.unwrap_or(SaveIntent::Close),
 3796            window,
 3797            cx,
 3798        ) {
 3799            task.detach_and_log_err(cx)
 3800        }
 3801    }
 3802
 3803    /// Closes the active item across all panes.
 3804    pub fn close_item_in_all_panes(
 3805        &mut self,
 3806        action: &CloseItemInAllPanes,
 3807        window: &mut Window,
 3808        cx: &mut Context<Self>,
 3809    ) {
 3810        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3811            return;
 3812        };
 3813
 3814        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3815        let close_pinned = action.close_pinned;
 3816
 3817        if let Some(project_path) = active_item.project_path(cx) {
 3818            self.close_items_with_project_path(
 3819                &project_path,
 3820                save_intent,
 3821                close_pinned,
 3822                window,
 3823                cx,
 3824            );
 3825        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3826            let item_id = active_item.item_id();
 3827            self.active_pane().update(cx, |pane, cx| {
 3828                pane.close_item_by_id(item_id, save_intent, window, cx)
 3829                    .detach_and_log_err(cx);
 3830            });
 3831        }
 3832    }
 3833
 3834    /// Closes all items with the given project path across all panes.
 3835    pub fn close_items_with_project_path(
 3836        &mut self,
 3837        project_path: &ProjectPath,
 3838        save_intent: SaveIntent,
 3839        close_pinned: bool,
 3840        window: &mut Window,
 3841        cx: &mut Context<Self>,
 3842    ) {
 3843        let panes = self.panes().to_vec();
 3844        for pane in panes {
 3845            pane.update(cx, |pane, cx| {
 3846                pane.close_items_for_project_path(
 3847                    project_path,
 3848                    save_intent,
 3849                    close_pinned,
 3850                    window,
 3851                    cx,
 3852                )
 3853                .detach_and_log_err(cx);
 3854            });
 3855        }
 3856    }
 3857
 3858    fn close_all_internal(
 3859        &mut self,
 3860        retain_active_pane: bool,
 3861        save_intent: SaveIntent,
 3862        window: &mut Window,
 3863        cx: &mut Context<Self>,
 3864    ) -> Option<Task<Result<()>>> {
 3865        let current_pane = self.active_pane();
 3866
 3867        let mut tasks = Vec::new();
 3868
 3869        if retain_active_pane {
 3870            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3871                pane.close_other_items(
 3872                    &CloseOtherItems {
 3873                        save_intent: None,
 3874                        close_pinned: false,
 3875                    },
 3876                    None,
 3877                    window,
 3878                    cx,
 3879                )
 3880            });
 3881
 3882            tasks.push(current_pane_close);
 3883        }
 3884
 3885        for pane in self.panes() {
 3886            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3887                continue;
 3888            }
 3889
 3890            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3891                pane.close_all_items(
 3892                    &CloseAllItems {
 3893                        save_intent: Some(save_intent),
 3894                        close_pinned: false,
 3895                    },
 3896                    window,
 3897                    cx,
 3898                )
 3899            });
 3900
 3901            tasks.push(close_pane_items)
 3902        }
 3903
 3904        if tasks.is_empty() {
 3905            None
 3906        } else {
 3907            Some(cx.spawn_in(window, async move |_, _| {
 3908                for task in tasks {
 3909                    task.await?
 3910                }
 3911                Ok(())
 3912            }))
 3913        }
 3914    }
 3915
 3916    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3917        self.dock_at_position(position).read(cx).is_open()
 3918    }
 3919
 3920    pub fn toggle_dock(
 3921        &mut self,
 3922        dock_side: DockPosition,
 3923        window: &mut Window,
 3924        cx: &mut Context<Self>,
 3925    ) {
 3926        let mut focus_center = false;
 3927        let mut reveal_dock = false;
 3928
 3929        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3930        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3931
 3932        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3933            telemetry::event!(
 3934                "Panel Button Clicked",
 3935                name = panel.persistent_name(),
 3936                toggle_state = !was_visible
 3937            );
 3938        }
 3939        if was_visible {
 3940            self.save_open_dock_positions(cx);
 3941        }
 3942
 3943        let dock = self.dock_at_position(dock_side);
 3944        dock.update(cx, |dock, cx| {
 3945            dock.set_open(!was_visible, window, cx);
 3946
 3947            if dock.active_panel().is_none() {
 3948                let Some(panel_ix) = dock
 3949                    .first_enabled_panel_idx(cx)
 3950                    .log_with_level(log::Level::Info)
 3951                else {
 3952                    return;
 3953                };
 3954                dock.activate_panel(panel_ix, window, cx);
 3955            }
 3956
 3957            if let Some(active_panel) = dock.active_panel() {
 3958                if was_visible {
 3959                    if active_panel
 3960                        .panel_focus_handle(cx)
 3961                        .contains_focused(window, cx)
 3962                    {
 3963                        focus_center = true;
 3964                    }
 3965                } else {
 3966                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3967                    window.focus(focus_handle, cx);
 3968                    reveal_dock = true;
 3969                }
 3970            }
 3971        });
 3972
 3973        if reveal_dock {
 3974            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3975        }
 3976
 3977        if focus_center {
 3978            self.active_pane
 3979                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3980        }
 3981
 3982        cx.notify();
 3983        self.serialize_workspace(window, cx);
 3984    }
 3985
 3986    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3987        self.all_docks().into_iter().find(|&dock| {
 3988            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3989        })
 3990    }
 3991
 3992    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3993        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3994            self.save_open_dock_positions(cx);
 3995            dock.update(cx, |dock, cx| {
 3996                dock.set_open(false, window, cx);
 3997            });
 3998            return true;
 3999        }
 4000        false
 4001    }
 4002
 4003    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4004        self.save_open_dock_positions(cx);
 4005        for dock in self.all_docks() {
 4006            dock.update(cx, |dock, cx| {
 4007                dock.set_open(false, window, cx);
 4008            });
 4009        }
 4010
 4011        cx.focus_self(window);
 4012        cx.notify();
 4013        self.serialize_workspace(window, cx);
 4014    }
 4015
 4016    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 4017        self.all_docks()
 4018            .into_iter()
 4019            .filter_map(|dock| {
 4020                let dock_ref = dock.read(cx);
 4021                if dock_ref.is_open() {
 4022                    Some(dock_ref.position())
 4023                } else {
 4024                    None
 4025                }
 4026            })
 4027            .collect()
 4028    }
 4029
 4030    /// Saves the positions of currently open docks.
 4031    ///
 4032    /// Updates `last_open_dock_positions` with positions of all currently open
 4033    /// docks, to later be restored by the 'Toggle All Docks' action.
 4034    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 4035        let open_dock_positions = self.get_open_dock_positions(cx);
 4036        if !open_dock_positions.is_empty() {
 4037            self.last_open_dock_positions = open_dock_positions;
 4038        }
 4039    }
 4040
 4041    /// Toggles all docks between open and closed states.
 4042    ///
 4043    /// If any docks are open, closes all and remembers their positions. If all
 4044    /// docks are closed, restores the last remembered dock configuration.
 4045    fn toggle_all_docks(
 4046        &mut self,
 4047        _: &ToggleAllDocks,
 4048        window: &mut Window,
 4049        cx: &mut Context<Self>,
 4050    ) {
 4051        let open_dock_positions = self.get_open_dock_positions(cx);
 4052
 4053        if !open_dock_positions.is_empty() {
 4054            self.close_all_docks(window, cx);
 4055        } else if !self.last_open_dock_positions.is_empty() {
 4056            self.restore_last_open_docks(window, cx);
 4057        }
 4058    }
 4059
 4060    /// Reopens docks from the most recently remembered configuration.
 4061    ///
 4062    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 4063    /// and clears the stored positions.
 4064    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4065        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 4066
 4067        for position in positions_to_open {
 4068            let dock = self.dock_at_position(position);
 4069            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 4070        }
 4071
 4072        cx.focus_self(window);
 4073        cx.notify();
 4074        self.serialize_workspace(window, cx);
 4075    }
 4076
 4077    /// Transfer focus to the panel of the given type.
 4078    pub fn focus_panel<T: Panel>(
 4079        &mut self,
 4080        window: &mut Window,
 4081        cx: &mut Context<Self>,
 4082    ) -> Option<Entity<T>> {
 4083        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 4084        panel.to_any().downcast().ok()
 4085    }
 4086
 4087    /// Focus the panel of the given type if it isn't already focused. If it is
 4088    /// already focused, then transfer focus back to the workspace center.
 4089    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 4090    /// panel when transferring focus back to the center.
 4091    pub fn toggle_panel_focus<T: Panel>(
 4092        &mut self,
 4093        window: &mut Window,
 4094        cx: &mut Context<Self>,
 4095    ) -> bool {
 4096        let mut did_focus_panel = false;
 4097        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 4098            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 4099            did_focus_panel
 4100        });
 4101
 4102        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 4103            self.close_panel::<T>(window, cx);
 4104        }
 4105
 4106        telemetry::event!(
 4107            "Panel Button Clicked",
 4108            name = T::persistent_name(),
 4109            toggle_state = did_focus_panel
 4110        );
 4111
 4112        did_focus_panel
 4113    }
 4114
 4115    pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4116        if let Some(item) = self.active_item(cx) {
 4117            item.item_focus_handle(cx).focus(window, cx);
 4118        } else {
 4119            log::error!("Could not find a focus target when switching focus to the center panes",);
 4120        }
 4121    }
 4122
 4123    pub fn activate_panel_for_proto_id(
 4124        &mut self,
 4125        panel_id: PanelId,
 4126        window: &mut Window,
 4127        cx: &mut Context<Self>,
 4128    ) -> Option<Arc<dyn PanelHandle>> {
 4129        let mut panel = None;
 4130        for dock in self.all_docks() {
 4131            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 4132                panel = dock.update(cx, |dock, cx| {
 4133                    dock.activate_panel(panel_index, window, cx);
 4134                    dock.set_open(true, window, cx);
 4135                    dock.active_panel().cloned()
 4136                });
 4137                break;
 4138            }
 4139        }
 4140
 4141        if panel.is_some() {
 4142            cx.notify();
 4143            self.serialize_workspace(window, cx);
 4144        }
 4145
 4146        panel
 4147    }
 4148
 4149    /// Focus or unfocus the given panel type, depending on the given callback.
 4150    fn focus_or_unfocus_panel<T: Panel>(
 4151        &mut self,
 4152        window: &mut Window,
 4153        cx: &mut Context<Self>,
 4154        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 4155    ) -> Option<Arc<dyn PanelHandle>> {
 4156        let mut result_panel = None;
 4157        let mut serialize = false;
 4158        for dock in self.all_docks() {
 4159            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4160                let mut focus_center = false;
 4161                let panel = dock.update(cx, |dock, cx| {
 4162                    dock.activate_panel(panel_index, window, cx);
 4163
 4164                    let panel = dock.active_panel().cloned();
 4165                    if let Some(panel) = panel.as_ref() {
 4166                        if should_focus(&**panel, window, cx) {
 4167                            dock.set_open(true, window, cx);
 4168                            panel.panel_focus_handle(cx).focus(window, cx);
 4169                        } else {
 4170                            focus_center = true;
 4171                        }
 4172                    }
 4173                    panel
 4174                });
 4175
 4176                if focus_center {
 4177                    self.active_pane
 4178                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4179                }
 4180
 4181                result_panel = panel;
 4182                serialize = true;
 4183                break;
 4184            }
 4185        }
 4186
 4187        if serialize {
 4188            self.serialize_workspace(window, cx);
 4189        }
 4190
 4191        cx.notify();
 4192        result_panel
 4193    }
 4194
 4195    /// Open the panel of the given type
 4196    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4197        for dock in self.all_docks() {
 4198            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4199                dock.update(cx, |dock, cx| {
 4200                    dock.activate_panel(panel_index, window, cx);
 4201                    dock.set_open(true, window, cx);
 4202                });
 4203            }
 4204        }
 4205    }
 4206
 4207    /// Open the panel of the given type, dismissing any zoomed items that
 4208    /// would obscure it (e.g. a zoomed terminal).
 4209    pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4210        let dock_position = self.all_docks().iter().find_map(|dock| {
 4211            let dock = dock.read(cx);
 4212            dock.panel_index_for_type::<T>().map(|_| dock.position())
 4213        });
 4214        self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
 4215        self.open_panel::<T>(window, cx);
 4216    }
 4217
 4218    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 4219        for dock in self.all_docks().iter() {
 4220            dock.update(cx, |dock, cx| {
 4221                if dock.panel::<T>().is_some() {
 4222                    dock.set_open(false, window, cx)
 4223                }
 4224            })
 4225        }
 4226    }
 4227
 4228    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 4229        self.all_docks()
 4230            .iter()
 4231            .find_map(|dock| dock.read(cx).panel::<T>())
 4232    }
 4233
 4234    fn dismiss_zoomed_items_to_reveal(
 4235        &mut self,
 4236        dock_to_reveal: Option<DockPosition>,
 4237        window: &mut Window,
 4238        cx: &mut Context<Self>,
 4239    ) {
 4240        // If a center pane is zoomed, unzoom it.
 4241        for pane in &self.panes {
 4242            if pane != &self.active_pane || dock_to_reveal.is_some() {
 4243                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4244            }
 4245        }
 4246
 4247        // If another dock is zoomed, hide it.
 4248        let mut focus_center = false;
 4249        for dock in self.all_docks() {
 4250            dock.update(cx, |dock, cx| {
 4251                if Some(dock.position()) != dock_to_reveal
 4252                    && let Some(panel) = dock.active_panel()
 4253                    && panel.is_zoomed(window, cx)
 4254                {
 4255                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 4256                    dock.set_open(false, window, cx);
 4257                }
 4258            });
 4259        }
 4260
 4261        if focus_center {
 4262            self.active_pane
 4263                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4264        }
 4265
 4266        if self.zoomed_position != dock_to_reveal {
 4267            self.zoomed = None;
 4268            self.zoomed_position = None;
 4269            cx.emit(Event::ZoomChanged);
 4270        }
 4271
 4272        cx.notify();
 4273    }
 4274
 4275    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4276        let pane = cx.new(|cx| {
 4277            let mut pane = Pane::new(
 4278                self.weak_handle(),
 4279                self.project.clone(),
 4280                self.pane_history_timestamp.clone(),
 4281                None,
 4282                NewFile.boxed_clone(),
 4283                true,
 4284                window,
 4285                cx,
 4286            );
 4287            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4288            pane
 4289        });
 4290        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4291            .detach();
 4292        self.panes.push(pane.clone());
 4293
 4294        window.focus(&pane.focus_handle(cx), cx);
 4295
 4296        cx.emit(Event::PaneAdded(pane.clone()));
 4297        pane
 4298    }
 4299
 4300    pub fn add_item_to_center(
 4301        &mut self,
 4302        item: Box<dyn ItemHandle>,
 4303        window: &mut Window,
 4304        cx: &mut Context<Self>,
 4305    ) -> bool {
 4306        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4307            if let Some(center_pane) = center_pane.upgrade() {
 4308                center_pane.update(cx, |pane, cx| {
 4309                    pane.add_item(item, true, true, None, window, cx)
 4310                });
 4311                true
 4312            } else {
 4313                false
 4314            }
 4315        } else {
 4316            false
 4317        }
 4318    }
 4319
 4320    pub fn add_item_to_active_pane(
 4321        &mut self,
 4322        item: Box<dyn ItemHandle>,
 4323        destination_index: Option<usize>,
 4324        focus_item: bool,
 4325        window: &mut Window,
 4326        cx: &mut App,
 4327    ) {
 4328        self.add_item(
 4329            self.active_pane.clone(),
 4330            item,
 4331            destination_index,
 4332            false,
 4333            focus_item,
 4334            window,
 4335            cx,
 4336        )
 4337    }
 4338
 4339    pub fn add_item(
 4340        &mut self,
 4341        pane: Entity<Pane>,
 4342        item: Box<dyn ItemHandle>,
 4343        destination_index: Option<usize>,
 4344        activate_pane: bool,
 4345        focus_item: bool,
 4346        window: &mut Window,
 4347        cx: &mut App,
 4348    ) {
 4349        pane.update(cx, |pane, cx| {
 4350            pane.add_item(
 4351                item,
 4352                activate_pane,
 4353                focus_item,
 4354                destination_index,
 4355                window,
 4356                cx,
 4357            )
 4358        });
 4359    }
 4360
 4361    pub fn split_item(
 4362        &mut self,
 4363        split_direction: SplitDirection,
 4364        item: Box<dyn ItemHandle>,
 4365        window: &mut Window,
 4366        cx: &mut Context<Self>,
 4367    ) {
 4368        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4369        self.add_item(new_pane, item, None, true, true, window, cx);
 4370    }
 4371
 4372    pub fn open_abs_path(
 4373        &mut self,
 4374        abs_path: PathBuf,
 4375        options: OpenOptions,
 4376        window: &mut Window,
 4377        cx: &mut Context<Self>,
 4378    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4379        cx.spawn_in(window, async move |workspace, cx| {
 4380            let open_paths_task_result = workspace
 4381                .update_in(cx, |workspace, window, cx| {
 4382                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4383                })
 4384                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4385                .await;
 4386            anyhow::ensure!(
 4387                open_paths_task_result.len() == 1,
 4388                "open abs path {abs_path:?} task returned incorrect number of results"
 4389            );
 4390            match open_paths_task_result
 4391                .into_iter()
 4392                .next()
 4393                .expect("ensured single task result")
 4394            {
 4395                Some(open_result) => {
 4396                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4397                }
 4398                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4399            }
 4400        })
 4401    }
 4402
 4403    pub fn split_abs_path(
 4404        &mut self,
 4405        abs_path: PathBuf,
 4406        visible: bool,
 4407        window: &mut Window,
 4408        cx: &mut Context<Self>,
 4409    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4410        let project_path_task =
 4411            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4412        cx.spawn_in(window, async move |this, cx| {
 4413            let (_, path) = project_path_task.await?;
 4414            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4415                .await
 4416        })
 4417    }
 4418
 4419    pub fn open_path(
 4420        &mut self,
 4421        path: impl Into<ProjectPath>,
 4422        pane: Option<WeakEntity<Pane>>,
 4423        focus_item: bool,
 4424        window: &mut Window,
 4425        cx: &mut App,
 4426    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4427        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4428    }
 4429
 4430    pub fn open_path_preview(
 4431        &mut self,
 4432        path: impl Into<ProjectPath>,
 4433        pane: Option<WeakEntity<Pane>>,
 4434        focus_item: bool,
 4435        allow_preview: bool,
 4436        activate: bool,
 4437        window: &mut Window,
 4438        cx: &mut App,
 4439    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4440        let pane = pane.unwrap_or_else(|| {
 4441            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4442                self.panes
 4443                    .first()
 4444                    .expect("There must be an active pane")
 4445                    .downgrade()
 4446            })
 4447        });
 4448
 4449        let project_path = path.into();
 4450        let task = self.load_path(project_path.clone(), window, cx);
 4451        window.spawn(cx, async move |cx| {
 4452            let (project_entry_id, build_item) = task.await?;
 4453
 4454            pane.update_in(cx, |pane, window, cx| {
 4455                pane.open_item(
 4456                    project_entry_id,
 4457                    project_path,
 4458                    focus_item,
 4459                    allow_preview,
 4460                    activate,
 4461                    None,
 4462                    window,
 4463                    cx,
 4464                    build_item,
 4465                )
 4466            })
 4467        })
 4468    }
 4469
 4470    pub fn split_path(
 4471        &mut self,
 4472        path: impl Into<ProjectPath>,
 4473        window: &mut Window,
 4474        cx: &mut Context<Self>,
 4475    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4476        self.split_path_preview(path, false, None, window, cx)
 4477    }
 4478
 4479    pub fn split_path_preview(
 4480        &mut self,
 4481        path: impl Into<ProjectPath>,
 4482        allow_preview: bool,
 4483        split_direction: Option<SplitDirection>,
 4484        window: &mut Window,
 4485        cx: &mut Context<Self>,
 4486    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4487        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4488            self.panes
 4489                .first()
 4490                .expect("There must be an active pane")
 4491                .downgrade()
 4492        });
 4493
 4494        if let Member::Pane(center_pane) = &self.center.root
 4495            && center_pane.read(cx).items_len() == 0
 4496        {
 4497            return self.open_path(path, Some(pane), true, window, cx);
 4498        }
 4499
 4500        let project_path = path.into();
 4501        let task = self.load_path(project_path.clone(), window, cx);
 4502        cx.spawn_in(window, async move |this, cx| {
 4503            let (project_entry_id, build_item) = task.await?;
 4504            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4505                let pane = pane.upgrade()?;
 4506                let new_pane = this.split_pane(
 4507                    pane,
 4508                    split_direction.unwrap_or(SplitDirection::Right),
 4509                    window,
 4510                    cx,
 4511                );
 4512                new_pane.update(cx, |new_pane, cx| {
 4513                    Some(new_pane.open_item(
 4514                        project_entry_id,
 4515                        project_path,
 4516                        true,
 4517                        allow_preview,
 4518                        true,
 4519                        None,
 4520                        window,
 4521                        cx,
 4522                        build_item,
 4523                    ))
 4524                })
 4525            })
 4526            .map(|option| option.context("pane was dropped"))?
 4527        })
 4528    }
 4529
 4530    fn load_path(
 4531        &mut self,
 4532        path: ProjectPath,
 4533        window: &mut Window,
 4534        cx: &mut App,
 4535    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4536        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4537        registry.open_path(self.project(), &path, window, cx)
 4538    }
 4539
 4540    pub fn find_project_item<T>(
 4541        &self,
 4542        pane: &Entity<Pane>,
 4543        project_item: &Entity<T::Item>,
 4544        cx: &App,
 4545    ) -> Option<Entity<T>>
 4546    where
 4547        T: ProjectItem,
 4548    {
 4549        use project::ProjectItem as _;
 4550        let project_item = project_item.read(cx);
 4551        let entry_id = project_item.entry_id(cx);
 4552        let project_path = project_item.project_path(cx);
 4553
 4554        let mut item = None;
 4555        if let Some(entry_id) = entry_id {
 4556            item = pane.read(cx).item_for_entry(entry_id, cx);
 4557        }
 4558        if item.is_none()
 4559            && let Some(project_path) = project_path
 4560        {
 4561            item = pane.read(cx).item_for_path(project_path, cx);
 4562        }
 4563
 4564        item.and_then(|item| item.downcast::<T>())
 4565    }
 4566
 4567    pub fn is_project_item_open<T>(
 4568        &self,
 4569        pane: &Entity<Pane>,
 4570        project_item: &Entity<T::Item>,
 4571        cx: &App,
 4572    ) -> bool
 4573    where
 4574        T: ProjectItem,
 4575    {
 4576        self.find_project_item::<T>(pane, project_item, cx)
 4577            .is_some()
 4578    }
 4579
 4580    pub fn open_project_item<T>(
 4581        &mut self,
 4582        pane: Entity<Pane>,
 4583        project_item: Entity<T::Item>,
 4584        activate_pane: bool,
 4585        focus_item: bool,
 4586        keep_old_preview: bool,
 4587        allow_new_preview: bool,
 4588        window: &mut Window,
 4589        cx: &mut Context<Self>,
 4590    ) -> Entity<T>
 4591    where
 4592        T: ProjectItem,
 4593    {
 4594        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4595
 4596        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4597            if !keep_old_preview
 4598                && let Some(old_id) = old_item_id
 4599                && old_id != item.item_id()
 4600            {
 4601                // switching to a different item, so unpreview old active item
 4602                pane.update(cx, |pane, _| {
 4603                    pane.unpreview_item_if_preview(old_id);
 4604                });
 4605            }
 4606
 4607            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4608            if !allow_new_preview {
 4609                pane.update(cx, |pane, _| {
 4610                    pane.unpreview_item_if_preview(item.item_id());
 4611                });
 4612            }
 4613            return item;
 4614        }
 4615
 4616        let item = pane.update(cx, |pane, cx| {
 4617            cx.new(|cx| {
 4618                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4619            })
 4620        });
 4621        let mut destination_index = None;
 4622        pane.update(cx, |pane, cx| {
 4623            if !keep_old_preview && let Some(old_id) = old_item_id {
 4624                pane.unpreview_item_if_preview(old_id);
 4625            }
 4626            if allow_new_preview {
 4627                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4628            }
 4629        });
 4630
 4631        self.add_item(
 4632            pane,
 4633            Box::new(item.clone()),
 4634            destination_index,
 4635            activate_pane,
 4636            focus_item,
 4637            window,
 4638            cx,
 4639        );
 4640        item
 4641    }
 4642
 4643    pub fn open_shared_screen(
 4644        &mut self,
 4645        peer_id: PeerId,
 4646        window: &mut Window,
 4647        cx: &mut Context<Self>,
 4648    ) {
 4649        if let Some(shared_screen) =
 4650            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4651        {
 4652            self.active_pane.update(cx, |pane, cx| {
 4653                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4654            });
 4655        }
 4656    }
 4657
 4658    pub fn activate_item(
 4659        &mut self,
 4660        item: &dyn ItemHandle,
 4661        activate_pane: bool,
 4662        focus_item: bool,
 4663        window: &mut Window,
 4664        cx: &mut App,
 4665    ) -> bool {
 4666        let result = self.panes.iter().find_map(|pane| {
 4667            pane.read(cx)
 4668                .index_for_item(item)
 4669                .map(|ix| (pane.clone(), ix))
 4670        });
 4671        if let Some((pane, ix)) = result {
 4672            pane.update(cx, |pane, cx| {
 4673                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4674            });
 4675            true
 4676        } else {
 4677            false
 4678        }
 4679    }
 4680
 4681    fn activate_pane_at_index(
 4682        &mut self,
 4683        action: &ActivatePane,
 4684        window: &mut Window,
 4685        cx: &mut Context<Self>,
 4686    ) {
 4687        let panes = self.center.panes();
 4688        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4689            window.focus(&pane.focus_handle(cx), cx);
 4690        } else {
 4691            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4692                .detach();
 4693        }
 4694    }
 4695
 4696    fn move_item_to_pane_at_index(
 4697        &mut self,
 4698        action: &MoveItemToPane,
 4699        window: &mut Window,
 4700        cx: &mut Context<Self>,
 4701    ) {
 4702        let panes = self.center.panes();
 4703        let destination = match panes.get(action.destination) {
 4704            Some(&destination) => destination.clone(),
 4705            None => {
 4706                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4707                    return;
 4708                }
 4709                let direction = SplitDirection::Right;
 4710                let split_off_pane = self
 4711                    .find_pane_in_direction(direction, cx)
 4712                    .unwrap_or_else(|| self.active_pane.clone());
 4713                let new_pane = self.add_pane(window, cx);
 4714                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4715                new_pane
 4716            }
 4717        };
 4718
 4719        if action.clone {
 4720            if self
 4721                .active_pane
 4722                .read(cx)
 4723                .active_item()
 4724                .is_some_and(|item| item.can_split(cx))
 4725            {
 4726                clone_active_item(
 4727                    self.database_id(),
 4728                    &self.active_pane,
 4729                    &destination,
 4730                    action.focus,
 4731                    window,
 4732                    cx,
 4733                );
 4734                return;
 4735            }
 4736        }
 4737        move_active_item(
 4738            &self.active_pane,
 4739            &destination,
 4740            action.focus,
 4741            true,
 4742            window,
 4743            cx,
 4744        )
 4745    }
 4746
 4747    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4748        let panes = self.center.panes();
 4749        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4750            let next_ix = (ix + 1) % panes.len();
 4751            let next_pane = panes[next_ix].clone();
 4752            window.focus(&next_pane.focus_handle(cx), cx);
 4753        }
 4754    }
 4755
 4756    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4757        let panes = self.center.panes();
 4758        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4759            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4760            let prev_pane = panes[prev_ix].clone();
 4761            window.focus(&prev_pane.focus_handle(cx), cx);
 4762        }
 4763    }
 4764
 4765    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4766        let last_pane = self.center.last_pane();
 4767        window.focus(&last_pane.focus_handle(cx), cx);
 4768    }
 4769
 4770    pub fn activate_pane_in_direction(
 4771        &mut self,
 4772        direction: SplitDirection,
 4773        window: &mut Window,
 4774        cx: &mut App,
 4775    ) {
 4776        use ActivateInDirectionTarget as Target;
 4777        enum Origin {
 4778            Sidebar,
 4779            LeftDock,
 4780            RightDock,
 4781            BottomDock,
 4782            Center,
 4783        }
 4784
 4785        let origin: Origin = if self
 4786            .sidebar_focus_handle
 4787            .as_ref()
 4788            .is_some_and(|h| h.contains_focused(window, cx))
 4789        {
 4790            Origin::Sidebar
 4791        } else {
 4792            [
 4793                (&self.left_dock, Origin::LeftDock),
 4794                (&self.right_dock, Origin::RightDock),
 4795                (&self.bottom_dock, Origin::BottomDock),
 4796            ]
 4797            .into_iter()
 4798            .find_map(|(dock, origin)| {
 4799                if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4800                    Some(origin)
 4801                } else {
 4802                    None
 4803                }
 4804            })
 4805            .unwrap_or(Origin::Center)
 4806        };
 4807
 4808        let get_last_active_pane = || {
 4809            let pane = self
 4810                .last_active_center_pane
 4811                .clone()
 4812                .unwrap_or_else(|| {
 4813                    self.panes
 4814                        .first()
 4815                        .expect("There must be an active pane")
 4816                        .downgrade()
 4817                })
 4818                .upgrade()?;
 4819            (pane.read(cx).items_len() != 0).then_some(pane)
 4820        };
 4821
 4822        let try_dock =
 4823            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4824
 4825        let sidebar_target = self
 4826            .sidebar_focus_handle
 4827            .as_ref()
 4828            .map(|h| Target::Sidebar(h.clone()));
 4829
 4830        let target = match (origin, direction) {
 4831            // From the sidebar, only Right navigates into the workspace.
 4832            (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
 4833                .or_else(|| get_last_active_pane().map(Target::Pane))
 4834                .or_else(|| try_dock(&self.bottom_dock))
 4835                .or_else(|| try_dock(&self.right_dock)),
 4836
 4837            (Origin::Sidebar, _) => None,
 4838
 4839            // We're in the center, so we first try to go to a different pane,
 4840            // otherwise try to go to a dock.
 4841            (Origin::Center, direction) => {
 4842                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4843                    Some(Target::Pane(pane))
 4844                } else {
 4845                    match direction {
 4846                        SplitDirection::Up => None,
 4847                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4848                        SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
 4849                        SplitDirection::Right => try_dock(&self.right_dock),
 4850                    }
 4851                }
 4852            }
 4853
 4854            (Origin::LeftDock, SplitDirection::Right) => {
 4855                if let Some(last_active_pane) = get_last_active_pane() {
 4856                    Some(Target::Pane(last_active_pane))
 4857                } else {
 4858                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4859                }
 4860            }
 4861
 4862            (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
 4863
 4864            (Origin::LeftDock, SplitDirection::Down)
 4865            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4866
 4867            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4868            (Origin::BottomDock, SplitDirection::Left) => {
 4869                try_dock(&self.left_dock).or(sidebar_target)
 4870            }
 4871            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4872
 4873            (Origin::RightDock, SplitDirection::Left) => {
 4874                if let Some(last_active_pane) = get_last_active_pane() {
 4875                    Some(Target::Pane(last_active_pane))
 4876                } else {
 4877                    try_dock(&self.bottom_dock)
 4878                        .or_else(|| try_dock(&self.left_dock))
 4879                        .or(sidebar_target)
 4880                }
 4881            }
 4882
 4883            _ => None,
 4884        };
 4885
 4886        match target {
 4887            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4888                let pane = pane.read(cx);
 4889                if let Some(item) = pane.active_item() {
 4890                    item.item_focus_handle(cx).focus(window, cx);
 4891                } else {
 4892                    log::error!(
 4893                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4894                    );
 4895                }
 4896            }
 4897            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4898                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4899                window.defer(cx, move |window, cx| {
 4900                    let dock = dock.read(cx);
 4901                    if let Some(panel) = dock.active_panel() {
 4902                        panel.panel_focus_handle(cx).focus(window, cx);
 4903                    } else {
 4904                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4905                    }
 4906                })
 4907            }
 4908            Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
 4909                focus_handle.focus(window, cx);
 4910            }
 4911            None => {}
 4912        }
 4913    }
 4914
 4915    pub fn move_item_to_pane_in_direction(
 4916        &mut self,
 4917        action: &MoveItemToPaneInDirection,
 4918        window: &mut Window,
 4919        cx: &mut Context<Self>,
 4920    ) {
 4921        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4922            Some(destination) => destination,
 4923            None => {
 4924                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4925                    return;
 4926                }
 4927                let new_pane = self.add_pane(window, cx);
 4928                self.center
 4929                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4930                new_pane
 4931            }
 4932        };
 4933
 4934        if action.clone {
 4935            if self
 4936                .active_pane
 4937                .read(cx)
 4938                .active_item()
 4939                .is_some_and(|item| item.can_split(cx))
 4940            {
 4941                clone_active_item(
 4942                    self.database_id(),
 4943                    &self.active_pane,
 4944                    &destination,
 4945                    action.focus,
 4946                    window,
 4947                    cx,
 4948                );
 4949                return;
 4950            }
 4951        }
 4952        move_active_item(
 4953            &self.active_pane,
 4954            &destination,
 4955            action.focus,
 4956            true,
 4957            window,
 4958            cx,
 4959        );
 4960    }
 4961
 4962    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4963        self.center.bounding_box_for_pane(pane)
 4964    }
 4965
 4966    pub fn find_pane_in_direction(
 4967        &mut self,
 4968        direction: SplitDirection,
 4969        cx: &App,
 4970    ) -> Option<Entity<Pane>> {
 4971        self.center
 4972            .find_pane_in_direction(&self.active_pane, direction, cx)
 4973            .cloned()
 4974    }
 4975
 4976    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4977        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4978            self.center.swap(&self.active_pane, &to, cx);
 4979            cx.notify();
 4980        }
 4981    }
 4982
 4983    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4984        if self
 4985            .center
 4986            .move_to_border(&self.active_pane, direction, cx)
 4987            .unwrap()
 4988        {
 4989            cx.notify();
 4990        }
 4991    }
 4992
 4993    pub fn resize_pane(
 4994        &mut self,
 4995        axis: gpui::Axis,
 4996        amount: Pixels,
 4997        window: &mut Window,
 4998        cx: &mut Context<Self>,
 4999    ) {
 5000        let docks = self.all_docks();
 5001        let active_dock = docks
 5002            .into_iter()
 5003            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 5004
 5005        if let Some(dock_entity) = active_dock {
 5006            let dock = dock_entity.read(cx);
 5007            let Some(panel_size) = self.dock_size(&dock, window, cx) else {
 5008                return;
 5009            };
 5010            match dock.position() {
 5011                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 5012                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 5013                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 5014            }
 5015        } else {
 5016            self.center
 5017                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 5018        }
 5019        cx.notify();
 5020    }
 5021
 5022    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 5023        self.center.reset_pane_sizes(cx);
 5024        cx.notify();
 5025    }
 5026
 5027    fn handle_pane_focused(
 5028        &mut self,
 5029        pane: Entity<Pane>,
 5030        window: &mut Window,
 5031        cx: &mut Context<Self>,
 5032    ) {
 5033        // This is explicitly hoisted out of the following check for pane identity as
 5034        // terminal panel panes are not registered as a center panes.
 5035        self.status_bar.update(cx, |status_bar, cx| {
 5036            status_bar.set_active_pane(&pane, window, cx);
 5037        });
 5038        if self.active_pane != pane {
 5039            self.set_active_pane(&pane, window, cx);
 5040        }
 5041
 5042        if self.last_active_center_pane.is_none() {
 5043            self.last_active_center_pane = Some(pane.downgrade());
 5044        }
 5045
 5046        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 5047        // This prevents the dock from closing when focus events fire during window activation.
 5048        // We also preserve any dock whose active panel itself has focus — this covers
 5049        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 5050        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 5051            let dock_read = dock.read(cx);
 5052            if let Some(panel) = dock_read.active_panel() {
 5053                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 5054                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 5055                {
 5056                    return Some(dock_read.position());
 5057                }
 5058            }
 5059            None
 5060        });
 5061
 5062        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 5063        if pane.read(cx).is_zoomed() {
 5064            self.zoomed = Some(pane.downgrade().into());
 5065        } else {
 5066            self.zoomed = None;
 5067        }
 5068        self.zoomed_position = None;
 5069        cx.emit(Event::ZoomChanged);
 5070        self.update_active_view_for_followers(window, cx);
 5071        pane.update(cx, |pane, _| {
 5072            pane.track_alternate_file_items();
 5073        });
 5074
 5075        cx.notify();
 5076    }
 5077
 5078    fn set_active_pane(
 5079        &mut self,
 5080        pane: &Entity<Pane>,
 5081        window: &mut Window,
 5082        cx: &mut Context<Self>,
 5083    ) {
 5084        self.active_pane = pane.clone();
 5085        self.active_item_path_changed(true, window, cx);
 5086        self.last_active_center_pane = Some(pane.downgrade());
 5087    }
 5088
 5089    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5090        self.update_active_view_for_followers(window, cx);
 5091    }
 5092
 5093    fn handle_pane_event(
 5094        &mut self,
 5095        pane: &Entity<Pane>,
 5096        event: &pane::Event,
 5097        window: &mut Window,
 5098        cx: &mut Context<Self>,
 5099    ) {
 5100        let mut serialize_workspace = true;
 5101        match event {
 5102            pane::Event::AddItem { item } => {
 5103                item.added_to_pane(self, pane.clone(), window, cx);
 5104                cx.emit(Event::ItemAdded {
 5105                    item: item.boxed_clone(),
 5106                });
 5107            }
 5108            pane::Event::Split { direction, mode } => {
 5109                match mode {
 5110                    SplitMode::ClonePane => {
 5111                        self.split_and_clone(pane.clone(), *direction, window, cx)
 5112                            .detach();
 5113                    }
 5114                    SplitMode::EmptyPane => {
 5115                        self.split_pane(pane.clone(), *direction, window, cx);
 5116                    }
 5117                    SplitMode::MovePane => {
 5118                        self.split_and_move(pane.clone(), *direction, window, cx);
 5119                    }
 5120                };
 5121            }
 5122            pane::Event::JoinIntoNext => {
 5123                self.join_pane_into_next(pane.clone(), window, cx);
 5124            }
 5125            pane::Event::JoinAll => {
 5126                self.join_all_panes(window, cx);
 5127            }
 5128            pane::Event::Remove { focus_on_pane } => {
 5129                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 5130            }
 5131            pane::Event::ActivateItem {
 5132                local,
 5133                focus_changed,
 5134            } => {
 5135                window.invalidate_character_coordinates();
 5136
 5137                pane.update(cx, |pane, _| {
 5138                    pane.track_alternate_file_items();
 5139                });
 5140                if *local {
 5141                    self.unfollow_in_pane(pane, window, cx);
 5142                }
 5143                serialize_workspace = *focus_changed || pane != self.active_pane();
 5144                if pane == self.active_pane() {
 5145                    self.active_item_path_changed(*focus_changed, window, cx);
 5146                    self.update_active_view_for_followers(window, cx);
 5147                } else if *local {
 5148                    self.set_active_pane(pane, window, cx);
 5149                }
 5150            }
 5151            pane::Event::UserSavedItem { item, save_intent } => {
 5152                cx.emit(Event::UserSavedItem {
 5153                    pane: pane.downgrade(),
 5154                    item: item.boxed_clone(),
 5155                    save_intent: *save_intent,
 5156                });
 5157                serialize_workspace = false;
 5158            }
 5159            pane::Event::ChangeItemTitle => {
 5160                if *pane == self.active_pane {
 5161                    self.active_item_path_changed(false, window, cx);
 5162                }
 5163                serialize_workspace = false;
 5164            }
 5165            pane::Event::RemovedItem { item } => {
 5166                cx.emit(Event::ActiveItemChanged);
 5167                self.update_window_edited(window, cx);
 5168                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 5169                    && entry.get().entity_id() == pane.entity_id()
 5170                {
 5171                    entry.remove();
 5172                }
 5173                cx.emit(Event::ItemRemoved {
 5174                    item_id: item.item_id(),
 5175                });
 5176            }
 5177            pane::Event::Focus => {
 5178                window.invalidate_character_coordinates();
 5179                self.handle_pane_focused(pane.clone(), window, cx);
 5180            }
 5181            pane::Event::ZoomIn => {
 5182                if *pane == self.active_pane {
 5183                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 5184                    if pane.read(cx).has_focus(window, cx) {
 5185                        self.zoomed = Some(pane.downgrade().into());
 5186                        self.zoomed_position = None;
 5187                        cx.emit(Event::ZoomChanged);
 5188                    }
 5189                    cx.notify();
 5190                }
 5191            }
 5192            pane::Event::ZoomOut => {
 5193                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 5194                if self.zoomed_position.is_none() {
 5195                    self.zoomed = None;
 5196                    cx.emit(Event::ZoomChanged);
 5197                }
 5198                cx.notify();
 5199            }
 5200            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 5201        }
 5202
 5203        if serialize_workspace {
 5204            self.serialize_workspace(window, cx);
 5205        }
 5206    }
 5207
 5208    pub fn unfollow_in_pane(
 5209        &mut self,
 5210        pane: &Entity<Pane>,
 5211        window: &mut Window,
 5212        cx: &mut Context<Workspace>,
 5213    ) -> Option<CollaboratorId> {
 5214        let leader_id = self.leader_for_pane(pane)?;
 5215        self.unfollow(leader_id, window, cx);
 5216        Some(leader_id)
 5217    }
 5218
 5219    pub fn split_pane(
 5220        &mut self,
 5221        pane_to_split: Entity<Pane>,
 5222        split_direction: SplitDirection,
 5223        window: &mut Window,
 5224        cx: &mut Context<Self>,
 5225    ) -> Entity<Pane> {
 5226        let new_pane = self.add_pane(window, cx);
 5227        self.center
 5228            .split(&pane_to_split, &new_pane, split_direction, cx);
 5229        cx.notify();
 5230        new_pane
 5231    }
 5232
 5233    pub fn split_and_move(
 5234        &mut self,
 5235        pane: Entity<Pane>,
 5236        direction: SplitDirection,
 5237        window: &mut Window,
 5238        cx: &mut Context<Self>,
 5239    ) {
 5240        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 5241            return;
 5242        };
 5243        let new_pane = self.add_pane(window, cx);
 5244        new_pane.update(cx, |pane, cx| {
 5245            pane.add_item(item, true, true, None, window, cx)
 5246        });
 5247        self.center.split(&pane, &new_pane, direction, cx);
 5248        cx.notify();
 5249    }
 5250
 5251    pub fn split_and_clone(
 5252        &mut self,
 5253        pane: Entity<Pane>,
 5254        direction: SplitDirection,
 5255        window: &mut Window,
 5256        cx: &mut Context<Self>,
 5257    ) -> Task<Option<Entity<Pane>>> {
 5258        let Some(item) = pane.read(cx).active_item() else {
 5259            return Task::ready(None);
 5260        };
 5261        if !item.can_split(cx) {
 5262            return Task::ready(None);
 5263        }
 5264        let task = item.clone_on_split(self.database_id(), window, cx);
 5265        cx.spawn_in(window, async move |this, cx| {
 5266            if let Some(clone) = task.await {
 5267                this.update_in(cx, |this, window, cx| {
 5268                    let new_pane = this.add_pane(window, cx);
 5269                    let nav_history = pane.read(cx).fork_nav_history();
 5270                    new_pane.update(cx, |pane, cx| {
 5271                        pane.set_nav_history(nav_history, cx);
 5272                        pane.add_item(clone, true, true, None, window, cx)
 5273                    });
 5274                    this.center.split(&pane, &new_pane, direction, cx);
 5275                    cx.notify();
 5276                    new_pane
 5277                })
 5278                .ok()
 5279            } else {
 5280                None
 5281            }
 5282        })
 5283    }
 5284
 5285    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5286        let active_item = self.active_pane.read(cx).active_item();
 5287        for pane in &self.panes {
 5288            join_pane_into_active(&self.active_pane, pane, window, cx);
 5289        }
 5290        if let Some(active_item) = active_item {
 5291            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5292        }
 5293        cx.notify();
 5294    }
 5295
 5296    pub fn join_pane_into_next(
 5297        &mut self,
 5298        pane: Entity<Pane>,
 5299        window: &mut Window,
 5300        cx: &mut Context<Self>,
 5301    ) {
 5302        let next_pane = self
 5303            .find_pane_in_direction(SplitDirection::Right, cx)
 5304            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5305            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5306            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5307        let Some(next_pane) = next_pane else {
 5308            return;
 5309        };
 5310        move_all_items(&pane, &next_pane, window, cx);
 5311        cx.notify();
 5312    }
 5313
 5314    fn remove_pane(
 5315        &mut self,
 5316        pane: Entity<Pane>,
 5317        focus_on: Option<Entity<Pane>>,
 5318        window: &mut Window,
 5319        cx: &mut Context<Self>,
 5320    ) {
 5321        if self.center.remove(&pane, cx).unwrap() {
 5322            self.force_remove_pane(&pane, &focus_on, window, cx);
 5323            self.unfollow_in_pane(&pane, window, cx);
 5324            self.last_leaders_by_pane.remove(&pane.downgrade());
 5325            for removed_item in pane.read(cx).items() {
 5326                self.panes_by_item.remove(&removed_item.item_id());
 5327            }
 5328
 5329            cx.notify();
 5330        } else {
 5331            self.active_item_path_changed(true, window, cx);
 5332        }
 5333        cx.emit(Event::PaneRemoved);
 5334    }
 5335
 5336    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5337        &mut self.panes
 5338    }
 5339
 5340    pub fn panes(&self) -> &[Entity<Pane>] {
 5341        &self.panes
 5342    }
 5343
 5344    pub fn active_pane(&self) -> &Entity<Pane> {
 5345        &self.active_pane
 5346    }
 5347
 5348    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5349        for dock in self.all_docks() {
 5350            if dock.focus_handle(cx).contains_focused(window, cx)
 5351                && let Some(pane) = dock
 5352                    .read(cx)
 5353                    .active_panel()
 5354                    .and_then(|panel| panel.pane(cx))
 5355            {
 5356                return pane;
 5357            }
 5358        }
 5359        self.active_pane().clone()
 5360    }
 5361
 5362    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5363        self.find_pane_in_direction(SplitDirection::Right, cx)
 5364            .unwrap_or_else(|| {
 5365                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5366            })
 5367    }
 5368
 5369    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5370        self.pane_for_item_id(handle.item_id())
 5371    }
 5372
 5373    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5374        let weak_pane = self.panes_by_item.get(&item_id)?;
 5375        weak_pane.upgrade()
 5376    }
 5377
 5378    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5379        self.panes
 5380            .iter()
 5381            .find(|pane| pane.entity_id() == entity_id)
 5382            .cloned()
 5383    }
 5384
 5385    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5386        self.follower_states.retain(|leader_id, state| {
 5387            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5388                for item in state.items_by_leader_view_id.values() {
 5389                    item.view.set_leader_id(None, window, cx);
 5390                }
 5391                false
 5392            } else {
 5393                true
 5394            }
 5395        });
 5396        cx.notify();
 5397    }
 5398
 5399    pub fn start_following(
 5400        &mut self,
 5401        leader_id: impl Into<CollaboratorId>,
 5402        window: &mut Window,
 5403        cx: &mut Context<Self>,
 5404    ) -> Option<Task<Result<()>>> {
 5405        let leader_id = leader_id.into();
 5406        let pane = self.active_pane().clone();
 5407
 5408        self.last_leaders_by_pane
 5409            .insert(pane.downgrade(), leader_id);
 5410        self.unfollow(leader_id, window, cx);
 5411        self.unfollow_in_pane(&pane, window, cx);
 5412        self.follower_states.insert(
 5413            leader_id,
 5414            FollowerState {
 5415                center_pane: pane.clone(),
 5416                dock_pane: None,
 5417                active_view_id: None,
 5418                items_by_leader_view_id: Default::default(),
 5419            },
 5420        );
 5421        cx.notify();
 5422
 5423        match leader_id {
 5424            CollaboratorId::PeerId(leader_peer_id) => {
 5425                let room_id = self.active_call()?.room_id(cx)?;
 5426                let project_id = self.project.read(cx).remote_id();
 5427                let request = self.app_state.client.request(proto::Follow {
 5428                    room_id,
 5429                    project_id,
 5430                    leader_id: Some(leader_peer_id),
 5431                });
 5432
 5433                Some(cx.spawn_in(window, async move |this, cx| {
 5434                    let response = request.await?;
 5435                    this.update(cx, |this, _| {
 5436                        let state = this
 5437                            .follower_states
 5438                            .get_mut(&leader_id)
 5439                            .context("following interrupted")?;
 5440                        state.active_view_id = response
 5441                            .active_view
 5442                            .as_ref()
 5443                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5444                        anyhow::Ok(())
 5445                    })??;
 5446                    if let Some(view) = response.active_view {
 5447                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5448                    }
 5449                    this.update_in(cx, |this, window, cx| {
 5450                        this.leader_updated(leader_id, window, cx)
 5451                    })?;
 5452                    Ok(())
 5453                }))
 5454            }
 5455            CollaboratorId::Agent => {
 5456                self.leader_updated(leader_id, window, cx)?;
 5457                Some(Task::ready(Ok(())))
 5458            }
 5459        }
 5460    }
 5461
 5462    pub fn follow_next_collaborator(
 5463        &mut self,
 5464        _: &FollowNextCollaborator,
 5465        window: &mut Window,
 5466        cx: &mut Context<Self>,
 5467    ) {
 5468        let collaborators = self.project.read(cx).collaborators();
 5469        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5470            let mut collaborators = collaborators.keys().copied();
 5471            for peer_id in collaborators.by_ref() {
 5472                if CollaboratorId::PeerId(peer_id) == leader_id {
 5473                    break;
 5474                }
 5475            }
 5476            collaborators.next().map(CollaboratorId::PeerId)
 5477        } else if let Some(last_leader_id) =
 5478            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5479        {
 5480            match last_leader_id {
 5481                CollaboratorId::PeerId(peer_id) => {
 5482                    if collaborators.contains_key(peer_id) {
 5483                        Some(*last_leader_id)
 5484                    } else {
 5485                        None
 5486                    }
 5487                }
 5488                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5489            }
 5490        } else {
 5491            None
 5492        };
 5493
 5494        let pane = self.active_pane.clone();
 5495        let Some(leader_id) = next_leader_id.or_else(|| {
 5496            Some(CollaboratorId::PeerId(
 5497                collaborators.keys().copied().next()?,
 5498            ))
 5499        }) else {
 5500            return;
 5501        };
 5502        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5503            return;
 5504        }
 5505        if let Some(task) = self.start_following(leader_id, window, cx) {
 5506            task.detach_and_log_err(cx)
 5507        }
 5508    }
 5509
 5510    pub fn follow(
 5511        &mut self,
 5512        leader_id: impl Into<CollaboratorId>,
 5513        window: &mut Window,
 5514        cx: &mut Context<Self>,
 5515    ) {
 5516        let leader_id = leader_id.into();
 5517
 5518        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5519            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5520                return;
 5521            };
 5522            let Some(remote_participant) =
 5523                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5524            else {
 5525                return;
 5526            };
 5527
 5528            let project = self.project.read(cx);
 5529
 5530            let other_project_id = match remote_participant.location {
 5531                ParticipantLocation::External => None,
 5532                ParticipantLocation::UnsharedProject => None,
 5533                ParticipantLocation::SharedProject { project_id } => {
 5534                    if Some(project_id) == project.remote_id() {
 5535                        None
 5536                    } else {
 5537                        Some(project_id)
 5538                    }
 5539                }
 5540            };
 5541
 5542            // if they are active in another project, follow there.
 5543            if let Some(project_id) = other_project_id {
 5544                let app_state = self.app_state.clone();
 5545                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5546                    .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
 5547                        Some(format!("{error:#}"))
 5548                    });
 5549            }
 5550        }
 5551
 5552        // if you're already following, find the right pane and focus it.
 5553        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5554            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5555
 5556            return;
 5557        }
 5558
 5559        // Otherwise, follow.
 5560        if let Some(task) = self.start_following(leader_id, window, cx) {
 5561            task.detach_and_log_err(cx)
 5562        }
 5563    }
 5564
 5565    pub fn unfollow(
 5566        &mut self,
 5567        leader_id: impl Into<CollaboratorId>,
 5568        window: &mut Window,
 5569        cx: &mut Context<Self>,
 5570    ) -> Option<()> {
 5571        cx.notify();
 5572
 5573        let leader_id = leader_id.into();
 5574        let state = self.follower_states.remove(&leader_id)?;
 5575        for (_, item) in state.items_by_leader_view_id {
 5576            item.view.set_leader_id(None, window, cx);
 5577        }
 5578
 5579        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5580            let project_id = self.project.read(cx).remote_id();
 5581            let room_id = self.active_call()?.room_id(cx)?;
 5582            self.app_state
 5583                .client
 5584                .send(proto::Unfollow {
 5585                    room_id,
 5586                    project_id,
 5587                    leader_id: Some(leader_peer_id),
 5588                })
 5589                .log_err();
 5590        }
 5591
 5592        Some(())
 5593    }
 5594
 5595    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5596        self.follower_states.contains_key(&id.into())
 5597    }
 5598
 5599    fn active_item_path_changed(
 5600        &mut self,
 5601        focus_changed: bool,
 5602        window: &mut Window,
 5603        cx: &mut Context<Self>,
 5604    ) {
 5605        cx.emit(Event::ActiveItemChanged);
 5606        let active_entry = self.active_project_path(cx);
 5607        self.project.update(cx, |project, cx| {
 5608            project.set_active_path(active_entry.clone(), cx)
 5609        });
 5610
 5611        if focus_changed && let Some(project_path) = &active_entry {
 5612            let git_store_entity = self.project.read(cx).git_store().clone();
 5613            git_store_entity.update(cx, |git_store, cx| {
 5614                git_store.set_active_repo_for_path(project_path, cx);
 5615            });
 5616        }
 5617
 5618        self.update_window_title(window, cx);
 5619    }
 5620
 5621    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5622        let project = self.project().read(cx);
 5623        let mut title = String::new();
 5624
 5625        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5626            let name = {
 5627                let settings_location = SettingsLocation {
 5628                    worktree_id: worktree.read(cx).id(),
 5629                    path: RelPath::empty(),
 5630                };
 5631
 5632                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5633                match &settings.project_name {
 5634                    Some(name) => name.as_str(),
 5635                    None => worktree.read(cx).root_name_str(),
 5636                }
 5637            };
 5638            if i > 0 {
 5639                title.push_str(", ");
 5640            }
 5641            title.push_str(name);
 5642        }
 5643
 5644        if title.is_empty() {
 5645            title = "empty project".to_string();
 5646        }
 5647
 5648        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5649            let filename = path.path.file_name().or_else(|| {
 5650                Some(
 5651                    project
 5652                        .worktree_for_id(path.worktree_id, cx)?
 5653                        .read(cx)
 5654                        .root_name_str(),
 5655                )
 5656            });
 5657
 5658            if let Some(filename) = filename {
 5659                title.push_str("");
 5660                title.push_str(filename.as_ref());
 5661            }
 5662        }
 5663
 5664        if project.is_via_collab() {
 5665            title.push_str("");
 5666        } else if project.is_shared() {
 5667            title.push_str("");
 5668        }
 5669
 5670        if let Some(last_title) = self.last_window_title.as_ref()
 5671            && &title == last_title
 5672        {
 5673            return;
 5674        }
 5675        window.set_window_title(&title);
 5676        SystemWindowTabController::update_tab_title(
 5677            cx,
 5678            window.window_handle().window_id(),
 5679            SharedString::from(&title),
 5680        );
 5681        self.last_window_title = Some(title);
 5682    }
 5683
 5684    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5685        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5686        if is_edited != self.window_edited {
 5687            self.window_edited = is_edited;
 5688            window.set_window_edited(self.window_edited)
 5689        }
 5690    }
 5691
 5692    fn update_item_dirty_state(
 5693        &mut self,
 5694        item: &dyn ItemHandle,
 5695        window: &mut Window,
 5696        cx: &mut App,
 5697    ) {
 5698        let is_dirty = item.is_dirty(cx);
 5699        let item_id = item.item_id();
 5700        let was_dirty = self.dirty_items.contains_key(&item_id);
 5701        if is_dirty == was_dirty {
 5702            return;
 5703        }
 5704        if was_dirty {
 5705            self.dirty_items.remove(&item_id);
 5706            self.update_window_edited(window, cx);
 5707            return;
 5708        }
 5709
 5710        let workspace = self.weak_handle();
 5711        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5712            return;
 5713        };
 5714        let on_release_callback = Box::new(move |cx: &mut App| {
 5715            window_handle
 5716                .update(cx, |_, window, cx| {
 5717                    workspace
 5718                        .update(cx, |workspace, cx| {
 5719                            workspace.dirty_items.remove(&item_id);
 5720                            workspace.update_window_edited(window, cx)
 5721                        })
 5722                        .ok();
 5723                })
 5724                .ok();
 5725        });
 5726
 5727        let s = item.on_release(cx, on_release_callback);
 5728        self.dirty_items.insert(item_id, s);
 5729        self.update_window_edited(window, cx);
 5730    }
 5731
 5732    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5733        if self.notifications.is_empty() {
 5734            None
 5735        } else {
 5736            Some(
 5737                div()
 5738                    .absolute()
 5739                    .right_3()
 5740                    .bottom_3()
 5741                    .w_112()
 5742                    .h_full()
 5743                    .flex()
 5744                    .flex_col()
 5745                    .justify_end()
 5746                    .gap_2()
 5747                    .children(
 5748                        self.notifications
 5749                            .iter()
 5750                            .map(|(_, notification)| notification.clone().into_any()),
 5751                    ),
 5752            )
 5753        }
 5754    }
 5755
 5756    // RPC handlers
 5757
 5758    fn active_view_for_follower(
 5759        &self,
 5760        follower_project_id: Option<u64>,
 5761        window: &mut Window,
 5762        cx: &mut Context<Self>,
 5763    ) -> Option<proto::View> {
 5764        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5765        let item = item?;
 5766        let leader_id = self
 5767            .pane_for(&*item)
 5768            .and_then(|pane| self.leader_for_pane(&pane));
 5769        let leader_peer_id = match leader_id {
 5770            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5771            Some(CollaboratorId::Agent) | None => None,
 5772        };
 5773
 5774        let item_handle = item.to_followable_item_handle(cx)?;
 5775        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5776        let variant = item_handle.to_state_proto(window, cx)?;
 5777
 5778        if item_handle.is_project_item(window, cx)
 5779            && (follower_project_id.is_none()
 5780                || follower_project_id != self.project.read(cx).remote_id())
 5781        {
 5782            return None;
 5783        }
 5784
 5785        Some(proto::View {
 5786            id: id.to_proto(),
 5787            leader_id: leader_peer_id,
 5788            variant: Some(variant),
 5789            panel_id: panel_id.map(|id| id as i32),
 5790        })
 5791    }
 5792
 5793    fn handle_follow(
 5794        &mut self,
 5795        follower_project_id: Option<u64>,
 5796        window: &mut Window,
 5797        cx: &mut Context<Self>,
 5798    ) -> proto::FollowResponse {
 5799        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5800
 5801        cx.notify();
 5802        proto::FollowResponse {
 5803            views: active_view.iter().cloned().collect(),
 5804            active_view,
 5805        }
 5806    }
 5807
 5808    fn handle_update_followers(
 5809        &mut self,
 5810        leader_id: PeerId,
 5811        message: proto::UpdateFollowers,
 5812        _window: &mut Window,
 5813        _cx: &mut Context<Self>,
 5814    ) {
 5815        self.leader_updates_tx
 5816            .unbounded_send((leader_id, message))
 5817            .ok();
 5818    }
 5819
 5820    async fn process_leader_update(
 5821        this: &WeakEntity<Self>,
 5822        leader_id: PeerId,
 5823        update: proto::UpdateFollowers,
 5824        cx: &mut AsyncWindowContext,
 5825    ) -> Result<()> {
 5826        match update.variant.context("invalid update")? {
 5827            proto::update_followers::Variant::CreateView(view) => {
 5828                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5829                let should_add_view = this.update(cx, |this, _| {
 5830                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5831                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5832                    } else {
 5833                        anyhow::Ok(false)
 5834                    }
 5835                })??;
 5836
 5837                if should_add_view {
 5838                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5839                }
 5840            }
 5841            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5842                let should_add_view = this.update(cx, |this, _| {
 5843                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5844                        state.active_view_id = update_active_view
 5845                            .view
 5846                            .as_ref()
 5847                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5848
 5849                        if state.active_view_id.is_some_and(|view_id| {
 5850                            !state.items_by_leader_view_id.contains_key(&view_id)
 5851                        }) {
 5852                            anyhow::Ok(true)
 5853                        } else {
 5854                            anyhow::Ok(false)
 5855                        }
 5856                    } else {
 5857                        anyhow::Ok(false)
 5858                    }
 5859                })??;
 5860
 5861                if should_add_view && let Some(view) = update_active_view.view {
 5862                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5863                }
 5864            }
 5865            proto::update_followers::Variant::UpdateView(update_view) => {
 5866                let variant = update_view.variant.context("missing update view variant")?;
 5867                let id = update_view.id.context("missing update view id")?;
 5868                let mut tasks = Vec::new();
 5869                this.update_in(cx, |this, window, cx| {
 5870                    let project = this.project.clone();
 5871                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5872                        let view_id = ViewId::from_proto(id.clone())?;
 5873                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5874                            tasks.push(item.view.apply_update_proto(
 5875                                &project,
 5876                                variant.clone(),
 5877                                window,
 5878                                cx,
 5879                            ));
 5880                        }
 5881                    }
 5882                    anyhow::Ok(())
 5883                })??;
 5884                try_join_all(tasks).await.log_err();
 5885            }
 5886        }
 5887        this.update_in(cx, |this, window, cx| {
 5888            this.leader_updated(leader_id, window, cx)
 5889        })?;
 5890        Ok(())
 5891    }
 5892
 5893    async fn add_view_from_leader(
 5894        this: WeakEntity<Self>,
 5895        leader_id: PeerId,
 5896        view: &proto::View,
 5897        cx: &mut AsyncWindowContext,
 5898    ) -> Result<()> {
 5899        let this = this.upgrade().context("workspace dropped")?;
 5900
 5901        let Some(id) = view.id.clone() else {
 5902            anyhow::bail!("no id for view");
 5903        };
 5904        let id = ViewId::from_proto(id)?;
 5905        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5906
 5907        let pane = this.update(cx, |this, _cx| {
 5908            let state = this
 5909                .follower_states
 5910                .get(&leader_id.into())
 5911                .context("stopped following")?;
 5912            anyhow::Ok(state.pane().clone())
 5913        })?;
 5914        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5915            let client = this.read(cx).client().clone();
 5916            pane.items().find_map(|item| {
 5917                let item = item.to_followable_item_handle(cx)?;
 5918                if item.remote_id(&client, window, cx) == Some(id) {
 5919                    Some(item)
 5920                } else {
 5921                    None
 5922                }
 5923            })
 5924        })?;
 5925        let item = if let Some(existing_item) = existing_item {
 5926            existing_item
 5927        } else {
 5928            let variant = view.variant.clone();
 5929            anyhow::ensure!(variant.is_some(), "missing view variant");
 5930
 5931            let task = cx.update(|window, cx| {
 5932                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5933            })?;
 5934
 5935            let Some(task) = task else {
 5936                anyhow::bail!(
 5937                    "failed to construct view from leader (maybe from a different version of zed?)"
 5938                );
 5939            };
 5940
 5941            let mut new_item = task.await?;
 5942            pane.update_in(cx, |pane, window, cx| {
 5943                let mut item_to_remove = None;
 5944                for (ix, item) in pane.items().enumerate() {
 5945                    if let Some(item) = item.to_followable_item_handle(cx) {
 5946                        match new_item.dedup(item.as_ref(), window, cx) {
 5947                            Some(item::Dedup::KeepExisting) => {
 5948                                new_item =
 5949                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5950                                break;
 5951                            }
 5952                            Some(item::Dedup::ReplaceExisting) => {
 5953                                item_to_remove = Some((ix, item.item_id()));
 5954                                break;
 5955                            }
 5956                            None => {}
 5957                        }
 5958                    }
 5959                }
 5960
 5961                if let Some((ix, id)) = item_to_remove {
 5962                    pane.remove_item(id, false, false, window, cx);
 5963                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5964                }
 5965            })?;
 5966
 5967            new_item
 5968        };
 5969
 5970        this.update_in(cx, |this, window, cx| {
 5971            let state = this.follower_states.get_mut(&leader_id.into())?;
 5972            item.set_leader_id(Some(leader_id.into()), window, cx);
 5973            state.items_by_leader_view_id.insert(
 5974                id,
 5975                FollowerView {
 5976                    view: item,
 5977                    location: panel_id,
 5978                },
 5979            );
 5980
 5981            Some(())
 5982        })
 5983        .context("no follower state")?;
 5984
 5985        Ok(())
 5986    }
 5987
 5988    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5989        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5990            return;
 5991        };
 5992
 5993        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5994            let buffer_entity_id = agent_location.buffer.entity_id();
 5995            let view_id = ViewId {
 5996                creator: CollaboratorId::Agent,
 5997                id: buffer_entity_id.as_u64(),
 5998            };
 5999            follower_state.active_view_id = Some(view_id);
 6000
 6001            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 6002                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 6003                hash_map::Entry::Vacant(entry) => {
 6004                    let existing_view =
 6005                        follower_state
 6006                            .center_pane
 6007                            .read(cx)
 6008                            .items()
 6009                            .find_map(|item| {
 6010                                let item = item.to_followable_item_handle(cx)?;
 6011                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 6012                                    && item.project_item_model_ids(cx).as_slice()
 6013                                        == [buffer_entity_id]
 6014                                {
 6015                                    Some(item)
 6016                                } else {
 6017                                    None
 6018                                }
 6019                            });
 6020                    let view = existing_view.or_else(|| {
 6021                        agent_location.buffer.upgrade().and_then(|buffer| {
 6022                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 6023                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 6024                            })?
 6025                            .to_followable_item_handle(cx)
 6026                        })
 6027                    });
 6028
 6029                    view.map(|view| {
 6030                        entry.insert(FollowerView {
 6031                            view,
 6032                            location: None,
 6033                        })
 6034                    })
 6035                }
 6036            };
 6037
 6038            if let Some(item) = item {
 6039                item.view
 6040                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 6041                item.view
 6042                    .update_agent_location(agent_location.position, window, cx);
 6043            }
 6044        } else {
 6045            follower_state.active_view_id = None;
 6046        }
 6047
 6048        self.leader_updated(CollaboratorId::Agent, window, cx);
 6049    }
 6050
 6051    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 6052        let mut is_project_item = true;
 6053        let mut update = proto::UpdateActiveView::default();
 6054        if window.is_window_active() {
 6055            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 6056
 6057            if let Some(item) = active_item
 6058                && item.item_focus_handle(cx).contains_focused(window, cx)
 6059            {
 6060                let leader_id = self
 6061                    .pane_for(&*item)
 6062                    .and_then(|pane| self.leader_for_pane(&pane));
 6063                let leader_peer_id = match leader_id {
 6064                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 6065                    Some(CollaboratorId::Agent) | None => None,
 6066                };
 6067
 6068                if let Some(item) = item.to_followable_item_handle(cx) {
 6069                    let id = item
 6070                        .remote_id(&self.app_state.client, window, cx)
 6071                        .map(|id| id.to_proto());
 6072
 6073                    if let Some(id) = id
 6074                        && let Some(variant) = item.to_state_proto(window, cx)
 6075                    {
 6076                        let view = Some(proto::View {
 6077                            id,
 6078                            leader_id: leader_peer_id,
 6079                            variant: Some(variant),
 6080                            panel_id: panel_id.map(|id| id as i32),
 6081                        });
 6082
 6083                        is_project_item = item.is_project_item(window, cx);
 6084                        update = proto::UpdateActiveView { view };
 6085                    };
 6086                }
 6087            }
 6088        }
 6089
 6090        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 6091        if active_view_id != self.last_active_view_id.as_ref() {
 6092            self.last_active_view_id = active_view_id.cloned();
 6093            self.update_followers(
 6094                is_project_item,
 6095                proto::update_followers::Variant::UpdateActiveView(update),
 6096                window,
 6097                cx,
 6098            );
 6099        }
 6100    }
 6101
 6102    fn active_item_for_followers(
 6103        &self,
 6104        window: &mut Window,
 6105        cx: &mut App,
 6106    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 6107        let mut active_item = None;
 6108        let mut panel_id = None;
 6109        for dock in self.all_docks() {
 6110            if dock.focus_handle(cx).contains_focused(window, cx)
 6111                && let Some(panel) = dock.read(cx).active_panel()
 6112                && let Some(pane) = panel.pane(cx)
 6113                && let Some(item) = pane.read(cx).active_item()
 6114            {
 6115                active_item = Some(item);
 6116                panel_id = panel.remote_id();
 6117                break;
 6118            }
 6119        }
 6120
 6121        if active_item.is_none() {
 6122            active_item = self.active_pane().read(cx).active_item();
 6123        }
 6124        (active_item, panel_id)
 6125    }
 6126
 6127    fn update_followers(
 6128        &self,
 6129        project_only: bool,
 6130        update: proto::update_followers::Variant,
 6131        _: &mut Window,
 6132        cx: &mut App,
 6133    ) -> Option<()> {
 6134        // If this update only applies to for followers in the current project,
 6135        // then skip it unless this project is shared. If it applies to all
 6136        // followers, regardless of project, then set `project_id` to none,
 6137        // indicating that it goes to all followers.
 6138        let project_id = if project_only {
 6139            Some(self.project.read(cx).remote_id()?)
 6140        } else {
 6141            None
 6142        };
 6143        self.app_state().workspace_store.update(cx, |store, cx| {
 6144            store.update_followers(project_id, update, cx)
 6145        })
 6146    }
 6147
 6148    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 6149        self.follower_states.iter().find_map(|(leader_id, state)| {
 6150            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 6151                Some(*leader_id)
 6152            } else {
 6153                None
 6154            }
 6155        })
 6156    }
 6157
 6158    fn leader_updated(
 6159        &mut self,
 6160        leader_id: impl Into<CollaboratorId>,
 6161        window: &mut Window,
 6162        cx: &mut Context<Self>,
 6163    ) -> Option<Box<dyn ItemHandle>> {
 6164        cx.notify();
 6165
 6166        let leader_id = leader_id.into();
 6167        let (panel_id, item) = match leader_id {
 6168            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 6169            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 6170        };
 6171
 6172        let state = self.follower_states.get(&leader_id)?;
 6173        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 6174        let pane;
 6175        if let Some(panel_id) = panel_id {
 6176            pane = self
 6177                .activate_panel_for_proto_id(panel_id, window, cx)?
 6178                .pane(cx)?;
 6179            let state = self.follower_states.get_mut(&leader_id)?;
 6180            state.dock_pane = Some(pane.clone());
 6181        } else {
 6182            pane = state.center_pane.clone();
 6183            let state = self.follower_states.get_mut(&leader_id)?;
 6184            if let Some(dock_pane) = state.dock_pane.take() {
 6185                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 6186            }
 6187        }
 6188
 6189        pane.update(cx, |pane, cx| {
 6190            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 6191            if let Some(index) = pane.index_for_item(item.as_ref()) {
 6192                pane.activate_item(index, false, false, window, cx);
 6193            } else {
 6194                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 6195            }
 6196
 6197            if focus_active_item {
 6198                pane.focus_active_item(window, cx)
 6199            }
 6200        });
 6201
 6202        Some(item)
 6203    }
 6204
 6205    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 6206        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 6207        let active_view_id = state.active_view_id?;
 6208        Some(
 6209            state
 6210                .items_by_leader_view_id
 6211                .get(&active_view_id)?
 6212                .view
 6213                .boxed_clone(),
 6214        )
 6215    }
 6216
 6217    fn active_item_for_peer(
 6218        &self,
 6219        peer_id: PeerId,
 6220        window: &mut Window,
 6221        cx: &mut Context<Self>,
 6222    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 6223        let call = self.active_call()?;
 6224        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 6225        let leader_in_this_app;
 6226        let leader_in_this_project;
 6227        match participant.location {
 6228            ParticipantLocation::SharedProject { project_id } => {
 6229                leader_in_this_app = true;
 6230                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 6231            }
 6232            ParticipantLocation::UnsharedProject => {
 6233                leader_in_this_app = true;
 6234                leader_in_this_project = false;
 6235            }
 6236            ParticipantLocation::External => {
 6237                leader_in_this_app = false;
 6238                leader_in_this_project = false;
 6239            }
 6240        };
 6241        let state = self.follower_states.get(&peer_id.into())?;
 6242        let mut item_to_activate = None;
 6243        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 6244            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 6245                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 6246            {
 6247                item_to_activate = Some((item.location, item.view.boxed_clone()));
 6248            }
 6249        } else if let Some(shared_screen) =
 6250            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 6251        {
 6252            item_to_activate = Some((None, Box::new(shared_screen)));
 6253        }
 6254        item_to_activate
 6255    }
 6256
 6257    fn shared_screen_for_peer(
 6258        &self,
 6259        peer_id: PeerId,
 6260        pane: &Entity<Pane>,
 6261        window: &mut Window,
 6262        cx: &mut App,
 6263    ) -> Option<Entity<SharedScreen>> {
 6264        self.active_call()?
 6265            .create_shared_screen(peer_id, pane, window, cx)
 6266    }
 6267
 6268    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6269        if window.is_window_active() {
 6270            self.update_active_view_for_followers(window, cx);
 6271
 6272            if let Some(database_id) = self.database_id {
 6273                let db = WorkspaceDb::global(cx);
 6274                cx.background_spawn(async move { db.update_timestamp(database_id).await })
 6275                    .detach();
 6276            }
 6277        } else {
 6278            for pane in &self.panes {
 6279                pane.update(cx, |pane, cx| {
 6280                    if let Some(item) = pane.active_item() {
 6281                        item.workspace_deactivated(window, cx);
 6282                    }
 6283                    for item in pane.items() {
 6284                        if matches!(
 6285                            item.workspace_settings(cx).autosave,
 6286                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6287                        ) {
 6288                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6289                                .detach_and_log_err(cx);
 6290                        }
 6291                    }
 6292                });
 6293            }
 6294        }
 6295    }
 6296
 6297    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6298        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6299    }
 6300
 6301    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6302        self.active_call.as_ref().map(|(call, _)| call.clone())
 6303    }
 6304
 6305    fn on_active_call_event(
 6306        &mut self,
 6307        event: &ActiveCallEvent,
 6308        window: &mut Window,
 6309        cx: &mut Context<Self>,
 6310    ) {
 6311        match event {
 6312            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6313            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6314                self.leader_updated(participant_id, window, cx);
 6315            }
 6316        }
 6317    }
 6318
 6319    pub fn database_id(&self) -> Option<WorkspaceId> {
 6320        self.database_id
 6321    }
 6322
 6323    #[cfg(any(test, feature = "test-support"))]
 6324    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6325        self.database_id = Some(id);
 6326    }
 6327
 6328    pub fn session_id(&self) -> Option<String> {
 6329        self.session_id.clone()
 6330    }
 6331
 6332    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6333        let Some(display) = window.display(cx) else {
 6334            return Task::ready(());
 6335        };
 6336        let Ok(display_uuid) = display.uuid() else {
 6337            return Task::ready(());
 6338        };
 6339
 6340        let window_bounds = window.inner_window_bounds();
 6341        let database_id = self.database_id;
 6342        let has_paths = !self.root_paths(cx).is_empty();
 6343        let db = WorkspaceDb::global(cx);
 6344        let kvp = db::kvp::KeyValueStore::global(cx);
 6345
 6346        cx.background_executor().spawn(async move {
 6347            if !has_paths {
 6348                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6349                    .await
 6350                    .log_err();
 6351            }
 6352            if let Some(database_id) = database_id {
 6353                db.set_window_open_status(
 6354                    database_id,
 6355                    SerializedWindowBounds(window_bounds),
 6356                    display_uuid,
 6357                )
 6358                .await
 6359                .log_err();
 6360            } else {
 6361                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6362                    .await
 6363                    .log_err();
 6364            }
 6365        })
 6366    }
 6367
 6368    /// Bypass the 200ms serialization throttle and write workspace state to
 6369    /// the DB immediately. Returns a task the caller can await to ensure the
 6370    /// write completes. Used by the quit handler so the most recent state
 6371    /// isn't lost to a pending throttle timer when the process exits.
 6372    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6373        self._schedule_serialize_workspace.take();
 6374        self._serialize_workspace_task.take();
 6375        self.bounds_save_task_queued.take();
 6376
 6377        let bounds_task = self.save_window_bounds(window, cx);
 6378        let serialize_task = self.serialize_workspace_internal(window, cx);
 6379        cx.spawn(async move |_| {
 6380            bounds_task.await;
 6381            serialize_task.await;
 6382        })
 6383    }
 6384
 6385    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6386        let project = self.project().read(cx);
 6387        project
 6388            .visible_worktrees(cx)
 6389            .map(|worktree| worktree.read(cx).abs_path())
 6390            .collect::<Vec<_>>()
 6391    }
 6392
 6393    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6394        match member {
 6395            Member::Axis(PaneAxis { members, .. }) => {
 6396                for child in members.iter() {
 6397                    self.remove_panes(child.clone(), window, cx)
 6398                }
 6399            }
 6400            Member::Pane(pane) => {
 6401                self.force_remove_pane(&pane, &None, window, cx);
 6402            }
 6403        }
 6404    }
 6405
 6406    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6407        self.session_id.take();
 6408        self.serialize_workspace_internal(window, cx)
 6409    }
 6410
 6411    fn force_remove_pane(
 6412        &mut self,
 6413        pane: &Entity<Pane>,
 6414        focus_on: &Option<Entity<Pane>>,
 6415        window: &mut Window,
 6416        cx: &mut Context<Workspace>,
 6417    ) {
 6418        self.panes.retain(|p| p != pane);
 6419        if let Some(focus_on) = focus_on {
 6420            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6421        } else if self.active_pane() == pane {
 6422            self.panes
 6423                .last()
 6424                .unwrap()
 6425                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6426        }
 6427        if self.last_active_center_pane == Some(pane.downgrade()) {
 6428            self.last_active_center_pane = None;
 6429        }
 6430        cx.notify();
 6431    }
 6432
 6433    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6434        if self._schedule_serialize_workspace.is_none() {
 6435            self._schedule_serialize_workspace =
 6436                Some(cx.spawn_in(window, async move |this, cx| {
 6437                    cx.background_executor()
 6438                        .timer(SERIALIZATION_THROTTLE_TIME)
 6439                        .await;
 6440                    this.update_in(cx, |this, window, cx| {
 6441                        this._serialize_workspace_task =
 6442                            Some(this.serialize_workspace_internal(window, cx));
 6443                        this._schedule_serialize_workspace.take();
 6444                    })
 6445                    .log_err();
 6446                }));
 6447        }
 6448    }
 6449
 6450    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6451        let Some(database_id) = self.database_id() else {
 6452            return Task::ready(());
 6453        };
 6454
 6455        fn serialize_pane_handle(
 6456            pane_handle: &Entity<Pane>,
 6457            window: &mut Window,
 6458            cx: &mut App,
 6459        ) -> SerializedPane {
 6460            let (items, active, pinned_count) = {
 6461                let pane = pane_handle.read(cx);
 6462                let active_item_id = pane.active_item().map(|item| item.item_id());
 6463                (
 6464                    pane.items()
 6465                        .filter_map(|handle| {
 6466                            let handle = handle.to_serializable_item_handle(cx)?;
 6467
 6468                            Some(SerializedItem {
 6469                                kind: Arc::from(handle.serialized_item_kind()),
 6470                                item_id: handle.item_id().as_u64(),
 6471                                active: Some(handle.item_id()) == active_item_id,
 6472                                preview: pane.is_active_preview_item(handle.item_id()),
 6473                            })
 6474                        })
 6475                        .collect::<Vec<_>>(),
 6476                    pane.has_focus(window, cx),
 6477                    pane.pinned_count(),
 6478                )
 6479            };
 6480
 6481            SerializedPane::new(items, active, pinned_count)
 6482        }
 6483
 6484        fn build_serialized_pane_group(
 6485            pane_group: &Member,
 6486            window: &mut Window,
 6487            cx: &mut App,
 6488        ) -> SerializedPaneGroup {
 6489            match pane_group {
 6490                Member::Axis(PaneAxis {
 6491                    axis,
 6492                    members,
 6493                    flexes,
 6494                    bounding_boxes: _,
 6495                }) => SerializedPaneGroup::Group {
 6496                    axis: SerializedAxis(*axis),
 6497                    children: members
 6498                        .iter()
 6499                        .map(|member| build_serialized_pane_group(member, window, cx))
 6500                        .collect::<Vec<_>>(),
 6501                    flexes: Some(flexes.lock().clone()),
 6502                },
 6503                Member::Pane(pane_handle) => {
 6504                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6505                }
 6506            }
 6507        }
 6508
 6509        fn build_serialized_docks(
 6510            this: &Workspace,
 6511            window: &mut Window,
 6512            cx: &mut App,
 6513        ) -> DockStructure {
 6514            this.capture_dock_state(window, cx)
 6515        }
 6516
 6517        match self.workspace_location(cx) {
 6518            WorkspaceLocation::Location(location, paths) => {
 6519                let breakpoints = self.project.update(cx, |project, cx| {
 6520                    project
 6521                        .breakpoint_store()
 6522                        .read(cx)
 6523                        .all_source_breakpoints(cx)
 6524                });
 6525                let user_toolchains = self
 6526                    .project
 6527                    .read(cx)
 6528                    .user_toolchains(cx)
 6529                    .unwrap_or_default();
 6530
 6531                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6532                let docks = build_serialized_docks(self, window, cx);
 6533                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6534
 6535                let serialized_workspace = SerializedWorkspace {
 6536                    id: database_id,
 6537                    location,
 6538                    paths,
 6539                    center_group,
 6540                    window_bounds,
 6541                    display: Default::default(),
 6542                    docks,
 6543                    centered_layout: self.centered_layout,
 6544                    session_id: self.session_id.clone(),
 6545                    breakpoints,
 6546                    window_id: Some(window.window_handle().window_id().as_u64()),
 6547                    user_toolchains,
 6548                };
 6549
 6550                let db = WorkspaceDb::global(cx);
 6551                window.spawn(cx, async move |_| {
 6552                    db.save_workspace(serialized_workspace).await;
 6553                })
 6554            }
 6555            WorkspaceLocation::DetachFromSession => {
 6556                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6557                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6558                // Save dock state for empty local workspaces
 6559                let docks = build_serialized_docks(self, window, cx);
 6560                let db = WorkspaceDb::global(cx);
 6561                let kvp = db::kvp::KeyValueStore::global(cx);
 6562                window.spawn(cx, async move |_| {
 6563                    db.set_window_open_status(
 6564                        database_id,
 6565                        window_bounds,
 6566                        display.unwrap_or_default(),
 6567                    )
 6568                    .await
 6569                    .log_err();
 6570                    db.set_session_id(database_id, None).await.log_err();
 6571                    persistence::write_default_dock_state(&kvp, docks)
 6572                        .await
 6573                        .log_err();
 6574                })
 6575            }
 6576            WorkspaceLocation::None => {
 6577                // Save dock state for empty non-local workspaces
 6578                let docks = build_serialized_docks(self, window, cx);
 6579                let kvp = db::kvp::KeyValueStore::global(cx);
 6580                window.spawn(cx, async move |_| {
 6581                    persistence::write_default_dock_state(&kvp, docks)
 6582                        .await
 6583                        .log_err();
 6584                })
 6585            }
 6586        }
 6587    }
 6588
 6589    fn has_any_items_open(&self, cx: &App) -> bool {
 6590        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6591    }
 6592
 6593    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6594        let paths = PathList::new(&self.root_paths(cx));
 6595        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6596            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6597        } else if self.project.read(cx).is_local() {
 6598            if !paths.is_empty() || self.has_any_items_open(cx) {
 6599                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6600            } else {
 6601                WorkspaceLocation::DetachFromSession
 6602            }
 6603        } else {
 6604            WorkspaceLocation::None
 6605        }
 6606    }
 6607
 6608    fn update_history(&self, cx: &mut App) {
 6609        let Some(id) = self.database_id() else {
 6610            return;
 6611        };
 6612        if !self.project.read(cx).is_local() {
 6613            return;
 6614        }
 6615        if let Some(manager) = HistoryManager::global(cx) {
 6616            let paths = PathList::new(&self.root_paths(cx));
 6617            manager.update(cx, |this, cx| {
 6618                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6619            });
 6620        }
 6621    }
 6622
 6623    async fn serialize_items(
 6624        this: &WeakEntity<Self>,
 6625        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6626        cx: &mut AsyncWindowContext,
 6627    ) -> Result<()> {
 6628        const CHUNK_SIZE: usize = 200;
 6629
 6630        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6631
 6632        while let Some(items_received) = serializable_items.next().await {
 6633            let unique_items =
 6634                items_received
 6635                    .into_iter()
 6636                    .fold(HashMap::default(), |mut acc, item| {
 6637                        acc.entry(item.item_id()).or_insert(item);
 6638                        acc
 6639                    });
 6640
 6641            // We use into_iter() here so that the references to the items are moved into
 6642            // the tasks and not kept alive while we're sleeping.
 6643            for (_, item) in unique_items.into_iter() {
 6644                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6645                    item.serialize(workspace, false, window, cx)
 6646                }) {
 6647                    cx.background_spawn(async move { task.await.log_err() })
 6648                        .detach();
 6649                }
 6650            }
 6651
 6652            cx.background_executor()
 6653                .timer(SERIALIZATION_THROTTLE_TIME)
 6654                .await;
 6655        }
 6656
 6657        Ok(())
 6658    }
 6659
 6660    pub(crate) fn enqueue_item_serialization(
 6661        &mut self,
 6662        item: Box<dyn SerializableItemHandle>,
 6663    ) -> Result<()> {
 6664        self.serializable_items_tx
 6665            .unbounded_send(item)
 6666            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6667    }
 6668
 6669    pub(crate) fn load_workspace(
 6670        serialized_workspace: SerializedWorkspace,
 6671        paths_to_open: Vec<Option<ProjectPath>>,
 6672        window: &mut Window,
 6673        cx: &mut Context<Workspace>,
 6674    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6675        cx.spawn_in(window, async move |workspace, cx| {
 6676            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6677
 6678            let mut center_group = None;
 6679            let mut center_items = None;
 6680
 6681            // Traverse the splits tree and add to things
 6682            if let Some((group, active_pane, items)) = serialized_workspace
 6683                .center_group
 6684                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6685                .await
 6686            {
 6687                center_items = Some(items);
 6688                center_group = Some((group, active_pane))
 6689            }
 6690
 6691            let mut items_by_project_path = HashMap::default();
 6692            let mut item_ids_by_kind = HashMap::default();
 6693            let mut all_deserialized_items = Vec::default();
 6694            cx.update(|_, cx| {
 6695                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6696                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6697                        item_ids_by_kind
 6698                            .entry(serializable_item_handle.serialized_item_kind())
 6699                            .or_insert(Vec::new())
 6700                            .push(item.item_id().as_u64() as ItemId);
 6701                    }
 6702
 6703                    if let Some(project_path) = item.project_path(cx) {
 6704                        items_by_project_path.insert(project_path, item.clone());
 6705                    }
 6706                    all_deserialized_items.push(item);
 6707                }
 6708            })?;
 6709
 6710            let opened_items = paths_to_open
 6711                .into_iter()
 6712                .map(|path_to_open| {
 6713                    path_to_open
 6714                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6715                })
 6716                .collect::<Vec<_>>();
 6717
 6718            // Remove old panes from workspace panes list
 6719            workspace.update_in(cx, |workspace, window, cx| {
 6720                if let Some((center_group, active_pane)) = center_group {
 6721                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6722
 6723                    // Swap workspace center group
 6724                    workspace.center = PaneGroup::with_root(center_group);
 6725                    workspace.center.set_is_center(true);
 6726                    workspace.center.mark_positions(cx);
 6727
 6728                    if let Some(active_pane) = active_pane {
 6729                        workspace.set_active_pane(&active_pane, window, cx);
 6730                        cx.focus_self(window);
 6731                    } else {
 6732                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6733                    }
 6734                }
 6735
 6736                let docks = serialized_workspace.docks;
 6737
 6738                for (dock, serialized_dock) in [
 6739                    (&mut workspace.right_dock, docks.right),
 6740                    (&mut workspace.left_dock, docks.left),
 6741                    (&mut workspace.bottom_dock, docks.bottom),
 6742                ]
 6743                .iter_mut()
 6744                {
 6745                    dock.update(cx, |dock, cx| {
 6746                        dock.serialized_dock = Some(serialized_dock.clone());
 6747                        dock.restore_state(window, cx);
 6748                    });
 6749                }
 6750
 6751                cx.notify();
 6752            })?;
 6753
 6754            let _ = project
 6755                .update(cx, |project, cx| {
 6756                    project
 6757                        .breakpoint_store()
 6758                        .update(cx, |breakpoint_store, cx| {
 6759                            breakpoint_store
 6760                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6761                        })
 6762                })
 6763                .await;
 6764
 6765            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6766            // after loading the items, we might have different items and in order to avoid
 6767            // the database filling up, we delete items that haven't been loaded now.
 6768            //
 6769            // The items that have been loaded, have been saved after they've been added to the workspace.
 6770            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6771                item_ids_by_kind
 6772                    .into_iter()
 6773                    .map(|(item_kind, loaded_items)| {
 6774                        SerializableItemRegistry::cleanup(
 6775                            item_kind,
 6776                            serialized_workspace.id,
 6777                            loaded_items,
 6778                            window,
 6779                            cx,
 6780                        )
 6781                        .log_err()
 6782                    })
 6783                    .collect::<Vec<_>>()
 6784            })?;
 6785
 6786            futures::future::join_all(clean_up_tasks).await;
 6787
 6788            workspace
 6789                .update_in(cx, |workspace, window, cx| {
 6790                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6791                    workspace.serialize_workspace_internal(window, cx).detach();
 6792
 6793                    // Ensure that we mark the window as edited if we did load dirty items
 6794                    workspace.update_window_edited(window, cx);
 6795                })
 6796                .ok();
 6797
 6798            Ok(opened_items)
 6799        })
 6800    }
 6801
 6802    pub fn key_context(&self, cx: &App) -> KeyContext {
 6803        let mut context = KeyContext::new_with_defaults();
 6804        context.add("Workspace");
 6805        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6806        if let Some(status) = self
 6807            .debugger_provider
 6808            .as_ref()
 6809            .and_then(|provider| provider.active_thread_state(cx))
 6810        {
 6811            match status {
 6812                ThreadStatus::Running | ThreadStatus::Stepping => {
 6813                    context.add("debugger_running");
 6814                }
 6815                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6816                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6817            }
 6818        }
 6819
 6820        if self.left_dock.read(cx).is_open() {
 6821            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6822                context.set("left_dock", active_panel.panel_key());
 6823            }
 6824        }
 6825
 6826        if self.right_dock.read(cx).is_open() {
 6827            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6828                context.set("right_dock", active_panel.panel_key());
 6829            }
 6830        }
 6831
 6832        if self.bottom_dock.read(cx).is_open() {
 6833            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6834                context.set("bottom_dock", active_panel.panel_key());
 6835            }
 6836        }
 6837
 6838        context
 6839    }
 6840
 6841    /// Multiworkspace uses this to add workspace action handling to itself
 6842    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6843        self.add_workspace_actions_listeners(div, window, cx)
 6844            .on_action(cx.listener(
 6845                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6846                    for action in &action_sequence.0 {
 6847                        window.dispatch_action(action.boxed_clone(), cx);
 6848                    }
 6849                },
 6850            ))
 6851            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6852            .on_action(cx.listener(Self::close_all_items_and_panes))
 6853            .on_action(cx.listener(Self::close_item_in_all_panes))
 6854            .on_action(cx.listener(Self::save_all))
 6855            .on_action(cx.listener(Self::send_keystrokes))
 6856            .on_action(cx.listener(Self::add_folder_to_project))
 6857            .on_action(cx.listener(Self::follow_next_collaborator))
 6858            .on_action(cx.listener(Self::activate_pane_at_index))
 6859            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6860            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6861            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6862            .on_action(cx.listener(Self::toggle_theme_mode))
 6863            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6864                let pane = workspace.active_pane().clone();
 6865                workspace.unfollow_in_pane(&pane, window, cx);
 6866            }))
 6867            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6868                workspace
 6869                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6870                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6871            }))
 6872            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6873                workspace
 6874                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6875                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6876            }))
 6877            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6878                workspace
 6879                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6880                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6881            }))
 6882            .on_action(
 6883                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6884                    workspace.activate_previous_pane(window, cx)
 6885                }),
 6886            )
 6887            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6888                workspace.activate_next_pane(window, cx)
 6889            }))
 6890            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6891                workspace.activate_last_pane(window, cx)
 6892            }))
 6893            .on_action(
 6894                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6895                    workspace.activate_next_window(cx)
 6896                }),
 6897            )
 6898            .on_action(
 6899                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6900                    workspace.activate_previous_window(cx)
 6901                }),
 6902            )
 6903            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6904                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6905            }))
 6906            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6907                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6908            }))
 6909            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6910                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6911            }))
 6912            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6913                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6914            }))
 6915            .on_action(cx.listener(
 6916                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6917                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6918                },
 6919            ))
 6920            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6921                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6922            }))
 6923            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6924                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6925            }))
 6926            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6927                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6928            }))
 6929            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6930                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6931            }))
 6932            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6933                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6934                    SplitDirection::Down,
 6935                    SplitDirection::Up,
 6936                    SplitDirection::Right,
 6937                    SplitDirection::Left,
 6938                ];
 6939                for dir in DIRECTION_PRIORITY {
 6940                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6941                        workspace.swap_pane_in_direction(dir, cx);
 6942                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6943                        break;
 6944                    }
 6945                }
 6946            }))
 6947            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6948                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6949            }))
 6950            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6951                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6952            }))
 6953            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6954                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6955            }))
 6956            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6957                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6958            }))
 6959            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6960                this.toggle_dock(DockPosition::Left, window, cx);
 6961            }))
 6962            .on_action(cx.listener(
 6963                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6964                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6965                },
 6966            ))
 6967            .on_action(cx.listener(
 6968                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6969                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6970                },
 6971            ))
 6972            .on_action(cx.listener(
 6973                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6974                    if !workspace.close_active_dock(window, cx) {
 6975                        cx.propagate();
 6976                    }
 6977                },
 6978            ))
 6979            .on_action(
 6980                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6981                    workspace.close_all_docks(window, cx);
 6982                }),
 6983            )
 6984            .on_action(cx.listener(Self::toggle_all_docks))
 6985            .on_action(cx.listener(
 6986                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6987                    workspace.clear_all_notifications(cx);
 6988                },
 6989            ))
 6990            .on_action(cx.listener(
 6991                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6992                    workspace.clear_navigation_history(window, cx);
 6993                },
 6994            ))
 6995            .on_action(cx.listener(
 6996                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6997                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6998                        workspace.suppress_notification(&notification_id, cx);
 6999                    }
 7000                },
 7001            ))
 7002            .on_action(cx.listener(
 7003                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 7004                    workspace.show_worktree_trust_security_modal(true, window, cx);
 7005                },
 7006            ))
 7007            .on_action(
 7008                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 7009                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 7010                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 7011                            trusted_worktrees.clear_trusted_paths()
 7012                        });
 7013                        let db = WorkspaceDb::global(cx);
 7014                        cx.spawn(async move |_, cx| {
 7015                            if db.clear_trusted_worktrees().await.log_err().is_some() {
 7016                                cx.update(|cx| reload(cx));
 7017                            }
 7018                        })
 7019                        .detach();
 7020                    }
 7021                }),
 7022            )
 7023            .on_action(cx.listener(
 7024                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 7025                    workspace.reopen_closed_item(window, cx).detach();
 7026                },
 7027            ))
 7028            .on_action(cx.listener(
 7029                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 7030                    for dock in workspace.all_docks() {
 7031                        if dock.focus_handle(cx).contains_focused(window, cx) {
 7032                            let panel = dock.read(cx).active_panel().cloned();
 7033                            if let Some(panel) = panel {
 7034                                dock.update(cx, |dock, cx| {
 7035                                    dock.set_panel_size_state(
 7036                                        panel.as_ref(),
 7037                                        dock::PanelSizeState::default(),
 7038                                        cx,
 7039                                    );
 7040                                });
 7041                            }
 7042                            return;
 7043                        }
 7044                    }
 7045                },
 7046            ))
 7047            .on_action(cx.listener(
 7048                |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
 7049                    for dock in workspace.all_docks() {
 7050                        let panel = dock.read(cx).visible_panel().cloned();
 7051                        if let Some(panel) = panel {
 7052                            dock.update(cx, |dock, cx| {
 7053                                dock.set_panel_size_state(
 7054                                    panel.as_ref(),
 7055                                    dock::PanelSizeState::default(),
 7056                                    cx,
 7057                                );
 7058                            });
 7059                        }
 7060                    }
 7061                },
 7062            ))
 7063            .on_action(cx.listener(
 7064                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 7065                    adjust_active_dock_size_by_px(
 7066                        px_with_ui_font_fallback(act.px, cx),
 7067                        workspace,
 7068                        window,
 7069                        cx,
 7070                    );
 7071                },
 7072            ))
 7073            .on_action(cx.listener(
 7074                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 7075                    adjust_active_dock_size_by_px(
 7076                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7077                        workspace,
 7078                        window,
 7079                        cx,
 7080                    );
 7081                },
 7082            ))
 7083            .on_action(cx.listener(
 7084                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 7085                    adjust_open_docks_size_by_px(
 7086                        px_with_ui_font_fallback(act.px, cx),
 7087                        workspace,
 7088                        window,
 7089                        cx,
 7090                    );
 7091                },
 7092            ))
 7093            .on_action(cx.listener(
 7094                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 7095                    adjust_open_docks_size_by_px(
 7096                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7097                        workspace,
 7098                        window,
 7099                        cx,
 7100                    );
 7101                },
 7102            ))
 7103            .on_action(cx.listener(Workspace::toggle_centered_layout))
 7104            .on_action(cx.listener(
 7105                |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
 7106                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7107                        let dock = active_dock.read(cx);
 7108                        if let Some(active_panel) = dock.active_panel() {
 7109                            if active_panel.pane(cx).is_none() {
 7110                                let mut recent_pane: Option<Entity<Pane>> = None;
 7111                                let mut recent_timestamp = 0;
 7112                                for pane_handle in workspace.panes() {
 7113                                    let pane = pane_handle.read(cx);
 7114                                    for entry in pane.activation_history() {
 7115                                        if entry.timestamp > recent_timestamp {
 7116                                            recent_timestamp = entry.timestamp;
 7117                                            recent_pane = Some(pane_handle.clone());
 7118                                        }
 7119                                    }
 7120                                }
 7121
 7122                                if let Some(pane) = recent_pane {
 7123                                    let wrap_around = action.wrap_around;
 7124                                    pane.update(cx, |pane, cx| {
 7125                                        let current_index = pane.active_item_index();
 7126                                        let items_len = pane.items_len();
 7127                                        if items_len > 0 {
 7128                                            let next_index = if current_index + 1 < items_len {
 7129                                                current_index + 1
 7130                                            } else if wrap_around {
 7131                                                0
 7132                                            } else {
 7133                                                return;
 7134                                            };
 7135                                            pane.activate_item(
 7136                                                next_index, false, false, window, cx,
 7137                                            );
 7138                                        }
 7139                                    });
 7140                                    return;
 7141                                }
 7142                            }
 7143                        }
 7144                    }
 7145                    cx.propagate();
 7146                },
 7147            ))
 7148            .on_action(cx.listener(
 7149                |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
 7150                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7151                        let dock = active_dock.read(cx);
 7152                        if let Some(active_panel) = dock.active_panel() {
 7153                            if active_panel.pane(cx).is_none() {
 7154                                let mut recent_pane: Option<Entity<Pane>> = None;
 7155                                let mut recent_timestamp = 0;
 7156                                for pane_handle in workspace.panes() {
 7157                                    let pane = pane_handle.read(cx);
 7158                                    for entry in pane.activation_history() {
 7159                                        if entry.timestamp > recent_timestamp {
 7160                                            recent_timestamp = entry.timestamp;
 7161                                            recent_pane = Some(pane_handle.clone());
 7162                                        }
 7163                                    }
 7164                                }
 7165
 7166                                if let Some(pane) = recent_pane {
 7167                                    let wrap_around = action.wrap_around;
 7168                                    pane.update(cx, |pane, cx| {
 7169                                        let current_index = pane.active_item_index();
 7170                                        let items_len = pane.items_len();
 7171                                        if items_len > 0 {
 7172                                            let prev_index = if current_index > 0 {
 7173                                                current_index - 1
 7174                                            } else if wrap_around {
 7175                                                items_len.saturating_sub(1)
 7176                                            } else {
 7177                                                return;
 7178                                            };
 7179                                            pane.activate_item(
 7180                                                prev_index, false, false, window, cx,
 7181                                            );
 7182                                        }
 7183                                    });
 7184                                    return;
 7185                                }
 7186                            }
 7187                        }
 7188                    }
 7189                    cx.propagate();
 7190                },
 7191            ))
 7192            .on_action(cx.listener(
 7193                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 7194                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7195                        let dock = active_dock.read(cx);
 7196                        if let Some(active_panel) = dock.active_panel() {
 7197                            if active_panel.pane(cx).is_none() {
 7198                                let active_pane = workspace.active_pane().clone();
 7199                                active_pane.update(cx, |pane, cx| {
 7200                                    pane.close_active_item(action, window, cx)
 7201                                        .detach_and_log_err(cx);
 7202                                });
 7203                                return;
 7204                            }
 7205                        }
 7206                    }
 7207                    cx.propagate();
 7208                },
 7209            ))
 7210            .on_action(
 7211                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 7212                    let pane = workspace.active_pane().clone();
 7213                    if let Some(item) = pane.read(cx).active_item() {
 7214                        item.toggle_read_only(window, cx);
 7215                    }
 7216                }),
 7217            )
 7218            .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
 7219                workspace.focus_center_pane(window, cx);
 7220            }))
 7221            .on_action(cx.listener(Workspace::cancel))
 7222    }
 7223
 7224    #[cfg(any(test, feature = "test-support"))]
 7225    pub fn set_random_database_id(&mut self) {
 7226        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 7227    }
 7228
 7229    #[cfg(any(test, feature = "test-support"))]
 7230    pub(crate) fn test_new(
 7231        project: Entity<Project>,
 7232        window: &mut Window,
 7233        cx: &mut Context<Self>,
 7234    ) -> Self {
 7235        use node_runtime::NodeRuntime;
 7236        use session::Session;
 7237
 7238        let client = project.read(cx).client();
 7239        let user_store = project.read(cx).user_store();
 7240        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 7241        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 7242        window.activate_window();
 7243        let app_state = Arc::new(AppState {
 7244            languages: project.read(cx).languages().clone(),
 7245            workspace_store,
 7246            client,
 7247            user_store,
 7248            fs: project.read(cx).fs().clone(),
 7249            build_window_options: |_, _| Default::default(),
 7250            node_runtime: NodeRuntime::unavailable(),
 7251            session,
 7252        });
 7253        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 7254        workspace
 7255            .active_pane
 7256            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 7257        workspace
 7258    }
 7259
 7260    pub fn register_action<A: Action>(
 7261        &mut self,
 7262        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 7263    ) -> &mut Self {
 7264        let callback = Arc::new(callback);
 7265
 7266        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 7267            let callback = callback.clone();
 7268            div.on_action(cx.listener(move |workspace, event, window, cx| {
 7269                (callback)(workspace, event, window, cx)
 7270            }))
 7271        }));
 7272        self
 7273    }
 7274    pub fn register_action_renderer(
 7275        &mut self,
 7276        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 7277    ) -> &mut Self {
 7278        self.workspace_actions.push(Box::new(callback));
 7279        self
 7280    }
 7281
 7282    fn add_workspace_actions_listeners(
 7283        &self,
 7284        mut div: Div,
 7285        window: &mut Window,
 7286        cx: &mut Context<Self>,
 7287    ) -> Div {
 7288        for action in self.workspace_actions.iter() {
 7289            div = (action)(div, self, window, cx)
 7290        }
 7291        div
 7292    }
 7293
 7294    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 7295        self.modal_layer.read(cx).has_active_modal()
 7296    }
 7297
 7298    pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
 7299        self.modal_layer
 7300            .read(cx)
 7301            .is_active_modal_command_palette(cx)
 7302    }
 7303
 7304    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7305        self.modal_layer.read(cx).active_modal()
 7306    }
 7307
 7308    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7309    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7310    /// If no modal is active, the new modal will be shown.
 7311    ///
 7312    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7313    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7314    /// will not be shown.
 7315    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7316    where
 7317        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7318    {
 7319        self.modal_layer.update(cx, |modal_layer, cx| {
 7320            modal_layer.toggle_modal(window, cx, build)
 7321        })
 7322    }
 7323
 7324    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7325        self.modal_layer
 7326            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7327    }
 7328
 7329    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7330        self.toast_layer
 7331            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7332    }
 7333
 7334    pub fn toggle_centered_layout(
 7335        &mut self,
 7336        _: &ToggleCenteredLayout,
 7337        _: &mut Window,
 7338        cx: &mut Context<Self>,
 7339    ) {
 7340        self.centered_layout = !self.centered_layout;
 7341        if let Some(database_id) = self.database_id() {
 7342            let db = WorkspaceDb::global(cx);
 7343            let centered_layout = self.centered_layout;
 7344            cx.background_spawn(async move {
 7345                db.set_centered_layout(database_id, centered_layout).await
 7346            })
 7347            .detach_and_log_err(cx);
 7348        }
 7349        cx.notify();
 7350    }
 7351
 7352    fn adjust_padding(padding: Option<f32>) -> f32 {
 7353        padding
 7354            .unwrap_or(CenteredPaddingSettings::default().0)
 7355            .clamp(
 7356                CenteredPaddingSettings::MIN_PADDING,
 7357                CenteredPaddingSettings::MAX_PADDING,
 7358            )
 7359    }
 7360
 7361    fn render_dock(
 7362        &self,
 7363        position: DockPosition,
 7364        dock: &Entity<Dock>,
 7365        window: &mut Window,
 7366        cx: &mut App,
 7367    ) -> Option<Div> {
 7368        if self.zoomed_position == Some(position) {
 7369            return None;
 7370        }
 7371
 7372        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7373            let pane = panel.pane(cx)?;
 7374            let follower_states = &self.follower_states;
 7375            leader_border_for_pane(follower_states, &pane, window, cx)
 7376        });
 7377
 7378        let mut container = div()
 7379            .flex()
 7380            .overflow_hidden()
 7381            .flex_none()
 7382            .child(dock.clone())
 7383            .children(leader_border);
 7384
 7385        // Apply sizing only when the dock is open. When closed the dock is still
 7386        // included in the element tree so its focus handle remains mounted — without
 7387        // this, toggle_panel_focus cannot focus the panel when the dock is closed.
 7388        let dock = dock.read(cx);
 7389        if let Some(panel) = dock.visible_panel() {
 7390            let size_state = dock.stored_panel_size_state(panel.as_ref());
 7391            if position.axis() == Axis::Horizontal {
 7392                let use_flexible = panel.has_flexible_size(window, cx);
 7393                let flex_grow = if use_flexible {
 7394                    size_state
 7395                        .and_then(|state| state.flex)
 7396                        .or_else(|| self.default_dock_flex(position))
 7397                } else {
 7398                    None
 7399                };
 7400                if let Some(grow) = flex_grow {
 7401                    let grow = grow.max(0.001);
 7402                    let style = container.style();
 7403                    style.flex_grow = Some(grow);
 7404                    style.flex_shrink = Some(1.0);
 7405                    style.flex_basis = Some(relative(0.).into());
 7406                } else {
 7407                    let size = size_state
 7408                        .and_then(|state| state.size)
 7409                        .unwrap_or_else(|| panel.default_size(window, cx));
 7410                    container = container.w(size);
 7411                }
 7412            } else {
 7413                let size = size_state
 7414                    .and_then(|state| state.size)
 7415                    .unwrap_or_else(|| panel.default_size(window, cx));
 7416                container = container.h(size);
 7417            }
 7418        }
 7419
 7420        Some(container)
 7421    }
 7422
 7423    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7424        window
 7425            .root::<MultiWorkspace>()
 7426            .flatten()
 7427            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7428    }
 7429
 7430    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7431        self.zoomed.as_ref()
 7432    }
 7433
 7434    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7435        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7436            return;
 7437        };
 7438        let windows = cx.windows();
 7439        let next_window =
 7440            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7441                || {
 7442                    windows
 7443                        .iter()
 7444                        .cycle()
 7445                        .skip_while(|window| window.window_id() != current_window_id)
 7446                        .nth(1)
 7447                },
 7448            );
 7449
 7450        if let Some(window) = next_window {
 7451            window
 7452                .update(cx, |_, window, _| window.activate_window())
 7453                .ok();
 7454        }
 7455    }
 7456
 7457    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7458        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7459            return;
 7460        };
 7461        let windows = cx.windows();
 7462        let prev_window =
 7463            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7464                || {
 7465                    windows
 7466                        .iter()
 7467                        .rev()
 7468                        .cycle()
 7469                        .skip_while(|window| window.window_id() != current_window_id)
 7470                        .nth(1)
 7471                },
 7472            );
 7473
 7474        if let Some(window) = prev_window {
 7475            window
 7476                .update(cx, |_, window, _| window.activate_window())
 7477                .ok();
 7478        }
 7479    }
 7480
 7481    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7482        if cx.stop_active_drag(window) {
 7483        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7484            dismiss_app_notification(&notification_id, cx);
 7485        } else {
 7486            cx.propagate();
 7487        }
 7488    }
 7489
 7490    fn resize_dock(
 7491        &mut self,
 7492        dock_pos: DockPosition,
 7493        new_size: Pixels,
 7494        window: &mut Window,
 7495        cx: &mut Context<Self>,
 7496    ) {
 7497        match dock_pos {
 7498            DockPosition::Left => self.resize_left_dock(new_size, window, cx),
 7499            DockPosition::Right => self.resize_right_dock(new_size, window, cx),
 7500            DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
 7501        }
 7502    }
 7503
 7504    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7505        let workspace_width = self.bounds.size.width;
 7506        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7507
 7508        self.right_dock.read_with(cx, |right_dock, cx| {
 7509            let right_dock_size = right_dock
 7510                .stored_active_panel_size(window, cx)
 7511                .unwrap_or(Pixels::ZERO);
 7512            if right_dock_size + size > workspace_width {
 7513                size = workspace_width - right_dock_size
 7514            }
 7515        });
 7516
 7517        let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
 7518        self.left_dock.update(cx, |left_dock, cx| {
 7519            if WorkspaceSettings::get_global(cx)
 7520                .resize_all_panels_in_dock
 7521                .contains(&DockPosition::Left)
 7522            {
 7523                left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7524            } else {
 7525                left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7526            }
 7527        });
 7528    }
 7529
 7530    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7531        let workspace_width = self.bounds.size.width;
 7532        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7533        self.left_dock.read_with(cx, |left_dock, cx| {
 7534            let left_dock_size = left_dock
 7535                .stored_active_panel_size(window, cx)
 7536                .unwrap_or(Pixels::ZERO);
 7537            if left_dock_size + size > workspace_width {
 7538                size = workspace_width - left_dock_size
 7539            }
 7540        });
 7541        let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
 7542        self.right_dock.update(cx, |right_dock, cx| {
 7543            if WorkspaceSettings::get_global(cx)
 7544                .resize_all_panels_in_dock
 7545                .contains(&DockPosition::Right)
 7546            {
 7547                right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7548            } else {
 7549                right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7550            }
 7551        });
 7552    }
 7553
 7554    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7555        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7556        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7557            if WorkspaceSettings::get_global(cx)
 7558                .resize_all_panels_in_dock
 7559                .contains(&DockPosition::Bottom)
 7560            {
 7561                bottom_dock.resize_all_panels(Some(size), None, window, cx);
 7562            } else {
 7563                bottom_dock.resize_active_panel(Some(size), None, window, cx);
 7564            }
 7565        });
 7566    }
 7567
 7568    fn toggle_edit_predictions_all_files(
 7569        &mut self,
 7570        _: &ToggleEditPrediction,
 7571        _window: &mut Window,
 7572        cx: &mut Context<Self>,
 7573    ) {
 7574        let fs = self.project().read(cx).fs().clone();
 7575        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7576        update_settings_file(fs, cx, move |file, _| {
 7577            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7578        });
 7579    }
 7580
 7581    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7582        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7583        let next_mode = match current_mode {
 7584            Some(theme_settings::ThemeAppearanceMode::Light) => {
 7585                theme_settings::ThemeAppearanceMode::Dark
 7586            }
 7587            Some(theme_settings::ThemeAppearanceMode::Dark) => {
 7588                theme_settings::ThemeAppearanceMode::Light
 7589            }
 7590            Some(theme_settings::ThemeAppearanceMode::System) | None => {
 7591                match cx.theme().appearance() {
 7592                    theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
 7593                    theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
 7594                }
 7595            }
 7596        };
 7597
 7598        let fs = self.project().read(cx).fs().clone();
 7599        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7600            theme_settings::set_mode(settings, next_mode);
 7601        });
 7602    }
 7603
 7604    pub fn show_worktree_trust_security_modal(
 7605        &mut self,
 7606        toggle: bool,
 7607        window: &mut Window,
 7608        cx: &mut Context<Self>,
 7609    ) {
 7610        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7611            if toggle {
 7612                security_modal.update(cx, |security_modal, cx| {
 7613                    security_modal.dismiss(cx);
 7614                })
 7615            } else {
 7616                security_modal.update(cx, |security_modal, cx| {
 7617                    security_modal.refresh_restricted_paths(cx);
 7618                });
 7619            }
 7620        } else {
 7621            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7622                .map(|trusted_worktrees| {
 7623                    trusted_worktrees
 7624                        .read(cx)
 7625                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7626                })
 7627                .unwrap_or(false);
 7628            if has_restricted_worktrees {
 7629                let project = self.project().read(cx);
 7630                let remote_host = project
 7631                    .remote_connection_options(cx)
 7632                    .map(RemoteHostLocation::from);
 7633                let worktree_store = project.worktree_store().downgrade();
 7634                self.toggle_modal(window, cx, |_, cx| {
 7635                    SecurityModal::new(worktree_store, remote_host, cx)
 7636                });
 7637            }
 7638        }
 7639    }
 7640}
 7641
 7642pub trait AnyActiveCall {
 7643    fn entity(&self) -> AnyEntity;
 7644    fn is_in_room(&self, _: &App) -> bool;
 7645    fn room_id(&self, _: &App) -> Option<u64>;
 7646    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7647    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7648    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7649    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7650    fn is_sharing_project(&self, _: &App) -> bool;
 7651    fn has_remote_participants(&self, _: &App) -> bool;
 7652    fn local_participant_is_guest(&self, _: &App) -> bool;
 7653    fn client(&self, _: &App) -> Arc<Client>;
 7654    fn share_on_join(&self, _: &App) -> bool;
 7655    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7656    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7657    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7658    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7659    fn join_project(
 7660        &self,
 7661        _: u64,
 7662        _: Arc<LanguageRegistry>,
 7663        _: Arc<dyn Fs>,
 7664        _: &mut App,
 7665    ) -> Task<Result<Entity<Project>>>;
 7666    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7667    fn subscribe(
 7668        &self,
 7669        _: &mut Window,
 7670        _: &mut Context<Workspace>,
 7671        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7672    ) -> Subscription;
 7673    fn create_shared_screen(
 7674        &self,
 7675        _: PeerId,
 7676        _: &Entity<Pane>,
 7677        _: &mut Window,
 7678        _: &mut App,
 7679    ) -> Option<Entity<SharedScreen>>;
 7680}
 7681
 7682#[derive(Clone)]
 7683pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7684impl Global for GlobalAnyActiveCall {}
 7685
 7686impl GlobalAnyActiveCall {
 7687    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7688        cx.try_global()
 7689    }
 7690
 7691    pub(crate) fn global(cx: &App) -> &Self {
 7692        cx.global()
 7693    }
 7694}
 7695
 7696pub fn merge_conflict_notification_id() -> NotificationId {
 7697    struct MergeConflictNotification;
 7698    NotificationId::unique::<MergeConflictNotification>()
 7699}
 7700
 7701/// Workspace-local view of a remote participant's location.
 7702#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7703pub enum ParticipantLocation {
 7704    SharedProject { project_id: u64 },
 7705    UnsharedProject,
 7706    External,
 7707}
 7708
 7709impl ParticipantLocation {
 7710    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7711        match location
 7712            .and_then(|l| l.variant)
 7713            .context("participant location was not provided")?
 7714        {
 7715            proto::participant_location::Variant::SharedProject(project) => {
 7716                Ok(Self::SharedProject {
 7717                    project_id: project.id,
 7718                })
 7719            }
 7720            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7721            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7722        }
 7723    }
 7724}
 7725/// Workspace-local view of a remote collaborator's state.
 7726/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7727#[derive(Clone)]
 7728pub struct RemoteCollaborator {
 7729    pub user: Arc<User>,
 7730    pub peer_id: PeerId,
 7731    pub location: ParticipantLocation,
 7732    pub participant_index: ParticipantIndex,
 7733}
 7734
 7735pub enum ActiveCallEvent {
 7736    ParticipantLocationChanged { participant_id: PeerId },
 7737    RemoteVideoTracksChanged { participant_id: PeerId },
 7738}
 7739
 7740fn leader_border_for_pane(
 7741    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7742    pane: &Entity<Pane>,
 7743    _: &Window,
 7744    cx: &App,
 7745) -> Option<Div> {
 7746    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7747        if state.pane() == pane {
 7748            Some((*leader_id, state))
 7749        } else {
 7750            None
 7751        }
 7752    })?;
 7753
 7754    let mut leader_color = match leader_id {
 7755        CollaboratorId::PeerId(leader_peer_id) => {
 7756            let leader = GlobalAnyActiveCall::try_global(cx)?
 7757                .0
 7758                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7759
 7760            cx.theme()
 7761                .players()
 7762                .color_for_participant(leader.participant_index.0)
 7763                .cursor
 7764        }
 7765        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7766    };
 7767    leader_color.fade_out(0.3);
 7768    Some(
 7769        div()
 7770            .absolute()
 7771            .size_full()
 7772            .left_0()
 7773            .top_0()
 7774            .border_2()
 7775            .border_color(leader_color),
 7776    )
 7777}
 7778
 7779fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7780    ZED_WINDOW_POSITION
 7781        .zip(*ZED_WINDOW_SIZE)
 7782        .map(|(position, size)| Bounds {
 7783            origin: position,
 7784            size,
 7785        })
 7786}
 7787
 7788fn open_items(
 7789    serialized_workspace: Option<SerializedWorkspace>,
 7790    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7791    window: &mut Window,
 7792    cx: &mut Context<Workspace>,
 7793) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7794    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7795        Workspace::load_workspace(
 7796            serialized_workspace,
 7797            project_paths_to_open
 7798                .iter()
 7799                .map(|(_, project_path)| project_path)
 7800                .cloned()
 7801                .collect(),
 7802            window,
 7803            cx,
 7804        )
 7805    });
 7806
 7807    cx.spawn_in(window, async move |workspace, cx| {
 7808        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7809
 7810        if let Some(restored_items) = restored_items {
 7811            let restored_items = restored_items.await?;
 7812
 7813            let restored_project_paths = restored_items
 7814                .iter()
 7815                .filter_map(|item| {
 7816                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7817                        .ok()
 7818                        .flatten()
 7819                })
 7820                .collect::<HashSet<_>>();
 7821
 7822            for restored_item in restored_items {
 7823                opened_items.push(restored_item.map(Ok));
 7824            }
 7825
 7826            project_paths_to_open
 7827                .iter_mut()
 7828                .for_each(|(_, project_path)| {
 7829                    if let Some(project_path_to_open) = project_path
 7830                        && restored_project_paths.contains(project_path_to_open)
 7831                    {
 7832                        *project_path = None;
 7833                    }
 7834                });
 7835        } else {
 7836            for _ in 0..project_paths_to_open.len() {
 7837                opened_items.push(None);
 7838            }
 7839        }
 7840        assert!(opened_items.len() == project_paths_to_open.len());
 7841
 7842        let tasks =
 7843            project_paths_to_open
 7844                .into_iter()
 7845                .enumerate()
 7846                .map(|(ix, (abs_path, project_path))| {
 7847                    let workspace = workspace.clone();
 7848                    cx.spawn(async move |cx| {
 7849                        let file_project_path = project_path?;
 7850                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7851                            workspace.project().update(cx, |project, cx| {
 7852                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7853                            })
 7854                        });
 7855
 7856                        // We only want to open file paths here. If one of the items
 7857                        // here is a directory, it was already opened further above
 7858                        // with a `find_or_create_worktree`.
 7859                        if let Ok(task) = abs_path_task
 7860                            && task.await.is_none_or(|p| p.is_file())
 7861                        {
 7862                            return Some((
 7863                                ix,
 7864                                workspace
 7865                                    .update_in(cx, |workspace, window, cx| {
 7866                                        workspace.open_path(
 7867                                            file_project_path,
 7868                                            None,
 7869                                            true,
 7870                                            window,
 7871                                            cx,
 7872                                        )
 7873                                    })
 7874                                    .log_err()?
 7875                                    .await,
 7876                            ));
 7877                        }
 7878                        None
 7879                    })
 7880                });
 7881
 7882        let tasks = tasks.collect::<Vec<_>>();
 7883
 7884        let tasks = futures::future::join_all(tasks);
 7885        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7886            opened_items[ix] = Some(path_open_result);
 7887        }
 7888
 7889        Ok(opened_items)
 7890    })
 7891}
 7892
 7893#[derive(Clone)]
 7894enum ActivateInDirectionTarget {
 7895    Pane(Entity<Pane>),
 7896    Dock(Entity<Dock>),
 7897    Sidebar(FocusHandle),
 7898}
 7899
 7900fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7901    window
 7902        .update(cx, |multi_workspace, _, cx| {
 7903            let workspace = multi_workspace.workspace().clone();
 7904            workspace.update(cx, |workspace, cx| {
 7905                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7906                    struct DatabaseFailedNotification;
 7907
 7908                    workspace.show_notification(
 7909                        NotificationId::unique::<DatabaseFailedNotification>(),
 7910                        cx,
 7911                        |cx| {
 7912                            cx.new(|cx| {
 7913                                MessageNotification::new("Failed to load the database file.", cx)
 7914                                    .primary_message("File an Issue")
 7915                                    .primary_icon(IconName::Plus)
 7916                                    .primary_on_click(|window, cx| {
 7917                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7918                                    })
 7919                            })
 7920                        },
 7921                    );
 7922                }
 7923            });
 7924        })
 7925        .log_err();
 7926}
 7927
 7928fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7929    if val == 0 {
 7930        ThemeSettings::get_global(cx).ui_font_size(cx)
 7931    } else {
 7932        px(val as f32)
 7933    }
 7934}
 7935
 7936fn adjust_active_dock_size_by_px(
 7937    px: Pixels,
 7938    workspace: &mut Workspace,
 7939    window: &mut Window,
 7940    cx: &mut Context<Workspace>,
 7941) {
 7942    let Some(active_dock) = workspace
 7943        .all_docks()
 7944        .into_iter()
 7945        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7946    else {
 7947        return;
 7948    };
 7949    let dock = active_dock.read(cx);
 7950    let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
 7951        return;
 7952    };
 7953    workspace.resize_dock(dock.position(), panel_size + px, window, cx);
 7954}
 7955
 7956fn adjust_open_docks_size_by_px(
 7957    px: Pixels,
 7958    workspace: &mut Workspace,
 7959    window: &mut Window,
 7960    cx: &mut Context<Workspace>,
 7961) {
 7962    let docks = workspace
 7963        .all_docks()
 7964        .into_iter()
 7965        .filter_map(|dock_entity| {
 7966            let dock = dock_entity.read(cx);
 7967            if dock.is_open() {
 7968                let dock_pos = dock.position();
 7969                let panel_size = workspace.dock_size(&dock, window, cx)?;
 7970                Some((dock_pos, panel_size + px))
 7971            } else {
 7972                None
 7973            }
 7974        })
 7975        .collect::<Vec<_>>();
 7976
 7977    for (position, new_size) in docks {
 7978        workspace.resize_dock(position, new_size, window, cx);
 7979    }
 7980}
 7981
 7982impl Focusable for Workspace {
 7983    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7984        self.active_pane.focus_handle(cx)
 7985    }
 7986}
 7987
 7988#[derive(Clone)]
 7989struct DraggedDock(DockPosition);
 7990
 7991impl Render for DraggedDock {
 7992    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7993        gpui::Empty
 7994    }
 7995}
 7996
 7997impl Render for Workspace {
 7998    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 7999        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 8000        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 8001            log::info!("Rendered first frame");
 8002        }
 8003
 8004        let centered_layout = self.centered_layout
 8005            && self.center.panes().len() == 1
 8006            && self.active_item(cx).is_some();
 8007        let render_padding = |size| {
 8008            (size > 0.0).then(|| {
 8009                div()
 8010                    .h_full()
 8011                    .w(relative(size))
 8012                    .bg(cx.theme().colors().editor_background)
 8013                    .border_color(cx.theme().colors().pane_group_border)
 8014            })
 8015        };
 8016        let paddings = if centered_layout {
 8017            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 8018            (
 8019                render_padding(Self::adjust_padding(
 8020                    settings.left_padding.map(|padding| padding.0),
 8021                )),
 8022                render_padding(Self::adjust_padding(
 8023                    settings.right_padding.map(|padding| padding.0),
 8024                )),
 8025            )
 8026        } else {
 8027            (None, None)
 8028        };
 8029        let ui_font = theme_settings::setup_ui_font(window, cx);
 8030
 8031        let theme = cx.theme().clone();
 8032        let colors = theme.colors();
 8033        let notification_entities = self
 8034            .notifications
 8035            .iter()
 8036            .map(|(_, notification)| notification.entity_id())
 8037            .collect::<Vec<_>>();
 8038        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 8039
 8040        div()
 8041            .relative()
 8042            .size_full()
 8043            .flex()
 8044            .flex_col()
 8045            .font(ui_font)
 8046            .gap_0()
 8047                .justify_start()
 8048                .items_start()
 8049                .text_color(colors.text)
 8050                .overflow_hidden()
 8051                .children(self.titlebar_item.clone())
 8052                .on_modifiers_changed(move |_, _, cx| {
 8053                    for &id in &notification_entities {
 8054                        cx.notify(id);
 8055                    }
 8056                })
 8057                .child(
 8058                    div()
 8059                        .size_full()
 8060                        .relative()
 8061                        .flex_1()
 8062                        .flex()
 8063                        .flex_col()
 8064                        .child(
 8065                            div()
 8066                                .id("workspace")
 8067                                .bg(colors.background)
 8068                                .relative()
 8069                                .flex_1()
 8070                                .w_full()
 8071                                .flex()
 8072                                .flex_col()
 8073                                .overflow_hidden()
 8074                                .border_t_1()
 8075                                .border_b_1()
 8076                                .border_color(colors.border)
 8077                                .child({
 8078                                    let this = cx.entity();
 8079                                    canvas(
 8080                                        move |bounds, window, cx| {
 8081                                            this.update(cx, |this, cx| {
 8082                                                let bounds_changed = this.bounds != bounds;
 8083                                                this.bounds = bounds;
 8084
 8085                                                if bounds_changed {
 8086                                                    this.left_dock.update(cx, |dock, cx| {
 8087                                                        dock.clamp_panel_size(
 8088                                                            bounds.size.width,
 8089                                                            window,
 8090                                                            cx,
 8091                                                        )
 8092                                                    });
 8093
 8094                                                    this.right_dock.update(cx, |dock, cx| {
 8095                                                        dock.clamp_panel_size(
 8096                                                            bounds.size.width,
 8097                                                            window,
 8098                                                            cx,
 8099                                                        )
 8100                                                    });
 8101
 8102                                                    this.bottom_dock.update(cx, |dock, cx| {
 8103                                                        dock.clamp_panel_size(
 8104                                                            bounds.size.height,
 8105                                                            window,
 8106                                                            cx,
 8107                                                        )
 8108                                                    });
 8109                                                }
 8110                                            })
 8111                                        },
 8112                                        |_, _, _, _| {},
 8113                                    )
 8114                                    .absolute()
 8115                                    .size_full()
 8116                                })
 8117                                .when(self.zoomed.is_none(), |this| {
 8118                                    this.on_drag_move(cx.listener(
 8119                                        move |workspace,
 8120                                              e: &DragMoveEvent<DraggedDock>,
 8121                                              window,
 8122                                              cx| {
 8123                                            if workspace.previous_dock_drag_coordinates
 8124                                                != Some(e.event.position)
 8125                                            {
 8126                                                workspace.previous_dock_drag_coordinates =
 8127                                                    Some(e.event.position);
 8128
 8129                                                match e.drag(cx).0 {
 8130                                                    DockPosition::Left => {
 8131                                                        workspace.resize_left_dock(
 8132                                                            e.event.position.x
 8133                                                                - workspace.bounds.left(),
 8134                                                            window,
 8135                                                            cx,
 8136                                                        );
 8137                                                    }
 8138                                                    DockPosition::Right => {
 8139                                                        workspace.resize_right_dock(
 8140                                                            workspace.bounds.right()
 8141                                                                - e.event.position.x,
 8142                                                            window,
 8143                                                            cx,
 8144                                                        );
 8145                                                    }
 8146                                                    DockPosition::Bottom => {
 8147                                                        workspace.resize_bottom_dock(
 8148                                                            workspace.bounds.bottom()
 8149                                                                - e.event.position.y,
 8150                                                            window,
 8151                                                            cx,
 8152                                                        );
 8153                                                    }
 8154                                                };
 8155                                                workspace.serialize_workspace(window, cx);
 8156                                            }
 8157                                        },
 8158                                    ))
 8159
 8160                                })
 8161                                .child({
 8162                                    match bottom_dock_layout {
 8163                                        BottomDockLayout::Full => div()
 8164                                            .flex()
 8165                                            .flex_col()
 8166                                            .h_full()
 8167                                            .child(
 8168                                                div()
 8169                                                    .flex()
 8170                                                    .flex_row()
 8171                                                    .flex_1()
 8172                                                    .overflow_hidden()
 8173                                                    .children(self.render_dock(
 8174                                                        DockPosition::Left,
 8175                                                        &self.left_dock,
 8176                                                        window,
 8177                                                        cx,
 8178                                                    ))
 8179
 8180                                                    .child(
 8181                                                        div()
 8182                                                            .flex()
 8183                                                            .flex_col()
 8184                                                            .flex_1()
 8185                                                            .overflow_hidden()
 8186                                                            .child(
 8187                                                                h_flex()
 8188                                                                    .flex_1()
 8189                                                                    .when_some(
 8190                                                                        paddings.0,
 8191                                                                        |this, p| {
 8192                                                                            this.child(
 8193                                                                                p.border_r_1(),
 8194                                                                            )
 8195                                                                        },
 8196                                                                    )
 8197                                                                    .child(self.center.render(
 8198                                                                        self.zoomed.as_ref(),
 8199                                                                        &PaneRenderContext {
 8200                                                                            follower_states:
 8201                                                                                &self.follower_states,
 8202                                                                            active_call: self.active_call(),
 8203                                                                            active_pane: &self.active_pane,
 8204                                                                            app_state: &self.app_state,
 8205                                                                            project: &self.project,
 8206                                                                            workspace: &self.weak_self,
 8207                                                                        },
 8208                                                                        window,
 8209                                                                        cx,
 8210                                                                    ))
 8211                                                                    .when_some(
 8212                                                                        paddings.1,
 8213                                                                        |this, p| {
 8214                                                                            this.child(
 8215                                                                                p.border_l_1(),
 8216                                                                            )
 8217                                                                        },
 8218                                                                    ),
 8219                                                            ),
 8220                                                    )
 8221
 8222                                                    .children(self.render_dock(
 8223                                                        DockPosition::Right,
 8224                                                        &self.right_dock,
 8225                                                        window,
 8226                                                        cx,
 8227                                                    )),
 8228                                            )
 8229                                            .child(div().w_full().children(self.render_dock(
 8230                                                DockPosition::Bottom,
 8231                                                &self.bottom_dock,
 8232                                                window,
 8233                                                cx
 8234                                            ))),
 8235
 8236                                        BottomDockLayout::LeftAligned => div()
 8237                                            .flex()
 8238                                            .flex_row()
 8239                                            .h_full()
 8240                                            .child(
 8241                                                div()
 8242                                                    .flex()
 8243                                                    .flex_col()
 8244                                                    .flex_1()
 8245                                                    .h_full()
 8246                                                    .child(
 8247                                                        div()
 8248                                                            .flex()
 8249                                                            .flex_row()
 8250                                                            .flex_1()
 8251                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 8252
 8253                                                            .child(
 8254                                                                div()
 8255                                                                    .flex()
 8256                                                                    .flex_col()
 8257                                                                    .flex_1()
 8258                                                                    .overflow_hidden()
 8259                                                                    .child(
 8260                                                                        h_flex()
 8261                                                                            .flex_1()
 8262                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8263                                                                            .child(self.center.render(
 8264                                                                                self.zoomed.as_ref(),
 8265                                                                                &PaneRenderContext {
 8266                                                                                    follower_states:
 8267                                                                                        &self.follower_states,
 8268                                                                                    active_call: self.active_call(),
 8269                                                                                    active_pane: &self.active_pane,
 8270                                                                                    app_state: &self.app_state,
 8271                                                                                    project: &self.project,
 8272                                                                                    workspace: &self.weak_self,
 8273                                                                                },
 8274                                                                                window,
 8275                                                                                cx,
 8276                                                                            ))
 8277                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8278                                                                    )
 8279                                                            )
 8280
 8281                                                    )
 8282                                                    .child(
 8283                                                        div()
 8284                                                            .w_full()
 8285                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8286                                                    ),
 8287                                            )
 8288                                            .children(self.render_dock(
 8289                                                DockPosition::Right,
 8290                                                &self.right_dock,
 8291                                                window,
 8292                                                cx,
 8293                                            )),
 8294                                        BottomDockLayout::RightAligned => div()
 8295                                            .flex()
 8296                                            .flex_row()
 8297                                            .h_full()
 8298                                            .children(self.render_dock(
 8299                                                DockPosition::Left,
 8300                                                &self.left_dock,
 8301                                                window,
 8302                                                cx,
 8303                                            ))
 8304
 8305                                            .child(
 8306                                                div()
 8307                                                    .flex()
 8308                                                    .flex_col()
 8309                                                    .flex_1()
 8310                                                    .h_full()
 8311                                                    .child(
 8312                                                        div()
 8313                                                            .flex()
 8314                                                            .flex_row()
 8315                                                            .flex_1()
 8316                                                            .child(
 8317                                                                div()
 8318                                                                    .flex()
 8319                                                                    .flex_col()
 8320                                                                    .flex_1()
 8321                                                                    .overflow_hidden()
 8322                                                                    .child(
 8323                                                                        h_flex()
 8324                                                                            .flex_1()
 8325                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8326                                                                            .child(self.center.render(
 8327                                                                                self.zoomed.as_ref(),
 8328                                                                                &PaneRenderContext {
 8329                                                                                    follower_states:
 8330                                                                                        &self.follower_states,
 8331                                                                                    active_call: self.active_call(),
 8332                                                                                    active_pane: &self.active_pane,
 8333                                                                                    app_state: &self.app_state,
 8334                                                                                    project: &self.project,
 8335                                                                                    workspace: &self.weak_self,
 8336                                                                                },
 8337                                                                                window,
 8338                                                                                cx,
 8339                                                                            ))
 8340                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8341                                                                    )
 8342                                                            )
 8343
 8344                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 8345                                                    )
 8346                                                    .child(
 8347                                                        div()
 8348                                                            .w_full()
 8349                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8350                                                    ),
 8351                                            ),
 8352                                        BottomDockLayout::Contained => div()
 8353                                            .flex()
 8354                                            .flex_row()
 8355                                            .h_full()
 8356                                            .children(self.render_dock(
 8357                                                DockPosition::Left,
 8358                                                &self.left_dock,
 8359                                                window,
 8360                                                cx,
 8361                                            ))
 8362
 8363                                            .child(
 8364                                                div()
 8365                                                    .flex()
 8366                                                    .flex_col()
 8367                                                    .flex_1()
 8368                                                    .overflow_hidden()
 8369                                                    .child(
 8370                                                        h_flex()
 8371                                                            .flex_1()
 8372                                                            .when_some(paddings.0, |this, p| {
 8373                                                                this.child(p.border_r_1())
 8374                                                            })
 8375                                                            .child(self.center.render(
 8376                                                                self.zoomed.as_ref(),
 8377                                                                &PaneRenderContext {
 8378                                                                    follower_states:
 8379                                                                        &self.follower_states,
 8380                                                                    active_call: self.active_call(),
 8381                                                                    active_pane: &self.active_pane,
 8382                                                                    app_state: &self.app_state,
 8383                                                                    project: &self.project,
 8384                                                                    workspace: &self.weak_self,
 8385                                                                },
 8386                                                                window,
 8387                                                                cx,
 8388                                                            ))
 8389                                                            .when_some(paddings.1, |this, p| {
 8390                                                                this.child(p.border_l_1())
 8391                                                            }),
 8392                                                    )
 8393                                                    .children(self.render_dock(
 8394                                                        DockPosition::Bottom,
 8395                                                        &self.bottom_dock,
 8396                                                        window,
 8397                                                        cx,
 8398                                                    )),
 8399                                            )
 8400
 8401                                            .children(self.render_dock(
 8402                                                DockPosition::Right,
 8403                                                &self.right_dock,
 8404                                                window,
 8405                                                cx,
 8406                                            )),
 8407                                    }
 8408                                })
 8409                                .children(self.zoomed.as_ref().and_then(|view| {
 8410                                    let zoomed_view = view.upgrade()?;
 8411                                    let div = div()
 8412                                        .occlude()
 8413                                        .absolute()
 8414                                        .overflow_hidden()
 8415                                        .border_color(colors.border)
 8416                                        .bg(colors.background)
 8417                                        .child(zoomed_view)
 8418                                        .inset_0()
 8419                                        .shadow_lg();
 8420
 8421                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8422                                       return Some(div);
 8423                                    }
 8424
 8425                                    Some(match self.zoomed_position {
 8426                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8427                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8428                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8429                                        None => {
 8430                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8431                                        }
 8432                                    })
 8433                                }))
 8434                                .children(self.render_notifications(window, cx)),
 8435                        )
 8436                        .when(self.status_bar_visible(cx), |parent| {
 8437                            parent.child(self.status_bar.clone())
 8438                        })
 8439                        .child(self.toast_layer.clone()),
 8440                )
 8441    }
 8442}
 8443
 8444impl WorkspaceStore {
 8445    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8446        Self {
 8447            workspaces: Default::default(),
 8448            _subscriptions: vec![
 8449                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8450                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8451            ],
 8452            client,
 8453        }
 8454    }
 8455
 8456    pub fn update_followers(
 8457        &self,
 8458        project_id: Option<u64>,
 8459        update: proto::update_followers::Variant,
 8460        cx: &App,
 8461    ) -> Option<()> {
 8462        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8463        let room_id = active_call.0.room_id(cx)?;
 8464        self.client
 8465            .send(proto::UpdateFollowers {
 8466                room_id,
 8467                project_id,
 8468                variant: Some(update),
 8469            })
 8470            .log_err()
 8471    }
 8472
 8473    pub async fn handle_follow(
 8474        this: Entity<Self>,
 8475        envelope: TypedEnvelope<proto::Follow>,
 8476        mut cx: AsyncApp,
 8477    ) -> Result<proto::FollowResponse> {
 8478        this.update(&mut cx, |this, cx| {
 8479            let follower = Follower {
 8480                project_id: envelope.payload.project_id,
 8481                peer_id: envelope.original_sender_id()?,
 8482            };
 8483
 8484            let mut response = proto::FollowResponse::default();
 8485
 8486            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8487                let Some(workspace) = weak_workspace.upgrade() else {
 8488                    return false;
 8489                };
 8490                window_handle
 8491                    .update(cx, |_, window, cx| {
 8492                        workspace.update(cx, |workspace, cx| {
 8493                            let handler_response =
 8494                                workspace.handle_follow(follower.project_id, window, cx);
 8495                            if let Some(active_view) = handler_response.active_view
 8496                                && workspace.project.read(cx).remote_id() == follower.project_id
 8497                            {
 8498                                response.active_view = Some(active_view)
 8499                            }
 8500                        });
 8501                    })
 8502                    .is_ok()
 8503            });
 8504
 8505            Ok(response)
 8506        })
 8507    }
 8508
 8509    async fn handle_update_followers(
 8510        this: Entity<Self>,
 8511        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8512        mut cx: AsyncApp,
 8513    ) -> Result<()> {
 8514        let leader_id = envelope.original_sender_id()?;
 8515        let update = envelope.payload;
 8516
 8517        this.update(&mut cx, |this, cx| {
 8518            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8519                let Some(workspace) = weak_workspace.upgrade() else {
 8520                    return false;
 8521                };
 8522                window_handle
 8523                    .update(cx, |_, window, cx| {
 8524                        workspace.update(cx, |workspace, cx| {
 8525                            let project_id = workspace.project.read(cx).remote_id();
 8526                            if update.project_id != project_id && update.project_id.is_some() {
 8527                                return;
 8528                            }
 8529                            workspace.handle_update_followers(
 8530                                leader_id,
 8531                                update.clone(),
 8532                                window,
 8533                                cx,
 8534                            );
 8535                        });
 8536                    })
 8537                    .is_ok()
 8538            });
 8539            Ok(())
 8540        })
 8541    }
 8542
 8543    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8544        self.workspaces.iter().map(|(_, weak)| weak)
 8545    }
 8546
 8547    pub fn workspaces_with_windows(
 8548        &self,
 8549    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8550        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8551    }
 8552}
 8553
 8554impl ViewId {
 8555    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8556        Ok(Self {
 8557            creator: message
 8558                .creator
 8559                .map(CollaboratorId::PeerId)
 8560                .context("creator is missing")?,
 8561            id: message.id,
 8562        })
 8563    }
 8564
 8565    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8566        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8567            Some(proto::ViewId {
 8568                creator: Some(peer_id),
 8569                id: self.id,
 8570            })
 8571        } else {
 8572            None
 8573        }
 8574    }
 8575}
 8576
 8577impl FollowerState {
 8578    fn pane(&self) -> &Entity<Pane> {
 8579        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8580    }
 8581}
 8582
 8583pub trait WorkspaceHandle {
 8584    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8585}
 8586
 8587impl WorkspaceHandle for Entity<Workspace> {
 8588    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8589        self.read(cx)
 8590            .worktrees(cx)
 8591            .flat_map(|worktree| {
 8592                let worktree_id = worktree.read(cx).id();
 8593                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8594                    worktree_id,
 8595                    path: f.path.clone(),
 8596                })
 8597            })
 8598            .collect::<Vec<_>>()
 8599    }
 8600}
 8601
 8602pub async fn last_opened_workspace_location(
 8603    db: &WorkspaceDb,
 8604    fs: &dyn fs::Fs,
 8605) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8606    db.last_workspace(fs)
 8607        .await
 8608        .log_err()
 8609        .flatten()
 8610        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8611}
 8612
 8613pub async fn last_session_workspace_locations(
 8614    db: &WorkspaceDb,
 8615    last_session_id: &str,
 8616    last_session_window_stack: Option<Vec<WindowId>>,
 8617    fs: &dyn fs::Fs,
 8618) -> Option<Vec<SessionWorkspace>> {
 8619    db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8620        .await
 8621        .log_err()
 8622}
 8623
 8624pub struct MultiWorkspaceRestoreResult {
 8625    pub window_handle: WindowHandle<MultiWorkspace>,
 8626    pub errors: Vec<anyhow::Error>,
 8627}
 8628
 8629pub async fn restore_multiworkspace(
 8630    multi_workspace: SerializedMultiWorkspace,
 8631    app_state: Arc<AppState>,
 8632    cx: &mut AsyncApp,
 8633) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8634    let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
 8635    let mut group_iter = workspaces.into_iter();
 8636    let first = group_iter
 8637        .next()
 8638        .context("window group must not be empty")?;
 8639
 8640    let window_handle = if first.paths.is_empty() {
 8641        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8642            .await?
 8643    } else {
 8644        let OpenResult { window, .. } = cx
 8645            .update(|cx| {
 8646                Workspace::new_local(
 8647                    first.paths.paths().to_vec(),
 8648                    app_state.clone(),
 8649                    None,
 8650                    None,
 8651                    None,
 8652                    OpenMode::Activate,
 8653                    cx,
 8654                )
 8655            })
 8656            .await?;
 8657        window
 8658    };
 8659
 8660    let mut errors = Vec::new();
 8661
 8662    for session_workspace in group_iter {
 8663        let error = if session_workspace.paths.is_empty() {
 8664            cx.update(|cx| {
 8665                open_workspace_by_id(
 8666                    session_workspace.workspace_id,
 8667                    app_state.clone(),
 8668                    Some(window_handle),
 8669                    cx,
 8670                )
 8671            })
 8672            .await
 8673            .err()
 8674        } else {
 8675            cx.update(|cx| {
 8676                Workspace::new_local(
 8677                    session_workspace.paths.paths().to_vec(),
 8678                    app_state.clone(),
 8679                    Some(window_handle),
 8680                    None,
 8681                    None,
 8682                    OpenMode::Add,
 8683                    cx,
 8684                )
 8685            })
 8686            .await
 8687            .err()
 8688        };
 8689
 8690        if let Some(error) = error {
 8691            errors.push(error);
 8692        }
 8693    }
 8694
 8695    if let Some(target_id) = state.active_workspace_id {
 8696        window_handle
 8697            .update(cx, |multi_workspace, window, cx| {
 8698                let target_index = multi_workspace
 8699                    .workspaces()
 8700                    .iter()
 8701                    .position(|ws| ws.read(cx).database_id() == Some(target_id));
 8702                let index = target_index.unwrap_or(0);
 8703                if let Some(workspace) = multi_workspace.workspaces().get(index).cloned() {
 8704                    multi_workspace.activate(workspace, window, cx);
 8705                }
 8706            })
 8707            .ok();
 8708    } else {
 8709        window_handle
 8710            .update(cx, |multi_workspace, window, cx| {
 8711                if let Some(workspace) = multi_workspace.workspaces().first().cloned() {
 8712                    multi_workspace.activate(workspace, window, cx);
 8713                }
 8714            })
 8715            .ok();
 8716    }
 8717
 8718    if state.sidebar_open {
 8719        window_handle
 8720            .update(cx, |multi_workspace, _, cx| {
 8721                multi_workspace.open_sidebar(cx);
 8722            })
 8723            .ok();
 8724    }
 8725
 8726    if let Some(sidebar_state) = &state.sidebar_state {
 8727        let sidebar_state = sidebar_state.clone();
 8728        window_handle
 8729            .update(cx, |multi_workspace, window, cx| {
 8730                if let Some(sidebar) = multi_workspace.sidebar() {
 8731                    sidebar.restore_serialized_state(&sidebar_state, window, cx);
 8732                }
 8733                multi_workspace.serialize(cx);
 8734            })
 8735            .ok();
 8736    }
 8737
 8738    window_handle
 8739        .update(cx, |_, window, _cx| {
 8740            window.activate_window();
 8741        })
 8742        .ok();
 8743
 8744    Ok(MultiWorkspaceRestoreResult {
 8745        window_handle,
 8746        errors,
 8747    })
 8748}
 8749
 8750actions!(
 8751    collab,
 8752    [
 8753        /// Opens the channel notes for the current call.
 8754        ///
 8755        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8756        /// channel in the collab panel.
 8757        ///
 8758        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8759        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8760        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8761        OpenChannelNotes,
 8762        /// Mutes your microphone.
 8763        Mute,
 8764        /// Deafens yourself (mute both microphone and speakers).
 8765        Deafen,
 8766        /// Leaves the current call.
 8767        LeaveCall,
 8768        /// Shares the current project with collaborators.
 8769        ShareProject,
 8770        /// Shares your screen with collaborators.
 8771        ScreenShare,
 8772        /// Copies the current room name and session id for debugging purposes.
 8773        CopyRoomId,
 8774    ]
 8775);
 8776
 8777/// Opens the channel notes for a specific channel by its ID.
 8778#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8779#[action(namespace = collab)]
 8780#[serde(deny_unknown_fields)]
 8781pub struct OpenChannelNotesById {
 8782    pub channel_id: u64,
 8783}
 8784
 8785actions!(
 8786    zed,
 8787    [
 8788        /// Opens the Zed log file.
 8789        OpenLog,
 8790        /// Reveals the Zed log file in the system file manager.
 8791        RevealLogInFileManager
 8792    ]
 8793);
 8794
 8795async fn join_channel_internal(
 8796    channel_id: ChannelId,
 8797    app_state: &Arc<AppState>,
 8798    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8799    requesting_workspace: Option<WeakEntity<Workspace>>,
 8800    active_call: &dyn AnyActiveCall,
 8801    cx: &mut AsyncApp,
 8802) -> Result<bool> {
 8803    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8804        if !active_call.is_in_room(cx) {
 8805            return (false, false);
 8806        }
 8807
 8808        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8809        let should_prompt = active_call.is_sharing_project(cx)
 8810            && active_call.has_remote_participants(cx)
 8811            && !already_in_channel;
 8812        (should_prompt, already_in_channel)
 8813    });
 8814
 8815    if already_in_channel {
 8816        let task = cx.update(|cx| {
 8817            if let Some((project, host)) = active_call.most_active_project(cx) {
 8818                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8819            } else {
 8820                None
 8821            }
 8822        });
 8823        if let Some(task) = task {
 8824            task.await?;
 8825        }
 8826        return anyhow::Ok(true);
 8827    }
 8828
 8829    if should_prompt {
 8830        if let Some(multi_workspace) = requesting_window {
 8831            let answer = multi_workspace
 8832                .update(cx, |_, window, cx| {
 8833                    window.prompt(
 8834                        PromptLevel::Warning,
 8835                        "Do you want to switch channels?",
 8836                        Some("Leaving this call will unshare your current project."),
 8837                        &["Yes, Join Channel", "Cancel"],
 8838                        cx,
 8839                    )
 8840                })?
 8841                .await;
 8842
 8843            if answer == Ok(1) {
 8844                return Ok(false);
 8845            }
 8846        } else {
 8847            return Ok(false);
 8848        }
 8849    }
 8850
 8851    let client = cx.update(|cx| active_call.client(cx));
 8852
 8853    let mut client_status = client.status();
 8854
 8855    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8856    'outer: loop {
 8857        let Some(status) = client_status.recv().await else {
 8858            anyhow::bail!("error connecting");
 8859        };
 8860
 8861        match status {
 8862            Status::Connecting
 8863            | Status::Authenticating
 8864            | Status::Authenticated
 8865            | Status::Reconnecting
 8866            | Status::Reauthenticating
 8867            | Status::Reauthenticated => continue,
 8868            Status::Connected { .. } => break 'outer,
 8869            Status::SignedOut | Status::AuthenticationError => {
 8870                return Err(ErrorCode::SignedOut.into());
 8871            }
 8872            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8873            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8874                return Err(ErrorCode::Disconnected.into());
 8875            }
 8876        }
 8877    }
 8878
 8879    let joined = cx
 8880        .update(|cx| active_call.join_channel(channel_id, cx))
 8881        .await?;
 8882
 8883    if !joined {
 8884        return anyhow::Ok(true);
 8885    }
 8886
 8887    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8888
 8889    let task = cx.update(|cx| {
 8890        if let Some((project, host)) = active_call.most_active_project(cx) {
 8891            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8892        }
 8893
 8894        // If you are the first to join a channel, see if you should share your project.
 8895        if !active_call.has_remote_participants(cx)
 8896            && !active_call.local_participant_is_guest(cx)
 8897            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8898        {
 8899            let project = workspace.update(cx, |workspace, cx| {
 8900                let project = workspace.project.read(cx);
 8901
 8902                if !active_call.share_on_join(cx) {
 8903                    return None;
 8904                }
 8905
 8906                if (project.is_local() || project.is_via_remote_server())
 8907                    && project.visible_worktrees(cx).any(|tree| {
 8908                        tree.read(cx)
 8909                            .root_entry()
 8910                            .is_some_and(|entry| entry.is_dir())
 8911                    })
 8912                {
 8913                    Some(workspace.project.clone())
 8914                } else {
 8915                    None
 8916                }
 8917            });
 8918            if let Some(project) = project {
 8919                let share_task = active_call.share_project(project, cx);
 8920                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8921                    share_task.await?;
 8922                    Ok(())
 8923                }));
 8924            }
 8925        }
 8926
 8927        None
 8928    });
 8929    if let Some(task) = task {
 8930        task.await?;
 8931        return anyhow::Ok(true);
 8932    }
 8933    anyhow::Ok(false)
 8934}
 8935
 8936pub fn join_channel(
 8937    channel_id: ChannelId,
 8938    app_state: Arc<AppState>,
 8939    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8940    requesting_workspace: Option<WeakEntity<Workspace>>,
 8941    cx: &mut App,
 8942) -> Task<Result<()>> {
 8943    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8944    cx.spawn(async move |cx| {
 8945        let result = join_channel_internal(
 8946            channel_id,
 8947            &app_state,
 8948            requesting_window,
 8949            requesting_workspace,
 8950            &*active_call.0,
 8951            cx,
 8952        )
 8953        .await;
 8954
 8955        // join channel succeeded, and opened a window
 8956        if matches!(result, Ok(true)) {
 8957            return anyhow::Ok(());
 8958        }
 8959
 8960        // find an existing workspace to focus and show call controls
 8961        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8962        if active_window.is_none() {
 8963            // no open workspaces, make one to show the error in (blergh)
 8964            let OpenResult {
 8965                window: window_handle,
 8966                ..
 8967            } = cx
 8968                .update(|cx| {
 8969                    Workspace::new_local(
 8970                        vec![],
 8971                        app_state.clone(),
 8972                        requesting_window,
 8973                        None,
 8974                        None,
 8975                        OpenMode::Activate,
 8976                        cx,
 8977                    )
 8978                })
 8979                .await?;
 8980
 8981            window_handle
 8982                .update(cx, |_, window, _cx| {
 8983                    window.activate_window();
 8984                })
 8985                .ok();
 8986
 8987            if result.is_ok() {
 8988                cx.update(|cx| {
 8989                    cx.dispatch_action(&OpenChannelNotes);
 8990                });
 8991            }
 8992
 8993            active_window = Some(window_handle);
 8994        }
 8995
 8996        if let Err(err) = result {
 8997            log::error!("failed to join channel: {}", err);
 8998            if let Some(active_window) = active_window {
 8999                active_window
 9000                    .update(cx, |_, window, cx| {
 9001                        let detail: SharedString = match err.error_code() {
 9002                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 9003                            ErrorCode::UpgradeRequired => concat!(
 9004                                "Your are running an unsupported version of Zed. ",
 9005                                "Please update to continue."
 9006                            )
 9007                            .into(),
 9008                            ErrorCode::NoSuchChannel => concat!(
 9009                                "No matching channel was found. ",
 9010                                "Please check the link and try again."
 9011                            )
 9012                            .into(),
 9013                            ErrorCode::Forbidden => concat!(
 9014                                "This channel is private, and you do not have access. ",
 9015                                "Please ask someone to add you and try again."
 9016                            )
 9017                            .into(),
 9018                            ErrorCode::Disconnected => {
 9019                                "Please check your internet connection and try again.".into()
 9020                            }
 9021                            _ => format!("{}\n\nPlease try again.", err).into(),
 9022                        };
 9023                        window.prompt(
 9024                            PromptLevel::Critical,
 9025                            "Failed to join channel",
 9026                            Some(&detail),
 9027                            &["Ok"],
 9028                            cx,
 9029                        )
 9030                    })?
 9031                    .await
 9032                    .ok();
 9033            }
 9034        }
 9035
 9036        // return ok, we showed the error to the user.
 9037        anyhow::Ok(())
 9038    })
 9039}
 9040
 9041pub async fn get_any_active_multi_workspace(
 9042    app_state: Arc<AppState>,
 9043    mut cx: AsyncApp,
 9044) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 9045    // find an existing workspace to focus and show call controls
 9046    let active_window = activate_any_workspace_window(&mut cx);
 9047    if active_window.is_none() {
 9048        cx.update(|cx| {
 9049            Workspace::new_local(
 9050                vec![],
 9051                app_state.clone(),
 9052                None,
 9053                None,
 9054                None,
 9055                OpenMode::Activate,
 9056                cx,
 9057            )
 9058        })
 9059        .await?;
 9060    }
 9061    activate_any_workspace_window(&mut cx).context("could not open zed")
 9062}
 9063
 9064fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 9065    cx.update(|cx| {
 9066        if let Some(workspace_window) = cx
 9067            .active_window()
 9068            .and_then(|window| window.downcast::<MultiWorkspace>())
 9069        {
 9070            return Some(workspace_window);
 9071        }
 9072
 9073        for window in cx.windows() {
 9074            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 9075                workspace_window
 9076                    .update(cx, |_, window, _| window.activate_window())
 9077                    .ok();
 9078                return Some(workspace_window);
 9079            }
 9080        }
 9081        None
 9082    })
 9083}
 9084
 9085pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 9086    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 9087}
 9088
 9089pub fn workspace_windows_for_location(
 9090    serialized_location: &SerializedWorkspaceLocation,
 9091    cx: &App,
 9092) -> Vec<WindowHandle<MultiWorkspace>> {
 9093    cx.windows()
 9094        .into_iter()
 9095        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9096        .filter(|multi_workspace| {
 9097            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 9098                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 9099                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 9100                }
 9101                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 9102                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 9103                    a.distro_name == b.distro_name
 9104                }
 9105                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 9106                    a.container_id == b.container_id
 9107                }
 9108                #[cfg(any(test, feature = "test-support"))]
 9109                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 9110                    a.id == b.id
 9111                }
 9112                _ => false,
 9113            };
 9114
 9115            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 9116                multi_workspace.workspaces().iter().any(|workspace| {
 9117                    match workspace.read(cx).workspace_location(cx) {
 9118                        WorkspaceLocation::Location(location, _) => {
 9119                            match (&location, serialized_location) {
 9120                                (
 9121                                    SerializedWorkspaceLocation::Local,
 9122                                    SerializedWorkspaceLocation::Local,
 9123                                ) => true,
 9124                                (
 9125                                    SerializedWorkspaceLocation::Remote(a),
 9126                                    SerializedWorkspaceLocation::Remote(b),
 9127                                ) => same_host(a, b),
 9128                                _ => false,
 9129                            }
 9130                        }
 9131                        _ => false,
 9132                    }
 9133                })
 9134            })
 9135        })
 9136        .collect()
 9137}
 9138
 9139pub async fn find_existing_workspace(
 9140    abs_paths: &[PathBuf],
 9141    open_options: &OpenOptions,
 9142    location: &SerializedWorkspaceLocation,
 9143    cx: &mut AsyncApp,
 9144) -> (
 9145    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 9146    OpenVisible,
 9147) {
 9148    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 9149    let mut open_visible = OpenVisible::All;
 9150    let mut best_match = None;
 9151
 9152    if open_options.open_new_workspace != Some(true) {
 9153        cx.update(|cx| {
 9154            for window in workspace_windows_for_location(location, cx) {
 9155                if let Ok(multi_workspace) = window.read(cx) {
 9156                    for workspace in multi_workspace.workspaces() {
 9157                        let project = workspace.read(cx).project.read(cx);
 9158                        let m = project.visibility_for_paths(
 9159                            abs_paths,
 9160                            open_options.open_new_workspace == None,
 9161                            cx,
 9162                        );
 9163                        if m > best_match {
 9164                            existing = Some((window, workspace.clone()));
 9165                            best_match = m;
 9166                        } else if best_match.is_none()
 9167                            && open_options.open_new_workspace == Some(false)
 9168                        {
 9169                            existing = Some((window, workspace.clone()))
 9170                        }
 9171                    }
 9172                }
 9173            }
 9174        });
 9175
 9176        let all_paths_are_files = existing
 9177            .as_ref()
 9178            .and_then(|(_, target_workspace)| {
 9179                cx.update(|cx| {
 9180                    let workspace = target_workspace.read(cx);
 9181                    let project = workspace.project.read(cx);
 9182                    let path_style = workspace.path_style(cx);
 9183                    Some(!abs_paths.iter().any(|path| {
 9184                        let path = util::paths::SanitizedPath::new(path);
 9185                        project.worktrees(cx).any(|worktree| {
 9186                            let worktree = worktree.read(cx);
 9187                            let abs_path = worktree.abs_path();
 9188                            path_style
 9189                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 9190                                .and_then(|rel| worktree.entry_for_path(&rel))
 9191                                .is_some_and(|e| e.is_dir())
 9192                        })
 9193                    }))
 9194                })
 9195            })
 9196            .unwrap_or(false);
 9197
 9198        if open_options.open_new_workspace.is_none()
 9199            && existing.is_some()
 9200            && open_options.wait
 9201            && all_paths_are_files
 9202        {
 9203            cx.update(|cx| {
 9204                let windows = workspace_windows_for_location(location, cx);
 9205                let window = cx
 9206                    .active_window()
 9207                    .and_then(|window| window.downcast::<MultiWorkspace>())
 9208                    .filter(|window| windows.contains(window))
 9209                    .or_else(|| windows.into_iter().next());
 9210                if let Some(window) = window {
 9211                    if let Ok(multi_workspace) = window.read(cx) {
 9212                        let active_workspace = multi_workspace.workspace().clone();
 9213                        existing = Some((window, active_workspace));
 9214                        open_visible = OpenVisible::None;
 9215                    }
 9216                }
 9217            });
 9218        }
 9219    }
 9220    (existing, open_visible)
 9221}
 9222
 9223#[derive(Default, Clone)]
 9224pub struct OpenOptions {
 9225    pub visible: Option<OpenVisible>,
 9226    pub focus: Option<bool>,
 9227    pub open_new_workspace: Option<bool>,
 9228    pub wait: bool,
 9229    pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9230    pub open_mode: OpenMode,
 9231    pub env: Option<HashMap<String, String>>,
 9232    pub open_in_dev_container: bool,
 9233}
 9234
 9235/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 9236/// or [`Workspace::open_workspace_for_paths`].
 9237pub struct OpenResult {
 9238    pub window: WindowHandle<MultiWorkspace>,
 9239    pub workspace: Entity<Workspace>,
 9240    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 9241}
 9242
 9243/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 9244pub fn open_workspace_by_id(
 9245    workspace_id: WorkspaceId,
 9246    app_state: Arc<AppState>,
 9247    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9248    cx: &mut App,
 9249) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 9250    let project_handle = Project::local(
 9251        app_state.client.clone(),
 9252        app_state.node_runtime.clone(),
 9253        app_state.user_store.clone(),
 9254        app_state.languages.clone(),
 9255        app_state.fs.clone(),
 9256        None,
 9257        project::LocalProjectFlags {
 9258            init_worktree_trust: true,
 9259            ..project::LocalProjectFlags::default()
 9260        },
 9261        cx,
 9262    );
 9263
 9264    let db = WorkspaceDb::global(cx);
 9265    let kvp = db::kvp::KeyValueStore::global(cx);
 9266    cx.spawn(async move |cx| {
 9267        let serialized_workspace = db
 9268            .workspace_for_id(workspace_id)
 9269            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 9270
 9271        let centered_layout = serialized_workspace.centered_layout;
 9272
 9273        let (window, workspace) = if let Some(window) = requesting_window {
 9274            let workspace = window.update(cx, |multi_workspace, window, cx| {
 9275                let workspace = cx.new(|cx| {
 9276                    let mut workspace = Workspace::new(
 9277                        Some(workspace_id),
 9278                        project_handle.clone(),
 9279                        app_state.clone(),
 9280                        window,
 9281                        cx,
 9282                    );
 9283                    workspace.centered_layout = centered_layout;
 9284                    workspace
 9285                });
 9286                multi_workspace.add(workspace.clone(), &*window, cx);
 9287                workspace
 9288            })?;
 9289            (window, workspace)
 9290        } else {
 9291            let window_bounds_override = window_bounds_env_override();
 9292
 9293            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 9294                (Some(WindowBounds::Windowed(bounds)), None)
 9295            } else if let Some(display) = serialized_workspace.display
 9296                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 9297            {
 9298                (Some(bounds.0), Some(display))
 9299            } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
 9300                (Some(bounds), Some(display))
 9301            } else {
 9302                (None, None)
 9303            };
 9304
 9305            let options = cx.update(|cx| {
 9306                let mut options = (app_state.build_window_options)(display, cx);
 9307                options.window_bounds = window_bounds;
 9308                options
 9309            });
 9310
 9311            let window = cx.open_window(options, {
 9312                let app_state = app_state.clone();
 9313                let project_handle = project_handle.clone();
 9314                move |window, cx| {
 9315                    let workspace = cx.new(|cx| {
 9316                        let mut workspace = Workspace::new(
 9317                            Some(workspace_id),
 9318                            project_handle,
 9319                            app_state,
 9320                            window,
 9321                            cx,
 9322                        );
 9323                        workspace.centered_layout = centered_layout;
 9324                        workspace
 9325                    });
 9326                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9327                }
 9328            })?;
 9329
 9330            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 9331                multi_workspace.workspace().clone()
 9332            })?;
 9333
 9334            (window, workspace)
 9335        };
 9336
 9337        notify_if_database_failed(window, cx);
 9338
 9339        // Restore items from the serialized workspace
 9340        window
 9341            .update(cx, |_, window, cx| {
 9342                workspace.update(cx, |_workspace, cx| {
 9343                    open_items(Some(serialized_workspace), vec![], window, cx)
 9344                })
 9345            })?
 9346            .await?;
 9347
 9348        window.update(cx, |_, window, cx| {
 9349            workspace.update(cx, |workspace, cx| {
 9350                workspace.serialize_workspace(window, cx);
 9351            });
 9352        })?;
 9353
 9354        Ok(window)
 9355    })
 9356}
 9357
 9358#[allow(clippy::type_complexity)]
 9359pub fn open_paths(
 9360    abs_paths: &[PathBuf],
 9361    app_state: Arc<AppState>,
 9362    open_options: OpenOptions,
 9363    cx: &mut App,
 9364) -> Task<anyhow::Result<OpenResult>> {
 9365    let abs_paths = abs_paths.to_vec();
 9366    #[cfg(target_os = "windows")]
 9367    let wsl_path = abs_paths
 9368        .iter()
 9369        .find_map(|p| util::paths::WslPath::from_path(p));
 9370
 9371    cx.spawn(async move |cx| {
 9372        let (mut existing, mut open_visible) = find_existing_workspace(
 9373            &abs_paths,
 9374            &open_options,
 9375            &SerializedWorkspaceLocation::Local,
 9376            cx,
 9377        )
 9378        .await;
 9379
 9380        // Fallback: if no workspace contains the paths and all paths are files,
 9381        // prefer an existing local workspace window (active window first).
 9382        if open_options.open_new_workspace.is_none() && existing.is_none() {
 9383            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 9384            let all_metadatas = futures::future::join_all(all_paths)
 9385                .await
 9386                .into_iter()
 9387                .filter_map(|result| result.ok().flatten())
 9388                .collect::<Vec<_>>();
 9389
 9390            if all_metadatas.iter().all(|file| !file.is_dir) {
 9391                cx.update(|cx| {
 9392                    let windows = workspace_windows_for_location(
 9393                        &SerializedWorkspaceLocation::Local,
 9394                        cx,
 9395                    );
 9396                    let window = cx
 9397                        .active_window()
 9398                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9399                        .filter(|window| windows.contains(window))
 9400                        .or_else(|| windows.into_iter().next());
 9401                    if let Some(window) = window {
 9402                        if let Ok(multi_workspace) = window.read(cx) {
 9403                            let active_workspace = multi_workspace.workspace().clone();
 9404                            existing = Some((window, active_workspace));
 9405                            open_visible = OpenVisible::None;
 9406                        }
 9407                    }
 9408                });
 9409            }
 9410        }
 9411
 9412        let open_in_dev_container = open_options.open_in_dev_container;
 9413
 9414        let result = if let Some((existing, target_workspace)) = existing {
 9415            let open_task = existing
 9416                .update(cx, |multi_workspace, window, cx| {
 9417                    window.activate_window();
 9418                    multi_workspace.activate(target_workspace.clone(), window, cx);
 9419                    target_workspace.update(cx, |workspace, cx| {
 9420                        if open_in_dev_container {
 9421                            workspace.set_open_in_dev_container(true);
 9422                        }
 9423                        workspace.open_paths(
 9424                            abs_paths,
 9425                            OpenOptions {
 9426                                visible: Some(open_visible),
 9427                                ..Default::default()
 9428                            },
 9429                            None,
 9430                            window,
 9431                            cx,
 9432                        )
 9433                    })
 9434                })?
 9435                .await;
 9436
 9437            _ = existing.update(cx, |multi_workspace, _, cx| {
 9438                let workspace = multi_workspace.workspace().clone();
 9439                workspace.update(cx, |workspace, cx| {
 9440                    for item in open_task.iter().flatten() {
 9441                        if let Err(e) = item {
 9442                            workspace.show_error(&e, cx);
 9443                        }
 9444                    }
 9445                });
 9446            });
 9447
 9448            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9449        } else {
 9450            let init = if open_in_dev_container {
 9451                Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>| {
 9452                    workspace.set_open_in_dev_container(true);
 9453                }) as Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>)
 9454            } else {
 9455                None
 9456            };
 9457            let result = cx
 9458                .update(move |cx| {
 9459                    Workspace::new_local(
 9460                        abs_paths,
 9461                        app_state.clone(),
 9462                        open_options.requesting_window,
 9463                        open_options.env,
 9464                        init,
 9465                        open_options.open_mode,
 9466                        cx,
 9467                    )
 9468                })
 9469                .await;
 9470
 9471            if let Ok(ref result) = result {
 9472                result.window
 9473                    .update(cx, |_, window, _cx| {
 9474                        window.activate_window();
 9475                    })
 9476                    .log_err();
 9477            }
 9478
 9479            result
 9480        };
 9481
 9482        #[cfg(target_os = "windows")]
 9483        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9484            && let Ok(ref result) = result
 9485        {
 9486            result.window
 9487                .update(cx, move |multi_workspace, _window, cx| {
 9488                    struct OpenInWsl;
 9489                    let workspace = multi_workspace.workspace().clone();
 9490                    workspace.update(cx, |workspace, cx| {
 9491                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9492                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9493                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9494                            cx.new(move |cx| {
 9495                                MessageNotification::new(msg, cx)
 9496                                    .primary_message("Open in WSL")
 9497                                    .primary_icon(IconName::FolderOpen)
 9498                                    .primary_on_click(move |window, cx| {
 9499                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9500                                                distro: remote::WslConnectionOptions {
 9501                                                        distro_name: distro.clone(),
 9502                                                    user: None,
 9503                                                },
 9504                                                paths: vec![path.clone().into()],
 9505                                            }), cx)
 9506                                    })
 9507                            })
 9508                        });
 9509                    });
 9510                })
 9511                .unwrap();
 9512        };
 9513        result
 9514    })
 9515}
 9516
 9517pub fn open_new(
 9518    open_options: OpenOptions,
 9519    app_state: Arc<AppState>,
 9520    cx: &mut App,
 9521    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9522) -> Task<anyhow::Result<()>> {
 9523    let addition = open_options.open_mode;
 9524    let task = Workspace::new_local(
 9525        Vec::new(),
 9526        app_state,
 9527        open_options.requesting_window,
 9528        open_options.env,
 9529        Some(Box::new(init)),
 9530        addition,
 9531        cx,
 9532    );
 9533    cx.spawn(async move |cx| {
 9534        let OpenResult { window, .. } = task.await?;
 9535        window
 9536            .update(cx, |_, window, _cx| {
 9537                window.activate_window();
 9538            })
 9539            .ok();
 9540        Ok(())
 9541    })
 9542}
 9543
 9544pub fn create_and_open_local_file(
 9545    path: &'static Path,
 9546    window: &mut Window,
 9547    cx: &mut Context<Workspace>,
 9548    default_content: impl 'static + Send + FnOnce() -> Rope,
 9549) -> Task<Result<Box<dyn ItemHandle>>> {
 9550    cx.spawn_in(window, async move |workspace, cx| {
 9551        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9552        if !fs.is_file(path).await {
 9553            fs.create_file(path, Default::default()).await?;
 9554            fs.save(path, &default_content(), Default::default())
 9555                .await?;
 9556        }
 9557
 9558        workspace
 9559            .update_in(cx, |workspace, window, cx| {
 9560                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9561                    let path = workspace
 9562                        .project
 9563                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9564                    cx.spawn_in(window, async move |workspace, cx| {
 9565                        let path = path.await?;
 9566
 9567                        let path = fs.canonicalize(&path).await.unwrap_or(path);
 9568
 9569                        let mut items = workspace
 9570                            .update_in(cx, |workspace, window, cx| {
 9571                                workspace.open_paths(
 9572                                    vec![path.to_path_buf()],
 9573                                    OpenOptions {
 9574                                        visible: Some(OpenVisible::None),
 9575                                        ..Default::default()
 9576                                    },
 9577                                    None,
 9578                                    window,
 9579                                    cx,
 9580                                )
 9581                            })?
 9582                            .await;
 9583                        let item = items.pop().flatten();
 9584                        item.with_context(|| format!("path {path:?} is not a file"))?
 9585                    })
 9586                })
 9587            })?
 9588            .await?
 9589            .await
 9590    })
 9591}
 9592
 9593pub fn open_remote_project_with_new_connection(
 9594    window: WindowHandle<MultiWorkspace>,
 9595    remote_connection: Arc<dyn RemoteConnection>,
 9596    cancel_rx: oneshot::Receiver<()>,
 9597    delegate: Arc<dyn RemoteClientDelegate>,
 9598    app_state: Arc<AppState>,
 9599    paths: Vec<PathBuf>,
 9600    cx: &mut App,
 9601) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9602    cx.spawn(async move |cx| {
 9603        let (workspace_id, serialized_workspace) =
 9604            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9605                .await?;
 9606
 9607        let session = match cx
 9608            .update(|cx| {
 9609                remote::RemoteClient::new(
 9610                    ConnectionIdentifier::Workspace(workspace_id.0),
 9611                    remote_connection,
 9612                    cancel_rx,
 9613                    delegate,
 9614                    cx,
 9615                )
 9616            })
 9617            .await?
 9618        {
 9619            Some(result) => result,
 9620            None => return Ok(Vec::new()),
 9621        };
 9622
 9623        let project = cx.update(|cx| {
 9624            project::Project::remote(
 9625                session,
 9626                app_state.client.clone(),
 9627                app_state.node_runtime.clone(),
 9628                app_state.user_store.clone(),
 9629                app_state.languages.clone(),
 9630                app_state.fs.clone(),
 9631                true,
 9632                cx,
 9633            )
 9634        });
 9635
 9636        open_remote_project_inner(
 9637            project,
 9638            paths,
 9639            workspace_id,
 9640            serialized_workspace,
 9641            app_state,
 9642            window,
 9643            cx,
 9644        )
 9645        .await
 9646    })
 9647}
 9648
 9649pub fn open_remote_project_with_existing_connection(
 9650    connection_options: RemoteConnectionOptions,
 9651    project: Entity<Project>,
 9652    paths: Vec<PathBuf>,
 9653    app_state: Arc<AppState>,
 9654    window: WindowHandle<MultiWorkspace>,
 9655    cx: &mut AsyncApp,
 9656) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9657    cx.spawn(async move |cx| {
 9658        let (workspace_id, serialized_workspace) =
 9659            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9660
 9661        open_remote_project_inner(
 9662            project,
 9663            paths,
 9664            workspace_id,
 9665            serialized_workspace,
 9666            app_state,
 9667            window,
 9668            cx,
 9669        )
 9670        .await
 9671    })
 9672}
 9673
 9674async fn open_remote_project_inner(
 9675    project: Entity<Project>,
 9676    paths: Vec<PathBuf>,
 9677    workspace_id: WorkspaceId,
 9678    serialized_workspace: Option<SerializedWorkspace>,
 9679    app_state: Arc<AppState>,
 9680    window: WindowHandle<MultiWorkspace>,
 9681    cx: &mut AsyncApp,
 9682) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9683    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9684    let toolchains = db.toolchains(workspace_id).await?;
 9685    for (toolchain, worktree_path, path) in toolchains {
 9686        project
 9687            .update(cx, |this, cx| {
 9688                let Some(worktree_id) =
 9689                    this.find_worktree(&worktree_path, cx)
 9690                        .and_then(|(worktree, rel_path)| {
 9691                            if rel_path.is_empty() {
 9692                                Some(worktree.read(cx).id())
 9693                            } else {
 9694                                None
 9695                            }
 9696                        })
 9697                else {
 9698                    return Task::ready(None);
 9699                };
 9700
 9701                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9702            })
 9703            .await;
 9704    }
 9705    let mut project_paths_to_open = vec![];
 9706    let mut project_path_errors = vec![];
 9707
 9708    for path in paths {
 9709        let result = cx
 9710            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9711            .await;
 9712        match result {
 9713            Ok((_, project_path)) => {
 9714                project_paths_to_open.push((path.clone(), Some(project_path)));
 9715            }
 9716            Err(error) => {
 9717                project_path_errors.push(error);
 9718            }
 9719        };
 9720    }
 9721
 9722    if project_paths_to_open.is_empty() {
 9723        return Err(project_path_errors.pop().context("no paths given")?);
 9724    }
 9725
 9726    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9727        telemetry::event!("SSH Project Opened");
 9728
 9729        let new_workspace = cx.new(|cx| {
 9730            let mut workspace =
 9731                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9732            workspace.update_history(cx);
 9733
 9734            if let Some(ref serialized) = serialized_workspace {
 9735                workspace.centered_layout = serialized.centered_layout;
 9736            }
 9737
 9738            workspace
 9739        });
 9740
 9741        multi_workspace.activate(new_workspace.clone(), window, cx);
 9742        new_workspace
 9743    })?;
 9744
 9745    let items = window
 9746        .update(cx, |_, window, cx| {
 9747            window.activate_window();
 9748            workspace.update(cx, |_workspace, cx| {
 9749                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9750            })
 9751        })?
 9752        .await?;
 9753
 9754    workspace.update(cx, |workspace, cx| {
 9755        for error in project_path_errors {
 9756            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9757                if let Some(path) = error.error_tag("path") {
 9758                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9759                }
 9760            } else {
 9761                workspace.show_error(&error, cx)
 9762            }
 9763        }
 9764    });
 9765
 9766    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9767}
 9768
 9769fn deserialize_remote_project(
 9770    connection_options: RemoteConnectionOptions,
 9771    paths: Vec<PathBuf>,
 9772    cx: &AsyncApp,
 9773) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9774    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9775    cx.background_spawn(async move {
 9776        let remote_connection_id = db
 9777            .get_or_create_remote_connection(connection_options)
 9778            .await?;
 9779
 9780        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
 9781
 9782        let workspace_id = if let Some(workspace_id) =
 9783            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9784        {
 9785            workspace_id
 9786        } else {
 9787            db.next_id().await?
 9788        };
 9789
 9790        Ok((workspace_id, serialized_workspace))
 9791    })
 9792}
 9793
 9794pub fn join_in_room_project(
 9795    project_id: u64,
 9796    follow_user_id: u64,
 9797    app_state: Arc<AppState>,
 9798    cx: &mut App,
 9799) -> Task<Result<()>> {
 9800    let windows = cx.windows();
 9801    cx.spawn(async move |cx| {
 9802        let existing_window_and_workspace: Option<(
 9803            WindowHandle<MultiWorkspace>,
 9804            Entity<Workspace>,
 9805        )> = windows.into_iter().find_map(|window_handle| {
 9806            window_handle
 9807                .downcast::<MultiWorkspace>()
 9808                .and_then(|window_handle| {
 9809                    window_handle
 9810                        .update(cx, |multi_workspace, _window, cx| {
 9811                            for workspace in multi_workspace.workspaces() {
 9812                                if workspace.read(cx).project().read(cx).remote_id()
 9813                                    == Some(project_id)
 9814                                {
 9815                                    return Some((window_handle, workspace.clone()));
 9816                                }
 9817                            }
 9818                            None
 9819                        })
 9820                        .unwrap_or(None)
 9821                })
 9822        });
 9823
 9824        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9825            existing_window_and_workspace
 9826        {
 9827            existing_window
 9828                .update(cx, |multi_workspace, window, cx| {
 9829                    multi_workspace.activate(target_workspace, window, cx);
 9830                })
 9831                .ok();
 9832            existing_window
 9833        } else {
 9834            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9835            let project = cx
 9836                .update(|cx| {
 9837                    active_call.0.join_project(
 9838                        project_id,
 9839                        app_state.languages.clone(),
 9840                        app_state.fs.clone(),
 9841                        cx,
 9842                    )
 9843                })
 9844                .await?;
 9845
 9846            let window_bounds_override = window_bounds_env_override();
 9847            cx.update(|cx| {
 9848                let mut options = (app_state.build_window_options)(None, cx);
 9849                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9850                cx.open_window(options, |window, cx| {
 9851                    let workspace = cx.new(|cx| {
 9852                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9853                    });
 9854                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9855                })
 9856            })?
 9857        };
 9858
 9859        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9860            cx.activate(true);
 9861            window.activate_window();
 9862
 9863            // We set the active workspace above, so this is the correct workspace.
 9864            let workspace = multi_workspace.workspace().clone();
 9865            workspace.update(cx, |workspace, cx| {
 9866                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9867                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9868                    .or_else(|| {
 9869                        // If we couldn't follow the given user, follow the host instead.
 9870                        let collaborator = workspace
 9871                            .project()
 9872                            .read(cx)
 9873                            .collaborators()
 9874                            .values()
 9875                            .find(|collaborator| collaborator.is_host)?;
 9876                        Some(collaborator.peer_id)
 9877                    });
 9878
 9879                if let Some(follow_peer_id) = follow_peer_id {
 9880                    workspace.follow(follow_peer_id, window, cx);
 9881                }
 9882            });
 9883        })?;
 9884
 9885        anyhow::Ok(())
 9886    })
 9887}
 9888
 9889pub fn reload(cx: &mut App) {
 9890    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9891    let mut workspace_windows = cx
 9892        .windows()
 9893        .into_iter()
 9894        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9895        .collect::<Vec<_>>();
 9896
 9897    // If multiple windows have unsaved changes, and need a save prompt,
 9898    // prompt in the active window before switching to a different window.
 9899    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9900
 9901    let mut prompt = None;
 9902    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9903        prompt = window
 9904            .update(cx, |_, window, cx| {
 9905                window.prompt(
 9906                    PromptLevel::Info,
 9907                    "Are you sure you want to restart?",
 9908                    None,
 9909                    &["Restart", "Cancel"],
 9910                    cx,
 9911                )
 9912            })
 9913            .ok();
 9914    }
 9915
 9916    cx.spawn(async move |cx| {
 9917        if let Some(prompt) = prompt {
 9918            let answer = prompt.await?;
 9919            if answer != 0 {
 9920                return anyhow::Ok(());
 9921            }
 9922        }
 9923
 9924        // If the user cancels any save prompt, then keep the app open.
 9925        for window in workspace_windows {
 9926            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9927                let workspace = multi_workspace.workspace().clone();
 9928                workspace.update(cx, |workspace, cx| {
 9929                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9930                })
 9931            }) && !should_close.await?
 9932            {
 9933                return anyhow::Ok(());
 9934            }
 9935        }
 9936        cx.update(|cx| cx.restart());
 9937        anyhow::Ok(())
 9938    })
 9939    .detach_and_log_err(cx);
 9940}
 9941
 9942fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9943    let mut parts = value.split(',');
 9944    let x: usize = parts.next()?.parse().ok()?;
 9945    let y: usize = parts.next()?.parse().ok()?;
 9946    Some(point(px(x as f32), px(y as f32)))
 9947}
 9948
 9949fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9950    let mut parts = value.split(',');
 9951    let width: usize = parts.next()?.parse().ok()?;
 9952    let height: usize = parts.next()?.parse().ok()?;
 9953    Some(size(px(width as f32), px(height as f32)))
 9954}
 9955
 9956/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9957/// appropriate.
 9958///
 9959/// The `border_radius_tiling` parameter allows overriding which corners get
 9960/// rounded, independently of the actual window tiling state. This is used
 9961/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9962/// we want square corners on the left (so the sidebar appears flush with the
 9963/// window edge) but we still need the shadow padding for proper visual
 9964/// appearance. Unlike actual window tiling, this only affects border radius -
 9965/// not padding or shadows.
 9966pub fn client_side_decorations(
 9967    element: impl IntoElement,
 9968    window: &mut Window,
 9969    cx: &mut App,
 9970    border_radius_tiling: Tiling,
 9971) -> Stateful<Div> {
 9972    const BORDER_SIZE: Pixels = px(1.0);
 9973    let decorations = window.window_decorations();
 9974    let tiling = match decorations {
 9975        Decorations::Server => Tiling::default(),
 9976        Decorations::Client { tiling } => tiling,
 9977    };
 9978
 9979    match decorations {
 9980        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9981        Decorations::Server => window.set_client_inset(px(0.0)),
 9982    }
 9983
 9984    struct GlobalResizeEdge(ResizeEdge);
 9985    impl Global for GlobalResizeEdge {}
 9986
 9987    div()
 9988        .id("window-backdrop")
 9989        .bg(transparent_black())
 9990        .map(|div| match decorations {
 9991            Decorations::Server => div,
 9992            Decorations::Client { .. } => div
 9993                .when(
 9994                    !(tiling.top
 9995                        || tiling.right
 9996                        || border_radius_tiling.top
 9997                        || border_radius_tiling.right),
 9998                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9999                )
10000                .when(
10001                    !(tiling.top
10002                        || tiling.left
10003                        || border_radius_tiling.top
10004                        || border_radius_tiling.left),
10005                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10006                )
10007                .when(
10008                    !(tiling.bottom
10009                        || tiling.right
10010                        || border_radius_tiling.bottom
10011                        || border_radius_tiling.right),
10012                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10013                )
10014                .when(
10015                    !(tiling.bottom
10016                        || tiling.left
10017                        || border_radius_tiling.bottom
10018                        || border_radius_tiling.left),
10019                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10020                )
10021                .when(!tiling.top, |div| {
10022                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
10023                })
10024                .when(!tiling.bottom, |div| {
10025                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
10026                })
10027                .when(!tiling.left, |div| {
10028                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10029                })
10030                .when(!tiling.right, |div| {
10031                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10032                })
10033                .on_mouse_move(move |e, window, cx| {
10034                    let size = window.window_bounds().get_bounds().size;
10035                    let pos = e.position;
10036
10037                    let new_edge =
10038                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10039
10040                    let edge = cx.try_global::<GlobalResizeEdge>();
10041                    if new_edge != edge.map(|edge| edge.0) {
10042                        window
10043                            .window_handle()
10044                            .update(cx, |workspace, _, cx| {
10045                                cx.notify(workspace.entity_id());
10046                            })
10047                            .ok();
10048                    }
10049                })
10050                .on_mouse_down(MouseButton::Left, move |e, window, _| {
10051                    let size = window.window_bounds().get_bounds().size;
10052                    let pos = e.position;
10053
10054                    let edge = match resize_edge(
10055                        pos,
10056                        theme::CLIENT_SIDE_DECORATION_SHADOW,
10057                        size,
10058                        tiling,
10059                    ) {
10060                        Some(value) => value,
10061                        None => return,
10062                    };
10063
10064                    window.start_window_resize(edge);
10065                }),
10066        })
10067        .size_full()
10068        .child(
10069            div()
10070                .cursor(CursorStyle::Arrow)
10071                .map(|div| match decorations {
10072                    Decorations::Server => div,
10073                    Decorations::Client { .. } => div
10074                        .border_color(cx.theme().colors().border)
10075                        .when(
10076                            !(tiling.top
10077                                || tiling.right
10078                                || border_radius_tiling.top
10079                                || border_radius_tiling.right),
10080                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10081                        )
10082                        .when(
10083                            !(tiling.top
10084                                || tiling.left
10085                                || border_radius_tiling.top
10086                                || border_radius_tiling.left),
10087                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10088                        )
10089                        .when(
10090                            !(tiling.bottom
10091                                || tiling.right
10092                                || border_radius_tiling.bottom
10093                                || border_radius_tiling.right),
10094                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10095                        )
10096                        .when(
10097                            !(tiling.bottom
10098                                || tiling.left
10099                                || border_radius_tiling.bottom
10100                                || border_radius_tiling.left),
10101                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10102                        )
10103                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10104                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10105                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10106                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10107                        .when(!tiling.is_tiled(), |div| {
10108                            div.shadow(vec![gpui::BoxShadow {
10109                                color: Hsla {
10110                                    h: 0.,
10111                                    s: 0.,
10112                                    l: 0.,
10113                                    a: 0.4,
10114                                },
10115                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10116                                spread_radius: px(0.),
10117                                offset: point(px(0.0), px(0.0)),
10118                            }])
10119                        }),
10120                })
10121                .on_mouse_move(|_e, _, cx| {
10122                    cx.stop_propagation();
10123                })
10124                .size_full()
10125                .child(element),
10126        )
10127        .map(|div| match decorations {
10128            Decorations::Server => div,
10129            Decorations::Client { tiling, .. } => div.child(
10130                canvas(
10131                    |_bounds, window, _| {
10132                        window.insert_hitbox(
10133                            Bounds::new(
10134                                point(px(0.0), px(0.0)),
10135                                window.window_bounds().get_bounds().size,
10136                            ),
10137                            HitboxBehavior::Normal,
10138                        )
10139                    },
10140                    move |_bounds, hitbox, window, cx| {
10141                        let mouse = window.mouse_position();
10142                        let size = window.window_bounds().get_bounds().size;
10143                        let Some(edge) =
10144                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10145                        else {
10146                            return;
10147                        };
10148                        cx.set_global(GlobalResizeEdge(edge));
10149                        window.set_cursor_style(
10150                            match edge {
10151                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10152                                ResizeEdge::Left | ResizeEdge::Right => {
10153                                    CursorStyle::ResizeLeftRight
10154                                }
10155                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10156                                    CursorStyle::ResizeUpLeftDownRight
10157                                }
10158                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10159                                    CursorStyle::ResizeUpRightDownLeft
10160                                }
10161                            },
10162                            &hitbox,
10163                        );
10164                    },
10165                )
10166                .size_full()
10167                .absolute(),
10168            ),
10169        })
10170}
10171
10172fn resize_edge(
10173    pos: Point<Pixels>,
10174    shadow_size: Pixels,
10175    window_size: Size<Pixels>,
10176    tiling: Tiling,
10177) -> Option<ResizeEdge> {
10178    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10179    if bounds.contains(&pos) {
10180        return None;
10181    }
10182
10183    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10184    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10185    if !tiling.top && top_left_bounds.contains(&pos) {
10186        return Some(ResizeEdge::TopLeft);
10187    }
10188
10189    let top_right_bounds = Bounds::new(
10190        Point::new(window_size.width - corner_size.width, px(0.)),
10191        corner_size,
10192    );
10193    if !tiling.top && top_right_bounds.contains(&pos) {
10194        return Some(ResizeEdge::TopRight);
10195    }
10196
10197    let bottom_left_bounds = Bounds::new(
10198        Point::new(px(0.), window_size.height - corner_size.height),
10199        corner_size,
10200    );
10201    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10202        return Some(ResizeEdge::BottomLeft);
10203    }
10204
10205    let bottom_right_bounds = Bounds::new(
10206        Point::new(
10207            window_size.width - corner_size.width,
10208            window_size.height - corner_size.height,
10209        ),
10210        corner_size,
10211    );
10212    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10213        return Some(ResizeEdge::BottomRight);
10214    }
10215
10216    if !tiling.top && pos.y < shadow_size {
10217        Some(ResizeEdge::Top)
10218    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10219        Some(ResizeEdge::Bottom)
10220    } else if !tiling.left && pos.x < shadow_size {
10221        Some(ResizeEdge::Left)
10222    } else if !tiling.right && pos.x > window_size.width - shadow_size {
10223        Some(ResizeEdge::Right)
10224    } else {
10225        None
10226    }
10227}
10228
10229fn join_pane_into_active(
10230    active_pane: &Entity<Pane>,
10231    pane: &Entity<Pane>,
10232    window: &mut Window,
10233    cx: &mut App,
10234) {
10235    if pane == active_pane {
10236    } else if pane.read(cx).items_len() == 0 {
10237        pane.update(cx, |_, cx| {
10238            cx.emit(pane::Event::Remove {
10239                focus_on_pane: None,
10240            });
10241        })
10242    } else {
10243        move_all_items(pane, active_pane, window, cx);
10244    }
10245}
10246
10247fn move_all_items(
10248    from_pane: &Entity<Pane>,
10249    to_pane: &Entity<Pane>,
10250    window: &mut Window,
10251    cx: &mut App,
10252) {
10253    let destination_is_different = from_pane != to_pane;
10254    let mut moved_items = 0;
10255    for (item_ix, item_handle) in from_pane
10256        .read(cx)
10257        .items()
10258        .enumerate()
10259        .map(|(ix, item)| (ix, item.clone()))
10260        .collect::<Vec<_>>()
10261    {
10262        let ix = item_ix - moved_items;
10263        if destination_is_different {
10264            // Close item from previous pane
10265            from_pane.update(cx, |source, cx| {
10266                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10267            });
10268            moved_items += 1;
10269        }
10270
10271        // This automatically removes duplicate items in the pane
10272        to_pane.update(cx, |destination, cx| {
10273            destination.add_item(item_handle, true, true, None, window, cx);
10274            window.focus(&destination.focus_handle(cx), cx)
10275        });
10276    }
10277}
10278
10279pub fn move_item(
10280    source: &Entity<Pane>,
10281    destination: &Entity<Pane>,
10282    item_id_to_move: EntityId,
10283    destination_index: usize,
10284    activate: bool,
10285    window: &mut Window,
10286    cx: &mut App,
10287) {
10288    let Some((item_ix, item_handle)) = source
10289        .read(cx)
10290        .items()
10291        .enumerate()
10292        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10293        .map(|(ix, item)| (ix, item.clone()))
10294    else {
10295        // Tab was closed during drag
10296        return;
10297    };
10298
10299    if source != destination {
10300        // Close item from previous pane
10301        source.update(cx, |source, cx| {
10302            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10303        });
10304    }
10305
10306    // This automatically removes duplicate items in the pane
10307    destination.update(cx, |destination, cx| {
10308        destination.add_item_inner(
10309            item_handle,
10310            activate,
10311            activate,
10312            activate,
10313            Some(destination_index),
10314            window,
10315            cx,
10316        );
10317        if activate {
10318            window.focus(&destination.focus_handle(cx), cx)
10319        }
10320    });
10321}
10322
10323pub fn move_active_item(
10324    source: &Entity<Pane>,
10325    destination: &Entity<Pane>,
10326    focus_destination: bool,
10327    close_if_empty: bool,
10328    window: &mut Window,
10329    cx: &mut App,
10330) {
10331    if source == destination {
10332        return;
10333    }
10334    let Some(active_item) = source.read(cx).active_item() else {
10335        return;
10336    };
10337    source.update(cx, |source_pane, cx| {
10338        let item_id = active_item.item_id();
10339        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10340        destination.update(cx, |target_pane, cx| {
10341            target_pane.add_item(
10342                active_item,
10343                focus_destination,
10344                focus_destination,
10345                Some(target_pane.items_len()),
10346                window,
10347                cx,
10348            );
10349        });
10350    });
10351}
10352
10353pub fn clone_active_item(
10354    workspace_id: Option<WorkspaceId>,
10355    source: &Entity<Pane>,
10356    destination: &Entity<Pane>,
10357    focus_destination: bool,
10358    window: &mut Window,
10359    cx: &mut App,
10360) {
10361    if source == destination {
10362        return;
10363    }
10364    let Some(active_item) = source.read(cx).active_item() else {
10365        return;
10366    };
10367    if !active_item.can_split(cx) {
10368        return;
10369    }
10370    let destination = destination.downgrade();
10371    let task = active_item.clone_on_split(workspace_id, window, cx);
10372    window
10373        .spawn(cx, async move |cx| {
10374            let Some(clone) = task.await else {
10375                return;
10376            };
10377            destination
10378                .update_in(cx, |target_pane, window, cx| {
10379                    target_pane.add_item(
10380                        clone,
10381                        focus_destination,
10382                        focus_destination,
10383                        Some(target_pane.items_len()),
10384                        window,
10385                        cx,
10386                    );
10387                })
10388                .log_err();
10389        })
10390        .detach();
10391}
10392
10393#[derive(Debug)]
10394pub struct WorkspacePosition {
10395    pub window_bounds: Option<WindowBounds>,
10396    pub display: Option<Uuid>,
10397    pub centered_layout: bool,
10398}
10399
10400pub fn remote_workspace_position_from_db(
10401    connection_options: RemoteConnectionOptions,
10402    paths_to_open: &[PathBuf],
10403    cx: &App,
10404) -> Task<Result<WorkspacePosition>> {
10405    let paths = paths_to_open.to_vec();
10406    let db = WorkspaceDb::global(cx);
10407    let kvp = db::kvp::KeyValueStore::global(cx);
10408
10409    cx.background_spawn(async move {
10410        let remote_connection_id = db
10411            .get_or_create_remote_connection(connection_options)
10412            .await
10413            .context("fetching serialized ssh project")?;
10414        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10415
10416        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10417            (Some(WindowBounds::Windowed(bounds)), None)
10418        } else {
10419            let restorable_bounds = serialized_workspace
10420                .as_ref()
10421                .and_then(|workspace| {
10422                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10423                })
10424                .or_else(|| persistence::read_default_window_bounds(&kvp));
10425
10426            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10427                (Some(serialized_bounds), Some(serialized_display))
10428            } else {
10429                (None, None)
10430            }
10431        };
10432
10433        let centered_layout = serialized_workspace
10434            .as_ref()
10435            .map(|w| w.centered_layout)
10436            .unwrap_or(false);
10437
10438        Ok(WorkspacePosition {
10439            window_bounds,
10440            display,
10441            centered_layout,
10442        })
10443    })
10444}
10445
10446pub fn with_active_or_new_workspace(
10447    cx: &mut App,
10448    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10449) {
10450    match cx
10451        .active_window()
10452        .and_then(|w| w.downcast::<MultiWorkspace>())
10453    {
10454        Some(multi_workspace) => {
10455            cx.defer(move |cx| {
10456                multi_workspace
10457                    .update(cx, |multi_workspace, window, cx| {
10458                        let workspace = multi_workspace.workspace().clone();
10459                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10460                    })
10461                    .log_err();
10462            });
10463        }
10464        None => {
10465            let app_state = AppState::global(cx);
10466            open_new(
10467                OpenOptions::default(),
10468                app_state,
10469                cx,
10470                move |workspace, window, cx| f(workspace, window, cx),
10471            )
10472            .detach_and_log_err(cx);
10473        }
10474    }
10475}
10476
10477/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10478/// key. This migration path only runs once per panel per workspace.
10479fn load_legacy_panel_size(
10480    panel_key: &str,
10481    dock_position: DockPosition,
10482    workspace: &Workspace,
10483    cx: &mut App,
10484) -> Option<Pixels> {
10485    #[derive(Deserialize)]
10486    struct LegacyPanelState {
10487        #[serde(default)]
10488        width: Option<Pixels>,
10489        #[serde(default)]
10490        height: Option<Pixels>,
10491    }
10492
10493    let workspace_id = workspace
10494        .database_id()
10495        .map(|id| i64::from(id).to_string())
10496        .or_else(|| workspace.session_id())?;
10497
10498    let legacy_key = match panel_key {
10499        "ProjectPanel" => {
10500            format!("{}-{:?}", "ProjectPanel", workspace_id)
10501        }
10502        "OutlinePanel" => {
10503            format!("{}-{:?}", "OutlinePanel", workspace_id)
10504        }
10505        "GitPanel" => {
10506            format!("{}-{:?}", "GitPanel", workspace_id)
10507        }
10508        "TerminalPanel" => {
10509            format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10510        }
10511        _ => return None,
10512    };
10513
10514    let kvp = db::kvp::KeyValueStore::global(cx);
10515    let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10516    let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10517    let size = match dock_position {
10518        DockPosition::Bottom => state.height,
10519        DockPosition::Left | DockPosition::Right => state.width,
10520    }?;
10521
10522    cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10523        .detach_and_log_err(cx);
10524
10525    Some(size)
10526}
10527
10528#[cfg(test)]
10529mod tests {
10530    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10531
10532    use super::*;
10533    use crate::{
10534        dock::{PanelEvent, test::TestPanel},
10535        item::{
10536            ItemBufferKind, ItemEvent,
10537            test::{TestItem, TestProjectItem},
10538        },
10539    };
10540    use fs::FakeFs;
10541    use gpui::{
10542        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10543        UpdateGlobal, VisualTestContext, px,
10544    };
10545    use project::{Project, ProjectEntryId};
10546    use serde_json::json;
10547    use settings::SettingsStore;
10548    use util::path;
10549    use util::rel_path::rel_path;
10550
10551    #[gpui::test]
10552    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10553        init_test(cx);
10554
10555        let fs = FakeFs::new(cx.executor());
10556        let project = Project::test(fs, [], cx).await;
10557        let (workspace, cx) =
10558            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10559
10560        // Adding an item with no ambiguity renders the tab without detail.
10561        let item1 = cx.new(|cx| {
10562            let mut item = TestItem::new(cx);
10563            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10564            item
10565        });
10566        workspace.update_in(cx, |workspace, window, cx| {
10567            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10568        });
10569        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10570
10571        // Adding an item that creates ambiguity increases the level of detail on
10572        // both tabs.
10573        let item2 = cx.new_window_entity(|_window, cx| {
10574            let mut item = TestItem::new(cx);
10575            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10576            item
10577        });
10578        workspace.update_in(cx, |workspace, window, cx| {
10579            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10580        });
10581        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10582        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10583
10584        // Adding an item that creates ambiguity increases the level of detail only
10585        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10586        // we stop at the highest detail available.
10587        let item3 = cx.new(|cx| {
10588            let mut item = TestItem::new(cx);
10589            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10590            item
10591        });
10592        workspace.update_in(cx, |workspace, window, cx| {
10593            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10594        });
10595        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10596        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10597        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10598    }
10599
10600    #[gpui::test]
10601    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10602        init_test(cx);
10603
10604        let fs = FakeFs::new(cx.executor());
10605        fs.insert_tree(
10606            "/root1",
10607            json!({
10608                "one.txt": "",
10609                "two.txt": "",
10610            }),
10611        )
10612        .await;
10613        fs.insert_tree(
10614            "/root2",
10615            json!({
10616                "three.txt": "",
10617            }),
10618        )
10619        .await;
10620
10621        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10622        let (workspace, cx) =
10623            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10624        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10625        let worktree_id = project.update(cx, |project, cx| {
10626            project.worktrees(cx).next().unwrap().read(cx).id()
10627        });
10628
10629        let item1 = cx.new(|cx| {
10630            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10631        });
10632        let item2 = cx.new(|cx| {
10633            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10634        });
10635
10636        // Add an item to an empty pane
10637        workspace.update_in(cx, |workspace, window, cx| {
10638            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10639        });
10640        project.update(cx, |project, cx| {
10641            assert_eq!(
10642                project.active_entry(),
10643                project
10644                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10645                    .map(|e| e.id)
10646            );
10647        });
10648        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10649
10650        // Add a second item to a non-empty pane
10651        workspace.update_in(cx, |workspace, window, cx| {
10652            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10653        });
10654        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10655        project.update(cx, |project, cx| {
10656            assert_eq!(
10657                project.active_entry(),
10658                project
10659                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10660                    .map(|e| e.id)
10661            );
10662        });
10663
10664        // Close the active item
10665        pane.update_in(cx, |pane, window, cx| {
10666            pane.close_active_item(&Default::default(), window, cx)
10667        })
10668        .await
10669        .unwrap();
10670        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10671        project.update(cx, |project, cx| {
10672            assert_eq!(
10673                project.active_entry(),
10674                project
10675                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10676                    .map(|e| e.id)
10677            );
10678        });
10679
10680        // Add a project folder
10681        project
10682            .update(cx, |project, cx| {
10683                project.find_or_create_worktree("root2", true, cx)
10684            })
10685            .await
10686            .unwrap();
10687        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10688
10689        // Remove a project folder
10690        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10691        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10692    }
10693
10694    #[gpui::test]
10695    async fn test_close_window(cx: &mut TestAppContext) {
10696        init_test(cx);
10697
10698        let fs = FakeFs::new(cx.executor());
10699        fs.insert_tree("/root", json!({ "one": "" })).await;
10700
10701        let project = Project::test(fs, ["root".as_ref()], cx).await;
10702        let (workspace, cx) =
10703            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10704
10705        // When there are no dirty items, there's nothing to do.
10706        let item1 = cx.new(TestItem::new);
10707        workspace.update_in(cx, |w, window, cx| {
10708            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10709        });
10710        let task = workspace.update_in(cx, |w, window, cx| {
10711            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10712        });
10713        assert!(task.await.unwrap());
10714
10715        // When there are dirty untitled items, prompt to save each one. If the user
10716        // cancels any prompt, then abort.
10717        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10718        let item3 = cx.new(|cx| {
10719            TestItem::new(cx)
10720                .with_dirty(true)
10721                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10722        });
10723        workspace.update_in(cx, |w, window, cx| {
10724            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10725            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10726        });
10727        let task = workspace.update_in(cx, |w, window, cx| {
10728            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10729        });
10730        cx.executor().run_until_parked();
10731        cx.simulate_prompt_answer("Cancel"); // cancel save all
10732        cx.executor().run_until_parked();
10733        assert!(!cx.has_pending_prompt());
10734        assert!(!task.await.unwrap());
10735    }
10736
10737    #[gpui::test]
10738    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10739        init_test(cx);
10740
10741        let fs = FakeFs::new(cx.executor());
10742        fs.insert_tree("/root", json!({ "one": "" })).await;
10743
10744        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10745        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10746        let multi_workspace_handle =
10747            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10748        cx.run_until_parked();
10749
10750        let workspace_a = multi_workspace_handle
10751            .read_with(cx, |mw, _| mw.workspace().clone())
10752            .unwrap();
10753
10754        let workspace_b = multi_workspace_handle
10755            .update(cx, |mw, window, cx| {
10756                mw.test_add_workspace(project_b, window, cx)
10757            })
10758            .unwrap();
10759
10760        // Activate workspace A
10761        multi_workspace_handle
10762            .update(cx, |mw, window, cx| {
10763                let workspace = mw.workspaces()[0].clone();
10764                mw.activate(workspace, window, cx);
10765            })
10766            .unwrap();
10767
10768        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10769
10770        // Workspace A has a clean item
10771        let item_a = cx.new(TestItem::new);
10772        workspace_a.update_in(cx, |w, window, cx| {
10773            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10774        });
10775
10776        // Workspace B has a dirty item
10777        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10778        workspace_b.update_in(cx, |w, window, cx| {
10779            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10780        });
10781
10782        // Verify workspace A is active
10783        multi_workspace_handle
10784            .read_with(cx, |mw, _| {
10785                assert_eq!(mw.active_workspace_index(), 0);
10786            })
10787            .unwrap();
10788
10789        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10790        multi_workspace_handle
10791            .update(cx, |mw, window, cx| {
10792                mw.close_window(&CloseWindow, window, cx);
10793            })
10794            .unwrap();
10795        cx.run_until_parked();
10796
10797        // Workspace B should now be active since it has dirty items that need attention
10798        multi_workspace_handle
10799            .read_with(cx, |mw, _| {
10800                assert_eq!(
10801                    mw.active_workspace_index(),
10802                    1,
10803                    "workspace B should be activated when it prompts"
10804                );
10805            })
10806            .unwrap();
10807
10808        // User cancels the save prompt from workspace B
10809        cx.simulate_prompt_answer("Cancel");
10810        cx.run_until_parked();
10811
10812        // Window should still exist because workspace B's close was cancelled
10813        assert!(
10814            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10815            "window should still exist after cancelling one workspace's close"
10816        );
10817    }
10818
10819    #[gpui::test]
10820    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10821        init_test(cx);
10822
10823        // Register TestItem as a serializable item
10824        cx.update(|cx| {
10825            register_serializable_item::<TestItem>(cx);
10826        });
10827
10828        let fs = FakeFs::new(cx.executor());
10829        fs.insert_tree("/root", json!({ "one": "" })).await;
10830
10831        let project = Project::test(fs, ["root".as_ref()], cx).await;
10832        let (workspace, cx) =
10833            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10834
10835        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10836        let item1 = cx.new(|cx| {
10837            TestItem::new(cx)
10838                .with_dirty(true)
10839                .with_serialize(|| Some(Task::ready(Ok(()))))
10840        });
10841        let item2 = cx.new(|cx| {
10842            TestItem::new(cx)
10843                .with_dirty(true)
10844                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10845                .with_serialize(|| Some(Task::ready(Ok(()))))
10846        });
10847        workspace.update_in(cx, |w, window, cx| {
10848            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10849            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10850        });
10851        let task = workspace.update_in(cx, |w, window, cx| {
10852            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10853        });
10854        assert!(task.await.unwrap());
10855    }
10856
10857    #[gpui::test]
10858    async fn test_close_pane_items(cx: &mut TestAppContext) {
10859        init_test(cx);
10860
10861        let fs = FakeFs::new(cx.executor());
10862
10863        let project = Project::test(fs, None, cx).await;
10864        let (workspace, cx) =
10865            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10866
10867        let item1 = cx.new(|cx| {
10868            TestItem::new(cx)
10869                .with_dirty(true)
10870                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10871        });
10872        let item2 = cx.new(|cx| {
10873            TestItem::new(cx)
10874                .with_dirty(true)
10875                .with_conflict(true)
10876                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10877        });
10878        let item3 = cx.new(|cx| {
10879            TestItem::new(cx)
10880                .with_dirty(true)
10881                .with_conflict(true)
10882                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10883        });
10884        let item4 = cx.new(|cx| {
10885            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10886                let project_item = TestProjectItem::new_untitled(cx);
10887                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10888                project_item
10889            }])
10890        });
10891        let pane = workspace.update_in(cx, |workspace, window, cx| {
10892            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10893            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10894            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10895            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10896            workspace.active_pane().clone()
10897        });
10898
10899        let close_items = pane.update_in(cx, |pane, window, cx| {
10900            pane.activate_item(1, true, true, window, cx);
10901            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10902            let item1_id = item1.item_id();
10903            let item3_id = item3.item_id();
10904            let item4_id = item4.item_id();
10905            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10906                [item1_id, item3_id, item4_id].contains(&id)
10907            })
10908        });
10909        cx.executor().run_until_parked();
10910
10911        assert!(cx.has_pending_prompt());
10912        cx.simulate_prompt_answer("Save all");
10913
10914        cx.executor().run_until_parked();
10915
10916        // Item 1 is saved. There's a prompt to save item 3.
10917        pane.update(cx, |pane, cx| {
10918            assert_eq!(item1.read(cx).save_count, 1);
10919            assert_eq!(item1.read(cx).save_as_count, 0);
10920            assert_eq!(item1.read(cx).reload_count, 0);
10921            assert_eq!(pane.items_len(), 3);
10922            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10923        });
10924        assert!(cx.has_pending_prompt());
10925
10926        // Cancel saving item 3.
10927        cx.simulate_prompt_answer("Discard");
10928        cx.executor().run_until_parked();
10929
10930        // Item 3 is reloaded. There's a prompt to save item 4.
10931        pane.update(cx, |pane, cx| {
10932            assert_eq!(item3.read(cx).save_count, 0);
10933            assert_eq!(item3.read(cx).save_as_count, 0);
10934            assert_eq!(item3.read(cx).reload_count, 1);
10935            assert_eq!(pane.items_len(), 2);
10936            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10937        });
10938
10939        // There's a prompt for a path for item 4.
10940        cx.simulate_new_path_selection(|_| Some(Default::default()));
10941        close_items.await.unwrap();
10942
10943        // The requested items are closed.
10944        pane.update(cx, |pane, cx| {
10945            assert_eq!(item4.read(cx).save_count, 0);
10946            assert_eq!(item4.read(cx).save_as_count, 1);
10947            assert_eq!(item4.read(cx).reload_count, 0);
10948            assert_eq!(pane.items_len(), 1);
10949            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10950        });
10951    }
10952
10953    #[gpui::test]
10954    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10955        init_test(cx);
10956
10957        let fs = FakeFs::new(cx.executor());
10958        let project = Project::test(fs, [], cx).await;
10959        let (workspace, cx) =
10960            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10961
10962        // Create several workspace items with single project entries, and two
10963        // workspace items with multiple project entries.
10964        let single_entry_items = (0..=4)
10965            .map(|project_entry_id| {
10966                cx.new(|cx| {
10967                    TestItem::new(cx)
10968                        .with_dirty(true)
10969                        .with_project_items(&[dirty_project_item(
10970                            project_entry_id,
10971                            &format!("{project_entry_id}.txt"),
10972                            cx,
10973                        )])
10974                })
10975            })
10976            .collect::<Vec<_>>();
10977        let item_2_3 = cx.new(|cx| {
10978            TestItem::new(cx)
10979                .with_dirty(true)
10980                .with_buffer_kind(ItemBufferKind::Multibuffer)
10981                .with_project_items(&[
10982                    single_entry_items[2].read(cx).project_items[0].clone(),
10983                    single_entry_items[3].read(cx).project_items[0].clone(),
10984                ])
10985        });
10986        let item_3_4 = cx.new(|cx| {
10987            TestItem::new(cx)
10988                .with_dirty(true)
10989                .with_buffer_kind(ItemBufferKind::Multibuffer)
10990                .with_project_items(&[
10991                    single_entry_items[3].read(cx).project_items[0].clone(),
10992                    single_entry_items[4].read(cx).project_items[0].clone(),
10993                ])
10994        });
10995
10996        // Create two panes that contain the following project entries:
10997        //   left pane:
10998        //     multi-entry items:   (2, 3)
10999        //     single-entry items:  0, 2, 3, 4
11000        //   right pane:
11001        //     single-entry items:  4, 1
11002        //     multi-entry items:   (3, 4)
11003        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
11004            let left_pane = workspace.active_pane().clone();
11005            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
11006            workspace.add_item_to_active_pane(
11007                single_entry_items[0].boxed_clone(),
11008                None,
11009                true,
11010                window,
11011                cx,
11012            );
11013            workspace.add_item_to_active_pane(
11014                single_entry_items[2].boxed_clone(),
11015                None,
11016                true,
11017                window,
11018                cx,
11019            );
11020            workspace.add_item_to_active_pane(
11021                single_entry_items[3].boxed_clone(),
11022                None,
11023                true,
11024                window,
11025                cx,
11026            );
11027            workspace.add_item_to_active_pane(
11028                single_entry_items[4].boxed_clone(),
11029                None,
11030                true,
11031                window,
11032                cx,
11033            );
11034
11035            let right_pane =
11036                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11037
11038            let boxed_clone = single_entry_items[1].boxed_clone();
11039            let right_pane = window.spawn(cx, async move |cx| {
11040                right_pane.await.inspect(|right_pane| {
11041                    right_pane
11042                        .update_in(cx, |pane, window, cx| {
11043                            pane.add_item(boxed_clone, true, true, None, window, cx);
11044                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11045                        })
11046                        .unwrap();
11047                })
11048            });
11049
11050            (left_pane, right_pane)
11051        });
11052        let right_pane = right_pane.await.unwrap();
11053        cx.focus(&right_pane);
11054
11055        let close = right_pane.update_in(cx, |pane, window, cx| {
11056            pane.close_all_items(&CloseAllItems::default(), window, cx)
11057                .unwrap()
11058        });
11059        cx.executor().run_until_parked();
11060
11061        let msg = cx.pending_prompt().unwrap().0;
11062        assert!(msg.contains("1.txt"));
11063        assert!(!msg.contains("2.txt"));
11064        assert!(!msg.contains("3.txt"));
11065        assert!(!msg.contains("4.txt"));
11066
11067        // With best-effort close, cancelling item 1 keeps it open but items 4
11068        // and (3,4) still close since their entries exist in left pane.
11069        cx.simulate_prompt_answer("Cancel");
11070        close.await;
11071
11072        right_pane.read_with(cx, |pane, _| {
11073            assert_eq!(pane.items_len(), 1);
11074        });
11075
11076        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11077        left_pane
11078            .update_in(cx, |left_pane, window, cx| {
11079                left_pane.close_item_by_id(
11080                    single_entry_items[3].entity_id(),
11081                    SaveIntent::Skip,
11082                    window,
11083                    cx,
11084                )
11085            })
11086            .await
11087            .unwrap();
11088
11089        let close = left_pane.update_in(cx, |pane, window, cx| {
11090            pane.close_all_items(&CloseAllItems::default(), window, cx)
11091                .unwrap()
11092        });
11093        cx.executor().run_until_parked();
11094
11095        let details = cx.pending_prompt().unwrap().1;
11096        assert!(details.contains("0.txt"));
11097        assert!(details.contains("3.txt"));
11098        assert!(details.contains("4.txt"));
11099        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11100        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11101        // assert!(!details.contains("2.txt"));
11102
11103        cx.simulate_prompt_answer("Save all");
11104        cx.executor().run_until_parked();
11105        close.await;
11106
11107        left_pane.read_with(cx, |pane, _| {
11108            assert_eq!(pane.items_len(), 0);
11109        });
11110    }
11111
11112    #[gpui::test]
11113    async fn test_autosave(cx: &mut gpui::TestAppContext) {
11114        init_test(cx);
11115
11116        let fs = FakeFs::new(cx.executor());
11117        let project = Project::test(fs, [], cx).await;
11118        let (workspace, cx) =
11119            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11120        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11121
11122        let item = cx.new(|cx| {
11123            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11124        });
11125        let item_id = item.entity_id();
11126        workspace.update_in(cx, |workspace, window, cx| {
11127            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11128        });
11129
11130        // Autosave on window change.
11131        item.update(cx, |item, cx| {
11132            SettingsStore::update_global(cx, |settings, cx| {
11133                settings.update_user_settings(cx, |settings| {
11134                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11135                })
11136            });
11137            item.is_dirty = true;
11138        });
11139
11140        // Deactivating the window saves the file.
11141        cx.deactivate_window();
11142        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11143
11144        // Re-activating the window doesn't save the file.
11145        cx.update(|window, _| window.activate_window());
11146        cx.executor().run_until_parked();
11147        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11148
11149        // Autosave on focus change.
11150        item.update_in(cx, |item, window, cx| {
11151            cx.focus_self(window);
11152            SettingsStore::update_global(cx, |settings, cx| {
11153                settings.update_user_settings(cx, |settings| {
11154                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11155                })
11156            });
11157            item.is_dirty = true;
11158        });
11159        // Blurring the item saves the file.
11160        item.update_in(cx, |_, window, _| window.blur());
11161        cx.executor().run_until_parked();
11162        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11163
11164        // Deactivating the window still saves the file.
11165        item.update_in(cx, |item, window, cx| {
11166            cx.focus_self(window);
11167            item.is_dirty = true;
11168        });
11169        cx.deactivate_window();
11170        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11171
11172        // Autosave after delay.
11173        item.update(cx, |item, cx| {
11174            SettingsStore::update_global(cx, |settings, cx| {
11175                settings.update_user_settings(cx, |settings| {
11176                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11177                        milliseconds: 500.into(),
11178                    });
11179                })
11180            });
11181            item.is_dirty = true;
11182            cx.emit(ItemEvent::Edit);
11183        });
11184
11185        // Delay hasn't fully expired, so the file is still dirty and unsaved.
11186        cx.executor().advance_clock(Duration::from_millis(250));
11187        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11188
11189        // After delay expires, the file is saved.
11190        cx.executor().advance_clock(Duration::from_millis(250));
11191        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11192
11193        // Autosave after delay, should save earlier than delay if tab is closed
11194        item.update(cx, |item, cx| {
11195            item.is_dirty = true;
11196            cx.emit(ItemEvent::Edit);
11197        });
11198        cx.executor().advance_clock(Duration::from_millis(250));
11199        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11200
11201        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11202        pane.update_in(cx, |pane, window, cx| {
11203            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11204        })
11205        .await
11206        .unwrap();
11207        assert!(!cx.has_pending_prompt());
11208        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11209
11210        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11211        workspace.update_in(cx, |workspace, window, cx| {
11212            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11213        });
11214        item.update_in(cx, |item, _window, cx| {
11215            item.is_dirty = true;
11216            for project_item in &mut item.project_items {
11217                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11218            }
11219        });
11220        cx.run_until_parked();
11221        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11222
11223        // Autosave on focus change, ensuring closing the tab counts as such.
11224        item.update(cx, |item, cx| {
11225            SettingsStore::update_global(cx, |settings, cx| {
11226                settings.update_user_settings(cx, |settings| {
11227                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11228                })
11229            });
11230            item.is_dirty = true;
11231            for project_item in &mut item.project_items {
11232                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11233            }
11234        });
11235
11236        pane.update_in(cx, |pane, window, cx| {
11237            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11238        })
11239        .await
11240        .unwrap();
11241        assert!(!cx.has_pending_prompt());
11242        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11243
11244        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11245        workspace.update_in(cx, |workspace, window, cx| {
11246            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11247        });
11248        item.update_in(cx, |item, window, cx| {
11249            item.project_items[0].update(cx, |item, _| {
11250                item.entry_id = None;
11251            });
11252            item.is_dirty = true;
11253            window.blur();
11254        });
11255        cx.run_until_parked();
11256        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11257
11258        // Ensure autosave is prevented for deleted files also when closing the buffer.
11259        let _close_items = pane.update_in(cx, |pane, window, cx| {
11260            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11261        });
11262        cx.run_until_parked();
11263        assert!(cx.has_pending_prompt());
11264        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11265    }
11266
11267    #[gpui::test]
11268    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11269        init_test(cx);
11270
11271        let fs = FakeFs::new(cx.executor());
11272        let project = Project::test(fs, [], cx).await;
11273        let (workspace, cx) =
11274            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11275
11276        // Create a multibuffer-like item with two child focus handles,
11277        // simulating individual buffer editors within a multibuffer.
11278        let item = cx.new(|cx| {
11279            TestItem::new(cx)
11280                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11281                .with_child_focus_handles(2, cx)
11282        });
11283        workspace.update_in(cx, |workspace, window, cx| {
11284            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11285        });
11286
11287        // Set autosave to OnFocusChange and focus the first child handle,
11288        // simulating the user's cursor being inside one of the multibuffer's excerpts.
11289        item.update_in(cx, |item, window, cx| {
11290            SettingsStore::update_global(cx, |settings, cx| {
11291                settings.update_user_settings(cx, |settings| {
11292                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11293                })
11294            });
11295            item.is_dirty = true;
11296            window.focus(&item.child_focus_handles[0], cx);
11297        });
11298        cx.executor().run_until_parked();
11299        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11300
11301        // Moving focus from one child to another within the same item should
11302        // NOT trigger autosave — focus is still within the item's focus hierarchy.
11303        item.update_in(cx, |item, window, cx| {
11304            window.focus(&item.child_focus_handles[1], cx);
11305        });
11306        cx.executor().run_until_parked();
11307        item.read_with(cx, |item, _| {
11308            assert_eq!(
11309                item.save_count, 0,
11310                "Switching focus between children within the same item should not autosave"
11311            );
11312        });
11313
11314        // Blurring the item saves the file. This is the core regression scenario:
11315        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11316        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11317        // the leaf is always a child focus handle, so `on_blur` never detected
11318        // focus leaving the item.
11319        item.update_in(cx, |_, window, _| window.blur());
11320        cx.executor().run_until_parked();
11321        item.read_with(cx, |item, _| {
11322            assert_eq!(
11323                item.save_count, 1,
11324                "Blurring should trigger autosave when focus was on a child of the item"
11325            );
11326        });
11327
11328        // Deactivating the window should also trigger autosave when a child of
11329        // the multibuffer item currently owns focus.
11330        item.update_in(cx, |item, window, cx| {
11331            item.is_dirty = true;
11332            window.focus(&item.child_focus_handles[0], cx);
11333        });
11334        cx.executor().run_until_parked();
11335        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11336
11337        cx.deactivate_window();
11338        item.read_with(cx, |item, _| {
11339            assert_eq!(
11340                item.save_count, 2,
11341                "Deactivating window should trigger autosave when focus was on a child"
11342            );
11343        });
11344    }
11345
11346    #[gpui::test]
11347    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11348        init_test(cx);
11349
11350        let fs = FakeFs::new(cx.executor());
11351
11352        let project = Project::test(fs, [], cx).await;
11353        let (workspace, cx) =
11354            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11355
11356        let item = cx.new(|cx| {
11357            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11358        });
11359        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11360        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11361        let toolbar_notify_count = Rc::new(RefCell::new(0));
11362
11363        workspace.update_in(cx, |workspace, window, cx| {
11364            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11365            let toolbar_notification_count = toolbar_notify_count.clone();
11366            cx.observe_in(&toolbar, window, move |_, _, _, _| {
11367                *toolbar_notification_count.borrow_mut() += 1
11368            })
11369            .detach();
11370        });
11371
11372        pane.read_with(cx, |pane, _| {
11373            assert!(!pane.can_navigate_backward());
11374            assert!(!pane.can_navigate_forward());
11375        });
11376
11377        item.update_in(cx, |item, _, cx| {
11378            item.set_state("one".to_string(), cx);
11379        });
11380
11381        // Toolbar must be notified to re-render the navigation buttons
11382        assert_eq!(*toolbar_notify_count.borrow(), 1);
11383
11384        pane.read_with(cx, |pane, _| {
11385            assert!(pane.can_navigate_backward());
11386            assert!(!pane.can_navigate_forward());
11387        });
11388
11389        workspace
11390            .update_in(cx, |workspace, window, cx| {
11391                workspace.go_back(pane.downgrade(), window, cx)
11392            })
11393            .await
11394            .unwrap();
11395
11396        assert_eq!(*toolbar_notify_count.borrow(), 2);
11397        pane.read_with(cx, |pane, _| {
11398            assert!(!pane.can_navigate_backward());
11399            assert!(pane.can_navigate_forward());
11400        });
11401    }
11402
11403    /// Tests that the navigation history deduplicates entries for the same item.
11404    ///
11405    /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11406    /// the navigation history deduplicates by keeping only the most recent visit to each item,
11407    /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11408    /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11409    /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11410    ///
11411    /// This behavior prevents the navigation history from growing unnecessarily large and provides
11412    /// a better user experience by eliminating redundant navigation steps when jumping between files.
11413    #[gpui::test]
11414    async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11415        init_test(cx);
11416
11417        let fs = FakeFs::new(cx.executor());
11418        let project = Project::test(fs, [], cx).await;
11419        let (workspace, cx) =
11420            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11421
11422        let item_a = cx.new(|cx| {
11423            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11424        });
11425        let item_b = cx.new(|cx| {
11426            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11427        });
11428        let item_c = cx.new(|cx| {
11429            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11430        });
11431
11432        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11433
11434        workspace.update_in(cx, |workspace, window, cx| {
11435            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11436            workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11437            workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11438        });
11439
11440        workspace.update_in(cx, |workspace, window, cx| {
11441            workspace.activate_item(&item_a, false, false, window, cx);
11442        });
11443        cx.run_until_parked();
11444
11445        workspace.update_in(cx, |workspace, window, cx| {
11446            workspace.activate_item(&item_b, false, false, window, cx);
11447        });
11448        cx.run_until_parked();
11449
11450        workspace.update_in(cx, |workspace, window, cx| {
11451            workspace.activate_item(&item_a, false, false, window, cx);
11452        });
11453        cx.run_until_parked();
11454
11455        workspace.update_in(cx, |workspace, window, cx| {
11456            workspace.activate_item(&item_b, false, false, window, cx);
11457        });
11458        cx.run_until_parked();
11459
11460        workspace.update_in(cx, |workspace, window, cx| {
11461            workspace.activate_item(&item_a, false, false, window, cx);
11462        });
11463        cx.run_until_parked();
11464
11465        workspace.update_in(cx, |workspace, window, cx| {
11466            workspace.activate_item(&item_b, false, false, window, cx);
11467        });
11468        cx.run_until_parked();
11469
11470        workspace.update_in(cx, |workspace, window, cx| {
11471            workspace.activate_item(&item_c, false, false, window, cx);
11472        });
11473        cx.run_until_parked();
11474
11475        let backward_count = pane.read_with(cx, |pane, cx| {
11476            let mut count = 0;
11477            pane.nav_history().for_each_entry(cx, &mut |_, _| {
11478                count += 1;
11479            });
11480            count
11481        });
11482        assert!(
11483            backward_count <= 4,
11484            "Should have at most 4 entries, got {}",
11485            backward_count
11486        );
11487
11488        workspace
11489            .update_in(cx, |workspace, window, cx| {
11490                workspace.go_back(pane.downgrade(), window, cx)
11491            })
11492            .await
11493            .unwrap();
11494
11495        let active_item = workspace.read_with(cx, |workspace, cx| {
11496            workspace.active_item(cx).unwrap().item_id()
11497        });
11498        assert_eq!(
11499            active_item,
11500            item_b.entity_id(),
11501            "After first go_back, should be at item B"
11502        );
11503
11504        workspace
11505            .update_in(cx, |workspace, window, cx| {
11506                workspace.go_back(pane.downgrade(), window, cx)
11507            })
11508            .await
11509            .unwrap();
11510
11511        let active_item = workspace.read_with(cx, |workspace, cx| {
11512            workspace.active_item(cx).unwrap().item_id()
11513        });
11514        assert_eq!(
11515            active_item,
11516            item_a.entity_id(),
11517            "After second go_back, should be at item A"
11518        );
11519
11520        pane.read_with(cx, |pane, _| {
11521            assert!(pane.can_navigate_forward(), "Should be able to go forward");
11522        });
11523    }
11524
11525    #[gpui::test]
11526    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11527        init_test(cx);
11528        let fs = FakeFs::new(cx.executor());
11529        let project = Project::test(fs, [], cx).await;
11530        let (multi_workspace, cx) =
11531            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11532        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11533
11534        workspace.update_in(cx, |workspace, window, cx| {
11535            let first_item = cx.new(|cx| {
11536                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11537            });
11538            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11539            workspace.split_pane(
11540                workspace.active_pane().clone(),
11541                SplitDirection::Right,
11542                window,
11543                cx,
11544            );
11545            workspace.split_pane(
11546                workspace.active_pane().clone(),
11547                SplitDirection::Right,
11548                window,
11549                cx,
11550            );
11551        });
11552
11553        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11554            let panes = workspace.center.panes();
11555            assert!(panes.len() >= 2);
11556            (
11557                panes.first().expect("at least one pane").entity_id(),
11558                panes.last().expect("at least one pane").entity_id(),
11559            )
11560        });
11561
11562        workspace.update_in(cx, |workspace, window, cx| {
11563            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11564        });
11565        workspace.update(cx, |workspace, _| {
11566            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11567            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11568        });
11569
11570        cx.dispatch_action(ActivateLastPane);
11571
11572        workspace.update(cx, |workspace, _| {
11573            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11574        });
11575    }
11576
11577    #[gpui::test]
11578    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11579        init_test(cx);
11580        let fs = FakeFs::new(cx.executor());
11581
11582        let project = Project::test(fs, [], cx).await;
11583        let (workspace, cx) =
11584            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11585
11586        let panel = workspace.update_in(cx, |workspace, window, cx| {
11587            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11588            workspace.add_panel(panel.clone(), window, cx);
11589
11590            workspace
11591                .right_dock()
11592                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11593
11594            panel
11595        });
11596
11597        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11598        pane.update_in(cx, |pane, window, cx| {
11599            let item = cx.new(TestItem::new);
11600            pane.add_item(Box::new(item), true, true, None, window, cx);
11601        });
11602
11603        // Transfer focus from center to panel
11604        workspace.update_in(cx, |workspace, window, cx| {
11605            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11606        });
11607
11608        workspace.update_in(cx, |workspace, window, cx| {
11609            assert!(workspace.right_dock().read(cx).is_open());
11610            assert!(!panel.is_zoomed(window, cx));
11611            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11612        });
11613
11614        // Transfer focus from panel to center
11615        workspace.update_in(cx, |workspace, window, cx| {
11616            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11617        });
11618
11619        workspace.update_in(cx, |workspace, window, cx| {
11620            assert!(workspace.right_dock().read(cx).is_open());
11621            assert!(!panel.is_zoomed(window, cx));
11622            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11623            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11624        });
11625
11626        // Close the dock
11627        workspace.update_in(cx, |workspace, window, cx| {
11628            workspace.toggle_dock(DockPosition::Right, window, cx);
11629        });
11630
11631        workspace.update_in(cx, |workspace, window, cx| {
11632            assert!(!workspace.right_dock().read(cx).is_open());
11633            assert!(!panel.is_zoomed(window, cx));
11634            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11635            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11636        });
11637
11638        // Open the dock
11639        workspace.update_in(cx, |workspace, window, cx| {
11640            workspace.toggle_dock(DockPosition::Right, window, cx);
11641        });
11642
11643        workspace.update_in(cx, |workspace, window, cx| {
11644            assert!(workspace.right_dock().read(cx).is_open());
11645            assert!(!panel.is_zoomed(window, cx));
11646            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11647        });
11648
11649        // Focus and zoom panel
11650        panel.update_in(cx, |panel, window, cx| {
11651            cx.focus_self(window);
11652            panel.set_zoomed(true, window, cx)
11653        });
11654
11655        workspace.update_in(cx, |workspace, window, cx| {
11656            assert!(workspace.right_dock().read(cx).is_open());
11657            assert!(panel.is_zoomed(window, cx));
11658            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11659        });
11660
11661        // Transfer focus to the center closes the dock
11662        workspace.update_in(cx, |workspace, window, cx| {
11663            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11664        });
11665
11666        workspace.update_in(cx, |workspace, window, cx| {
11667            assert!(!workspace.right_dock().read(cx).is_open());
11668            assert!(panel.is_zoomed(window, cx));
11669            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11670        });
11671
11672        // Transferring focus back to the panel keeps it zoomed
11673        workspace.update_in(cx, |workspace, window, cx| {
11674            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11675        });
11676
11677        workspace.update_in(cx, |workspace, window, cx| {
11678            assert!(workspace.right_dock().read(cx).is_open());
11679            assert!(panel.is_zoomed(window, cx));
11680            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11681        });
11682
11683        // Close the dock while it is zoomed
11684        workspace.update_in(cx, |workspace, window, cx| {
11685            workspace.toggle_dock(DockPosition::Right, window, cx)
11686        });
11687
11688        workspace.update_in(cx, |workspace, window, cx| {
11689            assert!(!workspace.right_dock().read(cx).is_open());
11690            assert!(panel.is_zoomed(window, cx));
11691            assert!(workspace.zoomed.is_none());
11692            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11693        });
11694
11695        // Opening the dock, when it's zoomed, retains focus
11696        workspace.update_in(cx, |workspace, window, cx| {
11697            workspace.toggle_dock(DockPosition::Right, window, cx)
11698        });
11699
11700        workspace.update_in(cx, |workspace, window, cx| {
11701            assert!(workspace.right_dock().read(cx).is_open());
11702            assert!(panel.is_zoomed(window, cx));
11703            assert!(workspace.zoomed.is_some());
11704            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11705        });
11706
11707        // Unzoom and close the panel, zoom the active pane.
11708        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11709        workspace.update_in(cx, |workspace, window, cx| {
11710            workspace.toggle_dock(DockPosition::Right, window, cx)
11711        });
11712        pane.update_in(cx, |pane, window, cx| {
11713            pane.toggle_zoom(&Default::default(), window, cx)
11714        });
11715
11716        // Opening a dock unzooms the pane.
11717        workspace.update_in(cx, |workspace, window, cx| {
11718            workspace.toggle_dock(DockPosition::Right, window, cx)
11719        });
11720        workspace.update_in(cx, |workspace, window, cx| {
11721            let pane = pane.read(cx);
11722            assert!(!pane.is_zoomed());
11723            assert!(!pane.focus_handle(cx).is_focused(window));
11724            assert!(workspace.right_dock().read(cx).is_open());
11725            assert!(workspace.zoomed.is_none());
11726        });
11727    }
11728
11729    #[gpui::test]
11730    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11731        init_test(cx);
11732        let fs = FakeFs::new(cx.executor());
11733
11734        let project = Project::test(fs, [], cx).await;
11735        let (workspace, cx) =
11736            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11737
11738        let panel = workspace.update_in(cx, |workspace, window, cx| {
11739            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11740            workspace.add_panel(panel.clone(), window, cx);
11741            panel
11742        });
11743
11744        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11745        pane.update_in(cx, |pane, window, cx| {
11746            let item = cx.new(TestItem::new);
11747            pane.add_item(Box::new(item), true, true, None, window, cx);
11748        });
11749
11750        // Enable close_panel_on_toggle
11751        cx.update_global(|store: &mut SettingsStore, cx| {
11752            store.update_user_settings(cx, |settings| {
11753                settings.workspace.close_panel_on_toggle = Some(true);
11754            });
11755        });
11756
11757        // Panel starts closed. Toggling should open and focus it.
11758        workspace.update_in(cx, |workspace, window, cx| {
11759            assert!(!workspace.right_dock().read(cx).is_open());
11760            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11761        });
11762
11763        workspace.update_in(cx, |workspace, window, cx| {
11764            assert!(
11765                workspace.right_dock().read(cx).is_open(),
11766                "Dock should be open after toggling from center"
11767            );
11768            assert!(
11769                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11770                "Panel should be focused after toggling from center"
11771            );
11772        });
11773
11774        // Panel is open and focused. Toggling should close the panel and
11775        // return focus to the center.
11776        workspace.update_in(cx, |workspace, window, cx| {
11777            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11778        });
11779
11780        workspace.update_in(cx, |workspace, window, cx| {
11781            assert!(
11782                !workspace.right_dock().read(cx).is_open(),
11783                "Dock should be closed after toggling from focused panel"
11784            );
11785            assert!(
11786                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11787                "Panel should not be focused after toggling from focused panel"
11788            );
11789        });
11790
11791        // Open the dock and focus something else so the panel is open but not
11792        // focused. Toggling should focus the panel (not close it).
11793        workspace.update_in(cx, |workspace, window, cx| {
11794            workspace
11795                .right_dock()
11796                .update(cx, |dock, cx| dock.set_open(true, window, cx));
11797            window.focus(&pane.read(cx).focus_handle(cx), cx);
11798        });
11799
11800        workspace.update_in(cx, |workspace, window, cx| {
11801            assert!(workspace.right_dock().read(cx).is_open());
11802            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11803            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11804        });
11805
11806        workspace.update_in(cx, |workspace, window, cx| {
11807            assert!(
11808                workspace.right_dock().read(cx).is_open(),
11809                "Dock should remain open when toggling focuses an open-but-unfocused panel"
11810            );
11811            assert!(
11812                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11813                "Panel should be focused after toggling an open-but-unfocused panel"
11814            );
11815        });
11816
11817        // Now disable the setting and verify the original behavior: toggling
11818        // from a focused panel moves focus to center but leaves the dock open.
11819        cx.update_global(|store: &mut SettingsStore, cx| {
11820            store.update_user_settings(cx, |settings| {
11821                settings.workspace.close_panel_on_toggle = Some(false);
11822            });
11823        });
11824
11825        workspace.update_in(cx, |workspace, window, cx| {
11826            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11827        });
11828
11829        workspace.update_in(cx, |workspace, window, cx| {
11830            assert!(
11831                workspace.right_dock().read(cx).is_open(),
11832                "Dock should remain open when setting is disabled"
11833            );
11834            assert!(
11835                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11836                "Panel should not be focused after toggling with setting disabled"
11837            );
11838        });
11839    }
11840
11841    #[gpui::test]
11842    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11843        init_test(cx);
11844        let fs = FakeFs::new(cx.executor());
11845
11846        let project = Project::test(fs, [], cx).await;
11847        let (workspace, cx) =
11848            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11849
11850        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11851            workspace.active_pane().clone()
11852        });
11853
11854        // Add an item to the pane so it can be zoomed
11855        workspace.update_in(cx, |workspace, window, cx| {
11856            let item = cx.new(TestItem::new);
11857            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11858        });
11859
11860        // Initially not zoomed
11861        workspace.update_in(cx, |workspace, _window, cx| {
11862            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11863            assert!(
11864                workspace.zoomed.is_none(),
11865                "Workspace should track no zoomed pane"
11866            );
11867            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11868        });
11869
11870        // Zoom In
11871        pane.update_in(cx, |pane, window, cx| {
11872            pane.zoom_in(&crate::ZoomIn, window, cx);
11873        });
11874
11875        workspace.update_in(cx, |workspace, window, cx| {
11876            assert!(
11877                pane.read(cx).is_zoomed(),
11878                "Pane should be zoomed after ZoomIn"
11879            );
11880            assert!(
11881                workspace.zoomed.is_some(),
11882                "Workspace should track the zoomed pane"
11883            );
11884            assert!(
11885                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11886                "ZoomIn should focus the pane"
11887            );
11888        });
11889
11890        // Zoom In again is a no-op
11891        pane.update_in(cx, |pane, window, cx| {
11892            pane.zoom_in(&crate::ZoomIn, window, cx);
11893        });
11894
11895        workspace.update_in(cx, |workspace, window, cx| {
11896            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11897            assert!(
11898                workspace.zoomed.is_some(),
11899                "Workspace still tracks zoomed pane"
11900            );
11901            assert!(
11902                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11903                "Pane remains focused after repeated ZoomIn"
11904            );
11905        });
11906
11907        // Zoom Out
11908        pane.update_in(cx, |pane, window, cx| {
11909            pane.zoom_out(&crate::ZoomOut, window, cx);
11910        });
11911
11912        workspace.update_in(cx, |workspace, _window, cx| {
11913            assert!(
11914                !pane.read(cx).is_zoomed(),
11915                "Pane should unzoom after ZoomOut"
11916            );
11917            assert!(
11918                workspace.zoomed.is_none(),
11919                "Workspace clears zoom tracking after ZoomOut"
11920            );
11921        });
11922
11923        // Zoom Out again is a no-op
11924        pane.update_in(cx, |pane, window, cx| {
11925            pane.zoom_out(&crate::ZoomOut, window, cx);
11926        });
11927
11928        workspace.update_in(cx, |workspace, _window, cx| {
11929            assert!(
11930                !pane.read(cx).is_zoomed(),
11931                "Second ZoomOut keeps pane unzoomed"
11932            );
11933            assert!(
11934                workspace.zoomed.is_none(),
11935                "Workspace remains without zoomed pane"
11936            );
11937        });
11938    }
11939
11940    #[gpui::test]
11941    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11942        init_test(cx);
11943        let fs = FakeFs::new(cx.executor());
11944
11945        let project = Project::test(fs, [], cx).await;
11946        let (workspace, cx) =
11947            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11948        workspace.update_in(cx, |workspace, window, cx| {
11949            // Open two docks
11950            let left_dock = workspace.dock_at_position(DockPosition::Left);
11951            let right_dock = workspace.dock_at_position(DockPosition::Right);
11952
11953            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11954            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11955
11956            assert!(left_dock.read(cx).is_open());
11957            assert!(right_dock.read(cx).is_open());
11958        });
11959
11960        workspace.update_in(cx, |workspace, window, cx| {
11961            // Toggle all docks - should close both
11962            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11963
11964            let left_dock = workspace.dock_at_position(DockPosition::Left);
11965            let right_dock = workspace.dock_at_position(DockPosition::Right);
11966            assert!(!left_dock.read(cx).is_open());
11967            assert!(!right_dock.read(cx).is_open());
11968        });
11969
11970        workspace.update_in(cx, |workspace, window, cx| {
11971            // Toggle again - should reopen both
11972            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11973
11974            let left_dock = workspace.dock_at_position(DockPosition::Left);
11975            let right_dock = workspace.dock_at_position(DockPosition::Right);
11976            assert!(left_dock.read(cx).is_open());
11977            assert!(right_dock.read(cx).is_open());
11978        });
11979    }
11980
11981    #[gpui::test]
11982    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11983        init_test(cx);
11984        let fs = FakeFs::new(cx.executor());
11985
11986        let project = Project::test(fs, [], cx).await;
11987        let (workspace, cx) =
11988            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11989        workspace.update_in(cx, |workspace, window, cx| {
11990            // Open two docks
11991            let left_dock = workspace.dock_at_position(DockPosition::Left);
11992            let right_dock = workspace.dock_at_position(DockPosition::Right);
11993
11994            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11995            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11996
11997            assert!(left_dock.read(cx).is_open());
11998            assert!(right_dock.read(cx).is_open());
11999        });
12000
12001        workspace.update_in(cx, |workspace, window, cx| {
12002            // Close them manually
12003            workspace.toggle_dock(DockPosition::Left, window, cx);
12004            workspace.toggle_dock(DockPosition::Right, window, cx);
12005
12006            let left_dock = workspace.dock_at_position(DockPosition::Left);
12007            let right_dock = workspace.dock_at_position(DockPosition::Right);
12008            assert!(!left_dock.read(cx).is_open());
12009            assert!(!right_dock.read(cx).is_open());
12010        });
12011
12012        workspace.update_in(cx, |workspace, window, cx| {
12013            // Toggle all docks - only last closed (right dock) should reopen
12014            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12015
12016            let left_dock = workspace.dock_at_position(DockPosition::Left);
12017            let right_dock = workspace.dock_at_position(DockPosition::Right);
12018            assert!(!left_dock.read(cx).is_open());
12019            assert!(right_dock.read(cx).is_open());
12020        });
12021    }
12022
12023    #[gpui::test]
12024    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
12025        init_test(cx);
12026        let fs = FakeFs::new(cx.executor());
12027        let project = Project::test(fs, [], cx).await;
12028        let (multi_workspace, cx) =
12029            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12030        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12031
12032        // Open two docks (left and right) with one panel each
12033        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12034            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12035            workspace.add_panel(left_panel.clone(), window, cx);
12036
12037            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12038            workspace.add_panel(right_panel.clone(), window, cx);
12039
12040            workspace.toggle_dock(DockPosition::Left, window, cx);
12041            workspace.toggle_dock(DockPosition::Right, window, cx);
12042
12043            // Verify initial state
12044            assert!(
12045                workspace.left_dock().read(cx).is_open(),
12046                "Left dock should be open"
12047            );
12048            assert_eq!(
12049                workspace
12050                    .left_dock()
12051                    .read(cx)
12052                    .visible_panel()
12053                    .unwrap()
12054                    .panel_id(),
12055                left_panel.panel_id(),
12056                "Left panel should be visible in left dock"
12057            );
12058            assert!(
12059                workspace.right_dock().read(cx).is_open(),
12060                "Right dock should be open"
12061            );
12062            assert_eq!(
12063                workspace
12064                    .right_dock()
12065                    .read(cx)
12066                    .visible_panel()
12067                    .unwrap()
12068                    .panel_id(),
12069                right_panel.panel_id(),
12070                "Right panel should be visible in right dock"
12071            );
12072            assert!(
12073                !workspace.bottom_dock().read(cx).is_open(),
12074                "Bottom dock should be closed"
12075            );
12076
12077            (left_panel, right_panel)
12078        });
12079
12080        // Focus the left panel and move it to the next position (bottom dock)
12081        workspace.update_in(cx, |workspace, window, cx| {
12082            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12083            assert!(
12084                left_panel.read(cx).focus_handle(cx).is_focused(window),
12085                "Left panel should be focused"
12086            );
12087        });
12088
12089        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12090
12091        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12092        workspace.update(cx, |workspace, cx| {
12093            assert!(
12094                !workspace.left_dock().read(cx).is_open(),
12095                "Left dock should be closed"
12096            );
12097            assert!(
12098                workspace.bottom_dock().read(cx).is_open(),
12099                "Bottom dock should now be open"
12100            );
12101            assert_eq!(
12102                left_panel.read(cx).position,
12103                DockPosition::Bottom,
12104                "Left panel should now be in the bottom dock"
12105            );
12106            assert_eq!(
12107                workspace
12108                    .bottom_dock()
12109                    .read(cx)
12110                    .visible_panel()
12111                    .unwrap()
12112                    .panel_id(),
12113                left_panel.panel_id(),
12114                "Left panel should be the visible panel in the bottom dock"
12115            );
12116        });
12117
12118        // Toggle all docks off
12119        workspace.update_in(cx, |workspace, window, cx| {
12120            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12121            assert!(
12122                !workspace.left_dock().read(cx).is_open(),
12123                "Left dock should be closed"
12124            );
12125            assert!(
12126                !workspace.right_dock().read(cx).is_open(),
12127                "Right dock should be closed"
12128            );
12129            assert!(
12130                !workspace.bottom_dock().read(cx).is_open(),
12131                "Bottom dock should be closed"
12132            );
12133        });
12134
12135        // Toggle all docks back on and verify positions are restored
12136        workspace.update_in(cx, |workspace, window, cx| {
12137            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12138            assert!(
12139                !workspace.left_dock().read(cx).is_open(),
12140                "Left dock should remain closed"
12141            );
12142            assert!(
12143                workspace.right_dock().read(cx).is_open(),
12144                "Right dock should remain open"
12145            );
12146            assert!(
12147                workspace.bottom_dock().read(cx).is_open(),
12148                "Bottom dock should remain open"
12149            );
12150            assert_eq!(
12151                left_panel.read(cx).position,
12152                DockPosition::Bottom,
12153                "Left panel should remain in the bottom dock"
12154            );
12155            assert_eq!(
12156                right_panel.read(cx).position,
12157                DockPosition::Right,
12158                "Right panel should remain in the right dock"
12159            );
12160            assert_eq!(
12161                workspace
12162                    .bottom_dock()
12163                    .read(cx)
12164                    .visible_panel()
12165                    .unwrap()
12166                    .panel_id(),
12167                left_panel.panel_id(),
12168                "Left panel should be the visible panel in the right dock"
12169            );
12170        });
12171    }
12172
12173    #[gpui::test]
12174    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12175        init_test(cx);
12176
12177        let fs = FakeFs::new(cx.executor());
12178
12179        let project = Project::test(fs, None, cx).await;
12180        let (workspace, cx) =
12181            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12182
12183        // Let's arrange the panes like this:
12184        //
12185        // +-----------------------+
12186        // |         top           |
12187        // +------+--------+-------+
12188        // | left | center | right |
12189        // +------+--------+-------+
12190        // |        bottom         |
12191        // +-----------------------+
12192
12193        let top_item = cx.new(|cx| {
12194            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12195        });
12196        let bottom_item = cx.new(|cx| {
12197            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12198        });
12199        let left_item = cx.new(|cx| {
12200            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12201        });
12202        let right_item = cx.new(|cx| {
12203            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12204        });
12205        let center_item = cx.new(|cx| {
12206            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12207        });
12208
12209        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12210            let top_pane_id = workspace.active_pane().entity_id();
12211            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12212            workspace.split_pane(
12213                workspace.active_pane().clone(),
12214                SplitDirection::Down,
12215                window,
12216                cx,
12217            );
12218            top_pane_id
12219        });
12220        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12221            let bottom_pane_id = workspace.active_pane().entity_id();
12222            workspace.add_item_to_active_pane(
12223                Box::new(bottom_item.clone()),
12224                None,
12225                false,
12226                window,
12227                cx,
12228            );
12229            workspace.split_pane(
12230                workspace.active_pane().clone(),
12231                SplitDirection::Up,
12232                window,
12233                cx,
12234            );
12235            bottom_pane_id
12236        });
12237        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12238            let left_pane_id = workspace.active_pane().entity_id();
12239            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12240            workspace.split_pane(
12241                workspace.active_pane().clone(),
12242                SplitDirection::Right,
12243                window,
12244                cx,
12245            );
12246            left_pane_id
12247        });
12248        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12249            let right_pane_id = workspace.active_pane().entity_id();
12250            workspace.add_item_to_active_pane(
12251                Box::new(right_item.clone()),
12252                None,
12253                false,
12254                window,
12255                cx,
12256            );
12257            workspace.split_pane(
12258                workspace.active_pane().clone(),
12259                SplitDirection::Left,
12260                window,
12261                cx,
12262            );
12263            right_pane_id
12264        });
12265        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12266            let center_pane_id = workspace.active_pane().entity_id();
12267            workspace.add_item_to_active_pane(
12268                Box::new(center_item.clone()),
12269                None,
12270                false,
12271                window,
12272                cx,
12273            );
12274            center_pane_id
12275        });
12276        cx.executor().run_until_parked();
12277
12278        workspace.update_in(cx, |workspace, window, cx| {
12279            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12280
12281            // Join into next from center pane into right
12282            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12283        });
12284
12285        workspace.update_in(cx, |workspace, window, cx| {
12286            let active_pane = workspace.active_pane();
12287            assert_eq!(right_pane_id, active_pane.entity_id());
12288            assert_eq!(2, active_pane.read(cx).items_len());
12289            let item_ids_in_pane =
12290                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12291            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12292            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12293
12294            // Join into next from right pane into bottom
12295            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12296        });
12297
12298        workspace.update_in(cx, |workspace, window, cx| {
12299            let active_pane = workspace.active_pane();
12300            assert_eq!(bottom_pane_id, active_pane.entity_id());
12301            assert_eq!(3, active_pane.read(cx).items_len());
12302            let item_ids_in_pane =
12303                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12304            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12305            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12306            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12307
12308            // Join into next from bottom pane into left
12309            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12310        });
12311
12312        workspace.update_in(cx, |workspace, window, cx| {
12313            let active_pane = workspace.active_pane();
12314            assert_eq!(left_pane_id, active_pane.entity_id());
12315            assert_eq!(4, active_pane.read(cx).items_len());
12316            let item_ids_in_pane =
12317                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12318            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12319            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12320            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12321            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12322
12323            // Join into next from left pane into top
12324            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12325        });
12326
12327        workspace.update_in(cx, |workspace, window, cx| {
12328            let active_pane = workspace.active_pane();
12329            assert_eq!(top_pane_id, active_pane.entity_id());
12330            assert_eq!(5, active_pane.read(cx).items_len());
12331            let item_ids_in_pane =
12332                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12333            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12334            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12335            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12336            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12337            assert!(item_ids_in_pane.contains(&top_item.item_id()));
12338
12339            // Single pane left: no-op
12340            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12341        });
12342
12343        workspace.update(cx, |workspace, _cx| {
12344            let active_pane = workspace.active_pane();
12345            assert_eq!(top_pane_id, active_pane.entity_id());
12346        });
12347    }
12348
12349    fn add_an_item_to_active_pane(
12350        cx: &mut VisualTestContext,
12351        workspace: &Entity<Workspace>,
12352        item_id: u64,
12353    ) -> Entity<TestItem> {
12354        let item = cx.new(|cx| {
12355            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12356                item_id,
12357                "item{item_id}.txt",
12358                cx,
12359            )])
12360        });
12361        workspace.update_in(cx, |workspace, window, cx| {
12362            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12363        });
12364        item
12365    }
12366
12367    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12368        workspace.update_in(cx, |workspace, window, cx| {
12369            workspace.split_pane(
12370                workspace.active_pane().clone(),
12371                SplitDirection::Right,
12372                window,
12373                cx,
12374            )
12375        })
12376    }
12377
12378    #[gpui::test]
12379    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12380        init_test(cx);
12381        let fs = FakeFs::new(cx.executor());
12382        let project = Project::test(fs, None, cx).await;
12383        let (workspace, cx) =
12384            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12385
12386        add_an_item_to_active_pane(cx, &workspace, 1);
12387        split_pane(cx, &workspace);
12388        add_an_item_to_active_pane(cx, &workspace, 2);
12389        split_pane(cx, &workspace); // empty pane
12390        split_pane(cx, &workspace);
12391        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12392
12393        cx.executor().run_until_parked();
12394
12395        workspace.update(cx, |workspace, cx| {
12396            let num_panes = workspace.panes().len();
12397            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12398            let active_item = workspace
12399                .active_pane()
12400                .read(cx)
12401                .active_item()
12402                .expect("item is in focus");
12403
12404            assert_eq!(num_panes, 4);
12405            assert_eq!(num_items_in_current_pane, 1);
12406            assert_eq!(active_item.item_id(), last_item.item_id());
12407        });
12408
12409        workspace.update_in(cx, |workspace, window, cx| {
12410            workspace.join_all_panes(window, cx);
12411        });
12412
12413        workspace.update(cx, |workspace, cx| {
12414            let num_panes = workspace.panes().len();
12415            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12416            let active_item = workspace
12417                .active_pane()
12418                .read(cx)
12419                .active_item()
12420                .expect("item is in focus");
12421
12422            assert_eq!(num_panes, 1);
12423            assert_eq!(num_items_in_current_pane, 3);
12424            assert_eq!(active_item.item_id(), last_item.item_id());
12425        });
12426    }
12427
12428    #[gpui::test]
12429    async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12430        init_test(cx);
12431        let fs = FakeFs::new(cx.executor());
12432
12433        let project = Project::test(fs, [], cx).await;
12434        let (multi_workspace, cx) =
12435            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12436        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12437
12438        workspace.update(cx, |workspace, _cx| {
12439            workspace.bounds.size.width = px(800.);
12440        });
12441
12442        workspace.update_in(cx, |workspace, window, cx| {
12443            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12444            workspace.add_panel(panel, window, cx);
12445            workspace.toggle_dock(DockPosition::Right, window, cx);
12446        });
12447
12448        let (panel, resized_width, ratio_basis_width) =
12449            workspace.update_in(cx, |workspace, window, cx| {
12450                let item = cx.new(|cx| {
12451                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12452                });
12453                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12454
12455                let dock = workspace.right_dock().read(cx);
12456                let workspace_width = workspace.bounds.size.width;
12457                let initial_width = workspace
12458                    .dock_size(&dock, window, cx)
12459                    .expect("flexible dock should have an initial width");
12460
12461                assert_eq!(initial_width, workspace_width / 2.);
12462
12463                workspace.resize_right_dock(px(300.), window, cx);
12464
12465                let dock = workspace.right_dock().read(cx);
12466                let resized_width = workspace
12467                    .dock_size(&dock, window, cx)
12468                    .expect("flexible dock should keep its resized width");
12469
12470                assert_eq!(resized_width, px(300.));
12471
12472                let panel = workspace
12473                    .right_dock()
12474                    .read(cx)
12475                    .visible_panel()
12476                    .expect("flexible dock should have a visible panel")
12477                    .panel_id();
12478
12479                (panel, resized_width, workspace_width)
12480            });
12481
12482        workspace.update_in(cx, |workspace, window, cx| {
12483            workspace.toggle_dock(DockPosition::Right, window, cx);
12484            workspace.toggle_dock(DockPosition::Right, window, cx);
12485
12486            let dock = workspace.right_dock().read(cx);
12487            let reopened_width = workspace
12488                .dock_size(&dock, window, cx)
12489                .expect("flexible dock should restore when reopened");
12490
12491            assert_eq!(reopened_width, resized_width);
12492
12493            let right_dock = workspace.right_dock().read(cx);
12494            let flexible_panel = right_dock
12495                .visible_panel()
12496                .expect("flexible dock should still have a visible panel");
12497            assert_eq!(flexible_panel.panel_id(), panel);
12498            assert_eq!(
12499                right_dock
12500                    .stored_panel_size_state(flexible_panel.as_ref())
12501                    .and_then(|size_state| size_state.flex),
12502                Some(
12503                    resized_width.to_f64() as f32
12504                        / (workspace.bounds.size.width - resized_width).to_f64() as f32
12505                )
12506            );
12507        });
12508
12509        workspace.update_in(cx, |workspace, window, cx| {
12510            workspace.split_pane(
12511                workspace.active_pane().clone(),
12512                SplitDirection::Right,
12513                window,
12514                cx,
12515            );
12516
12517            let dock = workspace.right_dock().read(cx);
12518            let split_width = workspace
12519                .dock_size(&dock, window, cx)
12520                .expect("flexible dock should keep its user-resized proportion");
12521
12522            assert_eq!(split_width, px(300.));
12523
12524            workspace.bounds.size.width = px(1600.);
12525
12526            let dock = workspace.right_dock().read(cx);
12527            let resized_window_width = workspace
12528                .dock_size(&dock, window, cx)
12529                .expect("flexible dock should preserve proportional size on window resize");
12530
12531            assert_eq!(
12532                resized_window_width,
12533                workspace.bounds.size.width
12534                    * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12535            );
12536        });
12537    }
12538
12539    #[gpui::test]
12540    async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12541        init_test(cx);
12542        let fs = FakeFs::new(cx.executor());
12543
12544        // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12545        {
12546            let project = Project::test(fs.clone(), [], cx).await;
12547            let (multi_workspace, cx) =
12548                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12549            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12550
12551            workspace.update(cx, |workspace, _cx| {
12552                workspace.set_random_database_id();
12553                workspace.bounds.size.width = px(800.);
12554            });
12555
12556            let panel = workspace.update_in(cx, |workspace, window, cx| {
12557                let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12558                workspace.add_panel(panel.clone(), window, cx);
12559                workspace.toggle_dock(DockPosition::Left, window, cx);
12560                panel
12561            });
12562
12563            workspace.update_in(cx, |workspace, window, cx| {
12564                workspace.resize_left_dock(px(350.), window, cx);
12565            });
12566
12567            cx.run_until_parked();
12568
12569            let persisted = workspace.read_with(cx, |workspace, cx| {
12570                workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12571            });
12572            assert_eq!(
12573                persisted.and_then(|s| s.size),
12574                Some(px(350.)),
12575                "fixed-width panel size should be persisted to KVP"
12576            );
12577
12578            // Remove the panel and re-add a fresh instance with the same key.
12579            // The new instance should have its size state restored from KVP.
12580            workspace.update_in(cx, |workspace, window, cx| {
12581                workspace.remove_panel(&panel, window, cx);
12582            });
12583
12584            workspace.update_in(cx, |workspace, window, cx| {
12585                let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12586                workspace.add_panel(new_panel, window, cx);
12587
12588                let left_dock = workspace.left_dock().read(cx);
12589                let size_state = left_dock
12590                    .panel::<TestPanel>()
12591                    .and_then(|p| left_dock.stored_panel_size_state(&p));
12592                assert_eq!(
12593                    size_state.and_then(|s| s.size),
12594                    Some(px(350.)),
12595                    "re-added fixed-width panel should restore persisted size from KVP"
12596                );
12597            });
12598        }
12599
12600        // Flexible panel: both pixel size and ratio are persisted and restored.
12601        {
12602            let project = Project::test(fs.clone(), [], cx).await;
12603            let (multi_workspace, cx) =
12604                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12605            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12606
12607            workspace.update(cx, |workspace, _cx| {
12608                workspace.set_random_database_id();
12609                workspace.bounds.size.width = px(800.);
12610            });
12611
12612            let panel = workspace.update_in(cx, |workspace, window, cx| {
12613                let item = cx.new(|cx| {
12614                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12615                });
12616                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12617
12618                let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12619                workspace.add_panel(panel.clone(), window, cx);
12620                workspace.toggle_dock(DockPosition::Right, window, cx);
12621                panel
12622            });
12623
12624            workspace.update_in(cx, |workspace, window, cx| {
12625                workspace.resize_right_dock(px(300.), window, cx);
12626            });
12627
12628            cx.run_until_parked();
12629
12630            let persisted = workspace
12631                .read_with(cx, |workspace, cx| {
12632                    workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12633                })
12634                .expect("flexible panel state should be persisted to KVP");
12635            assert_eq!(
12636                persisted.size, None,
12637                "flexible panel should not persist a redundant pixel size"
12638            );
12639            let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12640
12641            // Remove the panel and re-add: both size and ratio should be restored.
12642            workspace.update_in(cx, |workspace, window, cx| {
12643                workspace.remove_panel(&panel, window, cx);
12644            });
12645
12646            workspace.update_in(cx, |workspace, window, cx| {
12647                let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12648                workspace.add_panel(new_panel, window, cx);
12649
12650                let right_dock = workspace.right_dock().read(cx);
12651                let size_state = right_dock
12652                    .panel::<TestPanel>()
12653                    .and_then(|p| right_dock.stored_panel_size_state(&p))
12654                    .expect("re-added flexible panel should have restored size state from KVP");
12655                assert_eq!(
12656                    size_state.size, None,
12657                    "re-added flexible panel should not have a persisted pixel size"
12658                );
12659                assert_eq!(
12660                    size_state.flex,
12661                    Some(original_ratio),
12662                    "re-added flexible panel should restore persisted flex"
12663                );
12664            });
12665        }
12666    }
12667
12668    #[gpui::test]
12669    async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12670        init_test(cx);
12671        let fs = FakeFs::new(cx.executor());
12672
12673        let project = Project::test(fs, [], cx).await;
12674        let (multi_workspace, cx) =
12675            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12676        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12677
12678        workspace.update(cx, |workspace, _cx| {
12679            workspace.bounds.size.width = px(900.);
12680        });
12681
12682        // Step 1: Add a tab to the center pane then open a flexible panel in the left
12683        // dock. With one full-width center pane the default ratio is 0.5, so the panel
12684        // and the center pane each take half the workspace width.
12685        workspace.update_in(cx, |workspace, window, cx| {
12686            let item = cx.new(|cx| {
12687                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12688            });
12689            workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12690
12691            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12692            workspace.add_panel(panel, window, cx);
12693            workspace.toggle_dock(DockPosition::Left, window, cx);
12694
12695            let left_dock = workspace.left_dock().read(cx);
12696            let left_width = workspace
12697                .dock_size(&left_dock, window, cx)
12698                .expect("left dock should have an active panel");
12699
12700            assert_eq!(
12701                left_width,
12702                workspace.bounds.size.width / 2.,
12703                "flexible left panel should split evenly with the center pane"
12704            );
12705        });
12706
12707        // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12708        // change horizontal width fractions, so the flexible panel stays at the same
12709        // width as each half of the split.
12710        workspace.update_in(cx, |workspace, window, cx| {
12711            workspace.split_pane(
12712                workspace.active_pane().clone(),
12713                SplitDirection::Down,
12714                window,
12715                cx,
12716            );
12717
12718            let left_dock = workspace.left_dock().read(cx);
12719            let left_width = workspace
12720                .dock_size(&left_dock, window, cx)
12721                .expect("left dock should still have an active panel after vertical split");
12722
12723            assert_eq!(
12724                left_width,
12725                workspace.bounds.size.width / 2.,
12726                "flexible left panel width should match each vertically-split pane"
12727            );
12728        });
12729
12730        // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12731        // size reduces the available width, so the flexible left panel and the center
12732        // panes all shrink proportionally to accommodate it.
12733        workspace.update_in(cx, |workspace, window, cx| {
12734            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12735            workspace.add_panel(panel, window, cx);
12736            workspace.toggle_dock(DockPosition::Right, window, cx);
12737
12738            let right_dock = workspace.right_dock().read(cx);
12739            let right_width = workspace
12740                .dock_size(&right_dock, window, cx)
12741                .expect("right dock should have an active panel");
12742
12743            let left_dock = workspace.left_dock().read(cx);
12744            let left_width = workspace
12745                .dock_size(&left_dock, window, cx)
12746                .expect("left dock should still have an active panel");
12747
12748            let available_width = workspace.bounds.size.width - right_width;
12749            assert_eq!(
12750                left_width,
12751                available_width / 2.,
12752                "flexible left panel should shrink proportionally as the right dock takes space"
12753            );
12754        });
12755
12756        // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12757        // flex sizing and the workspace width is divided among left-flex, center
12758        // (implicit flex 1.0), and right-flex.
12759        workspace.update_in(cx, |workspace, window, cx| {
12760            let right_dock = workspace.right_dock().clone();
12761            let right_panel = right_dock
12762                .read(cx)
12763                .visible_panel()
12764                .expect("right dock should have a visible panel")
12765                .clone();
12766            workspace.toggle_dock_panel_flexible_size(
12767                &right_dock,
12768                right_panel.as_ref(),
12769                window,
12770                cx,
12771            );
12772
12773            let right_dock = right_dock.read(cx);
12774            let right_panel = right_dock
12775                .visible_panel()
12776                .expect("right dock should still have a visible panel");
12777            assert!(
12778                right_panel.has_flexible_size(window, cx),
12779                "right panel should now be flexible"
12780            );
12781
12782            let right_size_state = right_dock
12783                .stored_panel_size_state(right_panel.as_ref())
12784                .expect("right panel should have a stored size state after toggling");
12785            let right_flex = right_size_state
12786                .flex
12787                .expect("right panel should have a flex value after toggling");
12788
12789            let left_dock = workspace.left_dock().read(cx);
12790            let left_width = workspace
12791                .dock_size(&left_dock, window, cx)
12792                .expect("left dock should still have an active panel");
12793            let right_width = workspace
12794                .dock_size(&right_dock, window, cx)
12795                .expect("right dock should still have an active panel");
12796
12797            let left_flex = workspace
12798                .default_dock_flex(DockPosition::Left)
12799                .expect("left dock should have a default flex");
12800
12801            let total_flex = left_flex + 1.0 + right_flex;
12802            let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12803            let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12804            assert_eq!(
12805                left_width, expected_left,
12806                "flexible left panel should share workspace width via flex ratios"
12807            );
12808            assert_eq!(
12809                right_width, expected_right,
12810                "flexible right panel should share workspace width via flex ratios"
12811            );
12812        });
12813    }
12814
12815    struct TestModal(FocusHandle);
12816
12817    impl TestModal {
12818        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12819            Self(cx.focus_handle())
12820        }
12821    }
12822
12823    impl EventEmitter<DismissEvent> for TestModal {}
12824
12825    impl Focusable for TestModal {
12826        fn focus_handle(&self, _cx: &App) -> FocusHandle {
12827            self.0.clone()
12828        }
12829    }
12830
12831    impl ModalView for TestModal {}
12832
12833    impl Render for TestModal {
12834        fn render(
12835            &mut self,
12836            _window: &mut Window,
12837            _cx: &mut Context<TestModal>,
12838        ) -> impl IntoElement {
12839            div().track_focus(&self.0)
12840        }
12841    }
12842
12843    #[gpui::test]
12844    async fn test_panels(cx: &mut gpui::TestAppContext) {
12845        init_test(cx);
12846        let fs = FakeFs::new(cx.executor());
12847
12848        let project = Project::test(fs, [], cx).await;
12849        let (multi_workspace, cx) =
12850            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12851        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12852
12853        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12854            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12855            workspace.add_panel(panel_1.clone(), window, cx);
12856            workspace.toggle_dock(DockPosition::Left, window, cx);
12857            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12858            workspace.add_panel(panel_2.clone(), window, cx);
12859            workspace.toggle_dock(DockPosition::Right, window, cx);
12860
12861            let left_dock = workspace.left_dock();
12862            assert_eq!(
12863                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12864                panel_1.panel_id()
12865            );
12866            assert_eq!(
12867                workspace.dock_size(&left_dock.read(cx), window, cx),
12868                Some(px(300.))
12869            );
12870
12871            workspace.resize_left_dock(px(1337.), window, cx);
12872            assert_eq!(
12873                workspace
12874                    .right_dock()
12875                    .read(cx)
12876                    .visible_panel()
12877                    .unwrap()
12878                    .panel_id(),
12879                panel_2.panel_id(),
12880            );
12881
12882            (panel_1, panel_2)
12883        });
12884
12885        // Move panel_1 to the right
12886        panel_1.update_in(cx, |panel_1, window, cx| {
12887            panel_1.set_position(DockPosition::Right, window, cx)
12888        });
12889
12890        workspace.update_in(cx, |workspace, window, cx| {
12891            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12892            // Since it was the only panel on the left, the left dock should now be closed.
12893            assert!(!workspace.left_dock().read(cx).is_open());
12894            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12895            let right_dock = workspace.right_dock();
12896            assert_eq!(
12897                right_dock.read(cx).visible_panel().unwrap().panel_id(),
12898                panel_1.panel_id()
12899            );
12900            assert_eq!(
12901                right_dock
12902                    .read(cx)
12903                    .active_panel_size()
12904                    .unwrap()
12905                    .size
12906                    .unwrap(),
12907                px(1337.)
12908            );
12909
12910            // Now we move panel_2 to the left
12911            panel_2.set_position(DockPosition::Left, window, cx);
12912        });
12913
12914        workspace.update(cx, |workspace, cx| {
12915            // Since panel_2 was not visible on the right, we don't open the left dock.
12916            assert!(!workspace.left_dock().read(cx).is_open());
12917            // And the right dock is unaffected in its displaying of panel_1
12918            assert!(workspace.right_dock().read(cx).is_open());
12919            assert_eq!(
12920                workspace
12921                    .right_dock()
12922                    .read(cx)
12923                    .visible_panel()
12924                    .unwrap()
12925                    .panel_id(),
12926                panel_1.panel_id(),
12927            );
12928        });
12929
12930        // Move panel_1 back to the left
12931        panel_1.update_in(cx, |panel_1, window, cx| {
12932            panel_1.set_position(DockPosition::Left, window, cx)
12933        });
12934
12935        workspace.update_in(cx, |workspace, window, cx| {
12936            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12937            let left_dock = workspace.left_dock();
12938            assert!(left_dock.read(cx).is_open());
12939            assert_eq!(
12940                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12941                panel_1.panel_id()
12942            );
12943            assert_eq!(
12944                workspace.dock_size(&left_dock.read(cx), window, cx),
12945                Some(px(1337.))
12946            );
12947            // And the right dock should be closed as it no longer has any panels.
12948            assert!(!workspace.right_dock().read(cx).is_open());
12949
12950            // Now we move panel_1 to the bottom
12951            panel_1.set_position(DockPosition::Bottom, window, cx);
12952        });
12953
12954        workspace.update_in(cx, |workspace, window, cx| {
12955            // Since panel_1 was visible on the left, we close the left dock.
12956            assert!(!workspace.left_dock().read(cx).is_open());
12957            // The bottom dock is sized based on the panel's default size,
12958            // since the panel orientation changed from vertical to horizontal.
12959            let bottom_dock = workspace.bottom_dock();
12960            assert_eq!(
12961                workspace.dock_size(&bottom_dock.read(cx), window, cx),
12962                Some(px(300.))
12963            );
12964            // Close bottom dock and move panel_1 back to the left.
12965            bottom_dock.update(cx, |bottom_dock, cx| {
12966                bottom_dock.set_open(false, window, cx)
12967            });
12968            panel_1.set_position(DockPosition::Left, window, cx);
12969        });
12970
12971        // Emit activated event on panel 1
12972        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12973
12974        // Now the left dock is open and panel_1 is active and focused.
12975        workspace.update_in(cx, |workspace, window, cx| {
12976            let left_dock = workspace.left_dock();
12977            assert!(left_dock.read(cx).is_open());
12978            assert_eq!(
12979                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12980                panel_1.panel_id(),
12981            );
12982            assert!(panel_1.focus_handle(cx).is_focused(window));
12983        });
12984
12985        // Emit closed event on panel 2, which is not active
12986        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12987
12988        // Wo don't close the left dock, because panel_2 wasn't the active panel
12989        workspace.update(cx, |workspace, cx| {
12990            let left_dock = workspace.left_dock();
12991            assert!(left_dock.read(cx).is_open());
12992            assert_eq!(
12993                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12994                panel_1.panel_id(),
12995            );
12996        });
12997
12998        // Emitting a ZoomIn event shows the panel as zoomed.
12999        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
13000        workspace.read_with(cx, |workspace, _| {
13001            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13002            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
13003        });
13004
13005        // Move panel to another dock while it is zoomed
13006        panel_1.update_in(cx, |panel, window, cx| {
13007            panel.set_position(DockPosition::Right, window, cx)
13008        });
13009        workspace.read_with(cx, |workspace, _| {
13010            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13011
13012            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13013        });
13014
13015        // This is a helper for getting a:
13016        // - valid focus on an element,
13017        // - that isn't a part of the panes and panels system of the Workspace,
13018        // - and doesn't trigger the 'on_focus_lost' API.
13019        let focus_other_view = {
13020            let workspace = workspace.clone();
13021            move |cx: &mut VisualTestContext| {
13022                workspace.update_in(cx, |workspace, window, cx| {
13023                    if workspace.active_modal::<TestModal>(cx).is_some() {
13024                        workspace.toggle_modal(window, cx, TestModal::new);
13025                        workspace.toggle_modal(window, cx, TestModal::new);
13026                    } else {
13027                        workspace.toggle_modal(window, cx, TestModal::new);
13028                    }
13029                })
13030            }
13031        };
13032
13033        // If focus is transferred to another view that's not a panel or another pane, we still show
13034        // the panel as zoomed.
13035        focus_other_view(cx);
13036        workspace.read_with(cx, |workspace, _| {
13037            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13038            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13039        });
13040
13041        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13042        workspace.update_in(cx, |_workspace, window, cx| {
13043            cx.focus_self(window);
13044        });
13045        workspace.read_with(cx, |workspace, _| {
13046            assert_eq!(workspace.zoomed, None);
13047            assert_eq!(workspace.zoomed_position, None);
13048        });
13049
13050        // If focus is transferred again to another view that's not a panel or a pane, we won't
13051        // show the panel as zoomed because it wasn't zoomed before.
13052        focus_other_view(cx);
13053        workspace.read_with(cx, |workspace, _| {
13054            assert_eq!(workspace.zoomed, None);
13055            assert_eq!(workspace.zoomed_position, None);
13056        });
13057
13058        // When the panel is activated, it is zoomed again.
13059        cx.dispatch_action(ToggleRightDock);
13060        workspace.read_with(cx, |workspace, _| {
13061            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13062            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13063        });
13064
13065        // Emitting a ZoomOut event unzooms the panel.
13066        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13067        workspace.read_with(cx, |workspace, _| {
13068            assert_eq!(workspace.zoomed, None);
13069            assert_eq!(workspace.zoomed_position, None);
13070        });
13071
13072        // Emit closed event on panel 1, which is active
13073        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13074
13075        // Now the left dock is closed, because panel_1 was the active panel
13076        workspace.update(cx, |workspace, cx| {
13077            let right_dock = workspace.right_dock();
13078            assert!(!right_dock.read(cx).is_open());
13079        });
13080    }
13081
13082    #[gpui::test]
13083    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13084        init_test(cx);
13085
13086        let fs = FakeFs::new(cx.background_executor.clone());
13087        let project = Project::test(fs, [], cx).await;
13088        let (workspace, cx) =
13089            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13090        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13091
13092        let dirty_regular_buffer = cx.new(|cx| {
13093            TestItem::new(cx)
13094                .with_dirty(true)
13095                .with_label("1.txt")
13096                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13097        });
13098        let dirty_regular_buffer_2 = cx.new(|cx| {
13099            TestItem::new(cx)
13100                .with_dirty(true)
13101                .with_label("2.txt")
13102                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13103        });
13104        let dirty_multi_buffer_with_both = cx.new(|cx| {
13105            TestItem::new(cx)
13106                .with_dirty(true)
13107                .with_buffer_kind(ItemBufferKind::Multibuffer)
13108                .with_label("Fake Project Search")
13109                .with_project_items(&[
13110                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13111                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13112                ])
13113        });
13114        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13115        workspace.update_in(cx, |workspace, window, cx| {
13116            workspace.add_item(
13117                pane.clone(),
13118                Box::new(dirty_regular_buffer.clone()),
13119                None,
13120                false,
13121                false,
13122                window,
13123                cx,
13124            );
13125            workspace.add_item(
13126                pane.clone(),
13127                Box::new(dirty_regular_buffer_2.clone()),
13128                None,
13129                false,
13130                false,
13131                window,
13132                cx,
13133            );
13134            workspace.add_item(
13135                pane.clone(),
13136                Box::new(dirty_multi_buffer_with_both.clone()),
13137                None,
13138                false,
13139                false,
13140                window,
13141                cx,
13142            );
13143        });
13144
13145        pane.update_in(cx, |pane, window, cx| {
13146            pane.activate_item(2, true, true, window, cx);
13147            assert_eq!(
13148                pane.active_item().unwrap().item_id(),
13149                multi_buffer_with_both_files_id,
13150                "Should select the multi buffer in the pane"
13151            );
13152        });
13153        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13154            pane.close_other_items(
13155                &CloseOtherItems {
13156                    save_intent: Some(SaveIntent::Save),
13157                    close_pinned: true,
13158                },
13159                None,
13160                window,
13161                cx,
13162            )
13163        });
13164        cx.background_executor.run_until_parked();
13165        assert!(!cx.has_pending_prompt());
13166        close_all_but_multi_buffer_task
13167            .await
13168            .expect("Closing all buffers but the multi buffer failed");
13169        pane.update(cx, |pane, cx| {
13170            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13171            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13172            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13173            assert_eq!(pane.items_len(), 1);
13174            assert_eq!(
13175                pane.active_item().unwrap().item_id(),
13176                multi_buffer_with_both_files_id,
13177                "Should have only the multi buffer left in the pane"
13178            );
13179            assert!(
13180                dirty_multi_buffer_with_both.read(cx).is_dirty,
13181                "The multi buffer containing the unsaved buffer should still be dirty"
13182            );
13183        });
13184
13185        dirty_regular_buffer.update(cx, |buffer, cx| {
13186            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13187        });
13188
13189        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13190            pane.close_active_item(
13191                &CloseActiveItem {
13192                    save_intent: Some(SaveIntent::Close),
13193                    close_pinned: false,
13194                },
13195                window,
13196                cx,
13197            )
13198        });
13199        cx.background_executor.run_until_parked();
13200        assert!(
13201            cx.has_pending_prompt(),
13202            "Dirty multi buffer should prompt a save dialog"
13203        );
13204        cx.simulate_prompt_answer("Save");
13205        cx.background_executor.run_until_parked();
13206        close_multi_buffer_task
13207            .await
13208            .expect("Closing the multi buffer failed");
13209        pane.update(cx, |pane, cx| {
13210            assert_eq!(
13211                dirty_multi_buffer_with_both.read(cx).save_count,
13212                1,
13213                "Multi buffer item should get be saved"
13214            );
13215            // Test impl does not save inner items, so we do not assert them
13216            assert_eq!(
13217                pane.items_len(),
13218                0,
13219                "No more items should be left in the pane"
13220            );
13221            assert!(pane.active_item().is_none());
13222        });
13223    }
13224
13225    #[gpui::test]
13226    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13227        cx: &mut TestAppContext,
13228    ) {
13229        init_test(cx);
13230
13231        let fs = FakeFs::new(cx.background_executor.clone());
13232        let project = Project::test(fs, [], cx).await;
13233        let (workspace, cx) =
13234            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13235        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13236
13237        let dirty_regular_buffer = cx.new(|cx| {
13238            TestItem::new(cx)
13239                .with_dirty(true)
13240                .with_label("1.txt")
13241                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13242        });
13243        let dirty_regular_buffer_2 = cx.new(|cx| {
13244            TestItem::new(cx)
13245                .with_dirty(true)
13246                .with_label("2.txt")
13247                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13248        });
13249        let clear_regular_buffer = cx.new(|cx| {
13250            TestItem::new(cx)
13251                .with_label("3.txt")
13252                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13253        });
13254
13255        let dirty_multi_buffer_with_both = cx.new(|cx| {
13256            TestItem::new(cx)
13257                .with_dirty(true)
13258                .with_buffer_kind(ItemBufferKind::Multibuffer)
13259                .with_label("Fake Project Search")
13260                .with_project_items(&[
13261                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13262                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13263                    clear_regular_buffer.read(cx).project_items[0].clone(),
13264                ])
13265        });
13266        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13267        workspace.update_in(cx, |workspace, window, cx| {
13268            workspace.add_item(
13269                pane.clone(),
13270                Box::new(dirty_regular_buffer.clone()),
13271                None,
13272                false,
13273                false,
13274                window,
13275                cx,
13276            );
13277            workspace.add_item(
13278                pane.clone(),
13279                Box::new(dirty_multi_buffer_with_both.clone()),
13280                None,
13281                false,
13282                false,
13283                window,
13284                cx,
13285            );
13286        });
13287
13288        pane.update_in(cx, |pane, window, cx| {
13289            pane.activate_item(1, true, true, window, cx);
13290            assert_eq!(
13291                pane.active_item().unwrap().item_id(),
13292                multi_buffer_with_both_files_id,
13293                "Should select the multi buffer in the pane"
13294            );
13295        });
13296        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13297            pane.close_active_item(
13298                &CloseActiveItem {
13299                    save_intent: None,
13300                    close_pinned: false,
13301                },
13302                window,
13303                cx,
13304            )
13305        });
13306        cx.background_executor.run_until_parked();
13307        assert!(
13308            cx.has_pending_prompt(),
13309            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13310        );
13311    }
13312
13313    /// Tests that when `close_on_file_delete` is enabled, files are automatically
13314    /// closed when they are deleted from disk.
13315    #[gpui::test]
13316    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13317        init_test(cx);
13318
13319        // Enable the close_on_disk_deletion setting
13320        cx.update_global(|store: &mut SettingsStore, cx| {
13321            store.update_user_settings(cx, |settings| {
13322                settings.workspace.close_on_file_delete = Some(true);
13323            });
13324        });
13325
13326        let fs = FakeFs::new(cx.background_executor.clone());
13327        let project = Project::test(fs, [], cx).await;
13328        let (workspace, cx) =
13329            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13330        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13331
13332        // Create a test item that simulates a file
13333        let item = cx.new(|cx| {
13334            TestItem::new(cx)
13335                .with_label("test.txt")
13336                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13337        });
13338
13339        // Add item to workspace
13340        workspace.update_in(cx, |workspace, window, cx| {
13341            workspace.add_item(
13342                pane.clone(),
13343                Box::new(item.clone()),
13344                None,
13345                false,
13346                false,
13347                window,
13348                cx,
13349            );
13350        });
13351
13352        // Verify the item is in the pane
13353        pane.read_with(cx, |pane, _| {
13354            assert_eq!(pane.items().count(), 1);
13355        });
13356
13357        // Simulate file deletion by setting the item's deleted state
13358        item.update(cx, |item, _| {
13359            item.set_has_deleted_file(true);
13360        });
13361
13362        // Emit UpdateTab event to trigger the close behavior
13363        cx.run_until_parked();
13364        item.update(cx, |_, cx| {
13365            cx.emit(ItemEvent::UpdateTab);
13366        });
13367
13368        // Allow the close operation to complete
13369        cx.run_until_parked();
13370
13371        // Verify the item was automatically closed
13372        pane.read_with(cx, |pane, _| {
13373            assert_eq!(
13374                pane.items().count(),
13375                0,
13376                "Item should be automatically closed when file is deleted"
13377            );
13378        });
13379    }
13380
13381    /// Tests that when `close_on_file_delete` is disabled (default), files remain
13382    /// open with a strikethrough when they are deleted from disk.
13383    #[gpui::test]
13384    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13385        init_test(cx);
13386
13387        // Ensure close_on_disk_deletion is disabled (default)
13388        cx.update_global(|store: &mut SettingsStore, cx| {
13389            store.update_user_settings(cx, |settings| {
13390                settings.workspace.close_on_file_delete = Some(false);
13391            });
13392        });
13393
13394        let fs = FakeFs::new(cx.background_executor.clone());
13395        let project = Project::test(fs, [], cx).await;
13396        let (workspace, cx) =
13397            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13398        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13399
13400        // Create a test item that simulates a file
13401        let item = cx.new(|cx| {
13402            TestItem::new(cx)
13403                .with_label("test.txt")
13404                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13405        });
13406
13407        // Add item to workspace
13408        workspace.update_in(cx, |workspace, window, cx| {
13409            workspace.add_item(
13410                pane.clone(),
13411                Box::new(item.clone()),
13412                None,
13413                false,
13414                false,
13415                window,
13416                cx,
13417            );
13418        });
13419
13420        // Verify the item is in the pane
13421        pane.read_with(cx, |pane, _| {
13422            assert_eq!(pane.items().count(), 1);
13423        });
13424
13425        // Simulate file deletion
13426        item.update(cx, |item, _| {
13427            item.set_has_deleted_file(true);
13428        });
13429
13430        // Emit UpdateTab event
13431        cx.run_until_parked();
13432        item.update(cx, |_, cx| {
13433            cx.emit(ItemEvent::UpdateTab);
13434        });
13435
13436        // Allow any potential close operation to complete
13437        cx.run_until_parked();
13438
13439        // Verify the item remains open (with strikethrough)
13440        pane.read_with(cx, |pane, _| {
13441            assert_eq!(
13442                pane.items().count(),
13443                1,
13444                "Item should remain open when close_on_disk_deletion is disabled"
13445            );
13446        });
13447
13448        // Verify the item shows as deleted
13449        item.read_with(cx, |item, _| {
13450            assert!(
13451                item.has_deleted_file,
13452                "Item should be marked as having deleted file"
13453            );
13454        });
13455    }
13456
13457    /// Tests that dirty files are not automatically closed when deleted from disk,
13458    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13459    /// unsaved changes without being prompted.
13460    #[gpui::test]
13461    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13462        init_test(cx);
13463
13464        // Enable the close_on_file_delete setting
13465        cx.update_global(|store: &mut SettingsStore, cx| {
13466            store.update_user_settings(cx, |settings| {
13467                settings.workspace.close_on_file_delete = Some(true);
13468            });
13469        });
13470
13471        let fs = FakeFs::new(cx.background_executor.clone());
13472        let project = Project::test(fs, [], cx).await;
13473        let (workspace, cx) =
13474            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13475        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13476
13477        // Create a dirty test item
13478        let item = cx.new(|cx| {
13479            TestItem::new(cx)
13480                .with_dirty(true)
13481                .with_label("test.txt")
13482                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13483        });
13484
13485        // Add item to workspace
13486        workspace.update_in(cx, |workspace, window, cx| {
13487            workspace.add_item(
13488                pane.clone(),
13489                Box::new(item.clone()),
13490                None,
13491                false,
13492                false,
13493                window,
13494                cx,
13495            );
13496        });
13497
13498        // Simulate file deletion
13499        item.update(cx, |item, _| {
13500            item.set_has_deleted_file(true);
13501        });
13502
13503        // Emit UpdateTab event to trigger the close behavior
13504        cx.run_until_parked();
13505        item.update(cx, |_, cx| {
13506            cx.emit(ItemEvent::UpdateTab);
13507        });
13508
13509        // Allow any potential close operation to complete
13510        cx.run_until_parked();
13511
13512        // Verify the item remains open (dirty files are not auto-closed)
13513        pane.read_with(cx, |pane, _| {
13514            assert_eq!(
13515                pane.items().count(),
13516                1,
13517                "Dirty items should not be automatically closed even when file is deleted"
13518            );
13519        });
13520
13521        // Verify the item is marked as deleted and still dirty
13522        item.read_with(cx, |item, _| {
13523            assert!(
13524                item.has_deleted_file,
13525                "Item should be marked as having deleted file"
13526            );
13527            assert!(item.is_dirty, "Item should still be dirty");
13528        });
13529    }
13530
13531    /// Tests that navigation history is cleaned up when files are auto-closed
13532    /// due to deletion from disk.
13533    #[gpui::test]
13534    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13535        init_test(cx);
13536
13537        // Enable the close_on_file_delete setting
13538        cx.update_global(|store: &mut SettingsStore, cx| {
13539            store.update_user_settings(cx, |settings| {
13540                settings.workspace.close_on_file_delete = Some(true);
13541            });
13542        });
13543
13544        let fs = FakeFs::new(cx.background_executor.clone());
13545        let project = Project::test(fs, [], cx).await;
13546        let (workspace, cx) =
13547            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13548        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13549
13550        // Create test items
13551        let item1 = cx.new(|cx| {
13552            TestItem::new(cx)
13553                .with_label("test1.txt")
13554                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13555        });
13556        let item1_id = item1.item_id();
13557
13558        let item2 = cx.new(|cx| {
13559            TestItem::new(cx)
13560                .with_label("test2.txt")
13561                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13562        });
13563
13564        // Add items to workspace
13565        workspace.update_in(cx, |workspace, window, cx| {
13566            workspace.add_item(
13567                pane.clone(),
13568                Box::new(item1.clone()),
13569                None,
13570                false,
13571                false,
13572                window,
13573                cx,
13574            );
13575            workspace.add_item(
13576                pane.clone(),
13577                Box::new(item2.clone()),
13578                None,
13579                false,
13580                false,
13581                window,
13582                cx,
13583            );
13584        });
13585
13586        // Activate item1 to ensure it gets navigation entries
13587        pane.update_in(cx, |pane, window, cx| {
13588            pane.activate_item(0, true, true, window, cx);
13589        });
13590
13591        // Switch to item2 and back to create navigation history
13592        pane.update_in(cx, |pane, window, cx| {
13593            pane.activate_item(1, true, true, window, cx);
13594        });
13595        cx.run_until_parked();
13596
13597        pane.update_in(cx, |pane, window, cx| {
13598            pane.activate_item(0, true, true, window, cx);
13599        });
13600        cx.run_until_parked();
13601
13602        // Simulate file deletion for item1
13603        item1.update(cx, |item, _| {
13604            item.set_has_deleted_file(true);
13605        });
13606
13607        // Emit UpdateTab event to trigger the close behavior
13608        item1.update(cx, |_, cx| {
13609            cx.emit(ItemEvent::UpdateTab);
13610        });
13611        cx.run_until_parked();
13612
13613        // Verify item1 was closed
13614        pane.read_with(cx, |pane, _| {
13615            assert_eq!(
13616                pane.items().count(),
13617                1,
13618                "Should have 1 item remaining after auto-close"
13619            );
13620        });
13621
13622        // Check navigation history after close
13623        let has_item = pane.read_with(cx, |pane, cx| {
13624            let mut has_item = false;
13625            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13626                if entry.item.id() == item1_id {
13627                    has_item = true;
13628                }
13629            });
13630            has_item
13631        });
13632
13633        assert!(
13634            !has_item,
13635            "Navigation history should not contain closed item entries"
13636        );
13637    }
13638
13639    #[gpui::test]
13640    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13641        cx: &mut TestAppContext,
13642    ) {
13643        init_test(cx);
13644
13645        let fs = FakeFs::new(cx.background_executor.clone());
13646        let project = Project::test(fs, [], cx).await;
13647        let (workspace, cx) =
13648            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13649        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13650
13651        let dirty_regular_buffer = cx.new(|cx| {
13652            TestItem::new(cx)
13653                .with_dirty(true)
13654                .with_label("1.txt")
13655                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13656        });
13657        let dirty_regular_buffer_2 = cx.new(|cx| {
13658            TestItem::new(cx)
13659                .with_dirty(true)
13660                .with_label("2.txt")
13661                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13662        });
13663        let clear_regular_buffer = cx.new(|cx| {
13664            TestItem::new(cx)
13665                .with_label("3.txt")
13666                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13667        });
13668
13669        let dirty_multi_buffer = cx.new(|cx| {
13670            TestItem::new(cx)
13671                .with_dirty(true)
13672                .with_buffer_kind(ItemBufferKind::Multibuffer)
13673                .with_label("Fake Project Search")
13674                .with_project_items(&[
13675                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13676                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13677                    clear_regular_buffer.read(cx).project_items[0].clone(),
13678                ])
13679        });
13680        workspace.update_in(cx, |workspace, window, cx| {
13681            workspace.add_item(
13682                pane.clone(),
13683                Box::new(dirty_regular_buffer.clone()),
13684                None,
13685                false,
13686                false,
13687                window,
13688                cx,
13689            );
13690            workspace.add_item(
13691                pane.clone(),
13692                Box::new(dirty_regular_buffer_2.clone()),
13693                None,
13694                false,
13695                false,
13696                window,
13697                cx,
13698            );
13699            workspace.add_item(
13700                pane.clone(),
13701                Box::new(dirty_multi_buffer.clone()),
13702                None,
13703                false,
13704                false,
13705                window,
13706                cx,
13707            );
13708        });
13709
13710        pane.update_in(cx, |pane, window, cx| {
13711            pane.activate_item(2, true, true, window, cx);
13712            assert_eq!(
13713                pane.active_item().unwrap().item_id(),
13714                dirty_multi_buffer.item_id(),
13715                "Should select the multi buffer in the pane"
13716            );
13717        });
13718        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13719            pane.close_active_item(
13720                &CloseActiveItem {
13721                    save_intent: None,
13722                    close_pinned: false,
13723                },
13724                window,
13725                cx,
13726            )
13727        });
13728        cx.background_executor.run_until_parked();
13729        assert!(
13730            !cx.has_pending_prompt(),
13731            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13732        );
13733        close_multi_buffer_task
13734            .await
13735            .expect("Closing multi buffer failed");
13736        pane.update(cx, |pane, cx| {
13737            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13738            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13739            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13740            assert_eq!(
13741                pane.items()
13742                    .map(|item| item.item_id())
13743                    .sorted()
13744                    .collect::<Vec<_>>(),
13745                vec![
13746                    dirty_regular_buffer.item_id(),
13747                    dirty_regular_buffer_2.item_id(),
13748                ],
13749                "Should have no multi buffer left in the pane"
13750            );
13751            assert!(dirty_regular_buffer.read(cx).is_dirty);
13752            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13753        });
13754    }
13755
13756    #[gpui::test]
13757    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13758        init_test(cx);
13759        let fs = FakeFs::new(cx.executor());
13760        let project = Project::test(fs, [], cx).await;
13761        let (multi_workspace, cx) =
13762            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13763        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13764
13765        // Add a new panel to the right dock, opening the dock and setting the
13766        // focus to the new panel.
13767        let panel = workspace.update_in(cx, |workspace, window, cx| {
13768            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13769            workspace.add_panel(panel.clone(), window, cx);
13770
13771            workspace
13772                .right_dock()
13773                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13774
13775            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13776
13777            panel
13778        });
13779
13780        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13781        // panel to the next valid position which, in this case, is the left
13782        // dock.
13783        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13784        workspace.update(cx, |workspace, cx| {
13785            assert!(workspace.left_dock().read(cx).is_open());
13786            assert_eq!(panel.read(cx).position, DockPosition::Left);
13787        });
13788
13789        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13790        // panel to the next valid position which, in this case, is the bottom
13791        // dock.
13792        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13793        workspace.update(cx, |workspace, cx| {
13794            assert!(workspace.bottom_dock().read(cx).is_open());
13795            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13796        });
13797
13798        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13799        // around moving the panel to its initial position, the right dock.
13800        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13801        workspace.update(cx, |workspace, cx| {
13802            assert!(workspace.right_dock().read(cx).is_open());
13803            assert_eq!(panel.read(cx).position, DockPosition::Right);
13804        });
13805
13806        // Remove focus from the panel, ensuring that, if the panel is not
13807        // focused, the `MoveFocusedPanelToNextPosition` action does not update
13808        // the panel's position, so the panel is still in the right dock.
13809        workspace.update_in(cx, |workspace, window, cx| {
13810            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13811        });
13812
13813        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13814        workspace.update(cx, |workspace, cx| {
13815            assert!(workspace.right_dock().read(cx).is_open());
13816            assert_eq!(panel.read(cx).position, DockPosition::Right);
13817        });
13818    }
13819
13820    #[gpui::test]
13821    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13822        init_test(cx);
13823
13824        let fs = FakeFs::new(cx.executor());
13825        let project = Project::test(fs, [], cx).await;
13826        let (workspace, cx) =
13827            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13828
13829        let item_1 = cx.new(|cx| {
13830            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13831        });
13832        workspace.update_in(cx, |workspace, window, cx| {
13833            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13834            workspace.move_item_to_pane_in_direction(
13835                &MoveItemToPaneInDirection {
13836                    direction: SplitDirection::Right,
13837                    focus: true,
13838                    clone: false,
13839                },
13840                window,
13841                cx,
13842            );
13843            workspace.move_item_to_pane_at_index(
13844                &MoveItemToPane {
13845                    destination: 3,
13846                    focus: true,
13847                    clone: false,
13848                },
13849                window,
13850                cx,
13851            );
13852
13853            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13854            assert_eq!(
13855                pane_items_paths(&workspace.active_pane, cx),
13856                vec!["first.txt".to_string()],
13857                "Single item was not moved anywhere"
13858            );
13859        });
13860
13861        let item_2 = cx.new(|cx| {
13862            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13863        });
13864        workspace.update_in(cx, |workspace, window, cx| {
13865            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13866            assert_eq!(
13867                pane_items_paths(&workspace.panes[0], cx),
13868                vec!["first.txt".to_string(), "second.txt".to_string()],
13869            );
13870            workspace.move_item_to_pane_in_direction(
13871                &MoveItemToPaneInDirection {
13872                    direction: SplitDirection::Right,
13873                    focus: true,
13874                    clone: false,
13875                },
13876                window,
13877                cx,
13878            );
13879
13880            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13881            assert_eq!(
13882                pane_items_paths(&workspace.panes[0], cx),
13883                vec!["first.txt".to_string()],
13884                "After moving, one item should be left in the original pane"
13885            );
13886            assert_eq!(
13887                pane_items_paths(&workspace.panes[1], cx),
13888                vec!["second.txt".to_string()],
13889                "New item should have been moved to the new pane"
13890            );
13891        });
13892
13893        let item_3 = cx.new(|cx| {
13894            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13895        });
13896        workspace.update_in(cx, |workspace, window, cx| {
13897            let original_pane = workspace.panes[0].clone();
13898            workspace.set_active_pane(&original_pane, window, cx);
13899            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13900            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13901            assert_eq!(
13902                pane_items_paths(&workspace.active_pane, cx),
13903                vec!["first.txt".to_string(), "third.txt".to_string()],
13904                "New pane should be ready to move one item out"
13905            );
13906
13907            workspace.move_item_to_pane_at_index(
13908                &MoveItemToPane {
13909                    destination: 3,
13910                    focus: true,
13911                    clone: false,
13912                },
13913                window,
13914                cx,
13915            );
13916            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13917            assert_eq!(
13918                pane_items_paths(&workspace.active_pane, cx),
13919                vec!["first.txt".to_string()],
13920                "After moving, one item should be left in the original pane"
13921            );
13922            assert_eq!(
13923                pane_items_paths(&workspace.panes[1], cx),
13924                vec!["second.txt".to_string()],
13925                "Previously created pane should be unchanged"
13926            );
13927            assert_eq!(
13928                pane_items_paths(&workspace.panes[2], cx),
13929                vec!["third.txt".to_string()],
13930                "New item should have been moved to the new pane"
13931            );
13932        });
13933    }
13934
13935    #[gpui::test]
13936    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13937        init_test(cx);
13938
13939        let fs = FakeFs::new(cx.executor());
13940        let project = Project::test(fs, [], cx).await;
13941        let (workspace, cx) =
13942            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13943
13944        let item_1 = cx.new(|cx| {
13945            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13946        });
13947        workspace.update_in(cx, |workspace, window, cx| {
13948            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13949            workspace.move_item_to_pane_in_direction(
13950                &MoveItemToPaneInDirection {
13951                    direction: SplitDirection::Right,
13952                    focus: true,
13953                    clone: true,
13954                },
13955                window,
13956                cx,
13957            );
13958        });
13959        cx.run_until_parked();
13960        workspace.update_in(cx, |workspace, window, cx| {
13961            workspace.move_item_to_pane_at_index(
13962                &MoveItemToPane {
13963                    destination: 3,
13964                    focus: true,
13965                    clone: true,
13966                },
13967                window,
13968                cx,
13969            );
13970        });
13971        cx.run_until_parked();
13972
13973        workspace.update(cx, |workspace, cx| {
13974            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13975            for pane in workspace.panes() {
13976                assert_eq!(
13977                    pane_items_paths(pane, cx),
13978                    vec!["first.txt".to_string()],
13979                    "Single item exists in all panes"
13980                );
13981            }
13982        });
13983
13984        // verify that the active pane has been updated after waiting for the
13985        // pane focus event to fire and resolve
13986        workspace.read_with(cx, |workspace, _app| {
13987            assert_eq!(
13988                workspace.active_pane(),
13989                &workspace.panes[2],
13990                "The third pane should be the active one: {:?}",
13991                workspace.panes
13992            );
13993        })
13994    }
13995
13996    #[gpui::test]
13997    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13998        init_test(cx);
13999
14000        let fs = FakeFs::new(cx.executor());
14001        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
14002
14003        let project = Project::test(fs, ["root".as_ref()], cx).await;
14004        let (workspace, cx) =
14005            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14006
14007        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14008        // Add item to pane A with project path
14009        let item_a = cx.new(|cx| {
14010            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14011        });
14012        workspace.update_in(cx, |workspace, window, cx| {
14013            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14014        });
14015
14016        // Split to create pane B
14017        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14018            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14019        });
14020
14021        // Add item with SAME project path to pane B, and pin it
14022        let item_b = cx.new(|cx| {
14023            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14024        });
14025        pane_b.update_in(cx, |pane, window, cx| {
14026            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14027            pane.set_pinned_count(1);
14028        });
14029
14030        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14031        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14032
14033        // close_pinned: false should only close the unpinned copy
14034        workspace.update_in(cx, |workspace, window, cx| {
14035            workspace.close_item_in_all_panes(
14036                &CloseItemInAllPanes {
14037                    save_intent: Some(SaveIntent::Close),
14038                    close_pinned: false,
14039                },
14040                window,
14041                cx,
14042            )
14043        });
14044        cx.executor().run_until_parked();
14045
14046        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14047        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14048        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14049        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14050
14051        // Split again, seeing as closing the previous item also closed its
14052        // pane, so only pane remains, which does not allow us to properly test
14053        // that both items close when `close_pinned: true`.
14054        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14055            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14056        });
14057
14058        // Add an item with the same project path to pane C so that
14059        // close_item_in_all_panes can determine what to close across all panes
14060        // (it reads the active item from the active pane, and split_pane
14061        // creates an empty pane).
14062        let item_c = cx.new(|cx| {
14063            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14064        });
14065        pane_c.update_in(cx, |pane, window, cx| {
14066            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14067        });
14068
14069        // close_pinned: true should close the pinned copy too
14070        workspace.update_in(cx, |workspace, window, cx| {
14071            let panes_count = workspace.panes().len();
14072            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14073
14074            workspace.close_item_in_all_panes(
14075                &CloseItemInAllPanes {
14076                    save_intent: Some(SaveIntent::Close),
14077                    close_pinned: true,
14078                },
14079                window,
14080                cx,
14081            )
14082        });
14083        cx.executor().run_until_parked();
14084
14085        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14086        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14087        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14088        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14089    }
14090
14091    mod register_project_item_tests {
14092
14093        use super::*;
14094
14095        // View
14096        struct TestPngItemView {
14097            focus_handle: FocusHandle,
14098        }
14099        // Model
14100        struct TestPngItem {}
14101
14102        impl project::ProjectItem for TestPngItem {
14103            fn try_open(
14104                _project: &Entity<Project>,
14105                path: &ProjectPath,
14106                cx: &mut App,
14107            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14108                if path.path.extension().unwrap() == "png" {
14109                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14110                } else {
14111                    None
14112                }
14113            }
14114
14115            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14116                None
14117            }
14118
14119            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14120                None
14121            }
14122
14123            fn is_dirty(&self) -> bool {
14124                false
14125            }
14126        }
14127
14128        impl Item for TestPngItemView {
14129            type Event = ();
14130            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14131                "".into()
14132            }
14133        }
14134        impl EventEmitter<()> for TestPngItemView {}
14135        impl Focusable for TestPngItemView {
14136            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14137                self.focus_handle.clone()
14138            }
14139        }
14140
14141        impl Render for TestPngItemView {
14142            fn render(
14143                &mut self,
14144                _window: &mut Window,
14145                _cx: &mut Context<Self>,
14146            ) -> impl IntoElement {
14147                Empty
14148            }
14149        }
14150
14151        impl ProjectItem for TestPngItemView {
14152            type Item = TestPngItem;
14153
14154            fn for_project_item(
14155                _project: Entity<Project>,
14156                _pane: Option<&Pane>,
14157                _item: Entity<Self::Item>,
14158                _: &mut Window,
14159                cx: &mut Context<Self>,
14160            ) -> Self
14161            where
14162                Self: Sized,
14163            {
14164                Self {
14165                    focus_handle: cx.focus_handle(),
14166                }
14167            }
14168        }
14169
14170        // View
14171        struct TestIpynbItemView {
14172            focus_handle: FocusHandle,
14173        }
14174        // Model
14175        struct TestIpynbItem {}
14176
14177        impl project::ProjectItem for TestIpynbItem {
14178            fn try_open(
14179                _project: &Entity<Project>,
14180                path: &ProjectPath,
14181                cx: &mut App,
14182            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14183                if path.path.extension().unwrap() == "ipynb" {
14184                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14185                } else {
14186                    None
14187                }
14188            }
14189
14190            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14191                None
14192            }
14193
14194            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14195                None
14196            }
14197
14198            fn is_dirty(&self) -> bool {
14199                false
14200            }
14201        }
14202
14203        impl Item for TestIpynbItemView {
14204            type Event = ();
14205            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14206                "".into()
14207            }
14208        }
14209        impl EventEmitter<()> for TestIpynbItemView {}
14210        impl Focusable for TestIpynbItemView {
14211            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14212                self.focus_handle.clone()
14213            }
14214        }
14215
14216        impl Render for TestIpynbItemView {
14217            fn render(
14218                &mut self,
14219                _window: &mut Window,
14220                _cx: &mut Context<Self>,
14221            ) -> impl IntoElement {
14222                Empty
14223            }
14224        }
14225
14226        impl ProjectItem for TestIpynbItemView {
14227            type Item = TestIpynbItem;
14228
14229            fn for_project_item(
14230                _project: Entity<Project>,
14231                _pane: Option<&Pane>,
14232                _item: Entity<Self::Item>,
14233                _: &mut Window,
14234                cx: &mut Context<Self>,
14235            ) -> Self
14236            where
14237                Self: Sized,
14238            {
14239                Self {
14240                    focus_handle: cx.focus_handle(),
14241                }
14242            }
14243        }
14244
14245        struct TestAlternatePngItemView {
14246            focus_handle: FocusHandle,
14247        }
14248
14249        impl Item for TestAlternatePngItemView {
14250            type Event = ();
14251            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14252                "".into()
14253            }
14254        }
14255
14256        impl EventEmitter<()> for TestAlternatePngItemView {}
14257        impl Focusable for TestAlternatePngItemView {
14258            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14259                self.focus_handle.clone()
14260            }
14261        }
14262
14263        impl Render for TestAlternatePngItemView {
14264            fn render(
14265                &mut self,
14266                _window: &mut Window,
14267                _cx: &mut Context<Self>,
14268            ) -> impl IntoElement {
14269                Empty
14270            }
14271        }
14272
14273        impl ProjectItem for TestAlternatePngItemView {
14274            type Item = TestPngItem;
14275
14276            fn for_project_item(
14277                _project: Entity<Project>,
14278                _pane: Option<&Pane>,
14279                _item: Entity<Self::Item>,
14280                _: &mut Window,
14281                cx: &mut Context<Self>,
14282            ) -> Self
14283            where
14284                Self: Sized,
14285            {
14286                Self {
14287                    focus_handle: cx.focus_handle(),
14288                }
14289            }
14290        }
14291
14292        #[gpui::test]
14293        async fn test_register_project_item(cx: &mut TestAppContext) {
14294            init_test(cx);
14295
14296            cx.update(|cx| {
14297                register_project_item::<TestPngItemView>(cx);
14298                register_project_item::<TestIpynbItemView>(cx);
14299            });
14300
14301            let fs = FakeFs::new(cx.executor());
14302            fs.insert_tree(
14303                "/root1",
14304                json!({
14305                    "one.png": "BINARYDATAHERE",
14306                    "two.ipynb": "{ totally a notebook }",
14307                    "three.txt": "editing text, sure why not?"
14308                }),
14309            )
14310            .await;
14311
14312            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14313            let (workspace, cx) =
14314                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14315
14316            let worktree_id = project.update(cx, |project, cx| {
14317                project.worktrees(cx).next().unwrap().read(cx).id()
14318            });
14319
14320            let handle = workspace
14321                .update_in(cx, |workspace, window, cx| {
14322                    let project_path = (worktree_id, rel_path("one.png"));
14323                    workspace.open_path(project_path, None, true, window, cx)
14324                })
14325                .await
14326                .unwrap();
14327
14328            // Now we can check if the handle we got back errored or not
14329            assert_eq!(
14330                handle.to_any_view().entity_type(),
14331                TypeId::of::<TestPngItemView>()
14332            );
14333
14334            let handle = workspace
14335                .update_in(cx, |workspace, window, cx| {
14336                    let project_path = (worktree_id, rel_path("two.ipynb"));
14337                    workspace.open_path(project_path, None, true, window, cx)
14338                })
14339                .await
14340                .unwrap();
14341
14342            assert_eq!(
14343                handle.to_any_view().entity_type(),
14344                TypeId::of::<TestIpynbItemView>()
14345            );
14346
14347            let handle = workspace
14348                .update_in(cx, |workspace, window, cx| {
14349                    let project_path = (worktree_id, rel_path("three.txt"));
14350                    workspace.open_path(project_path, None, true, window, cx)
14351                })
14352                .await;
14353            assert!(handle.is_err());
14354        }
14355
14356        #[gpui::test]
14357        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14358            init_test(cx);
14359
14360            cx.update(|cx| {
14361                register_project_item::<TestPngItemView>(cx);
14362                register_project_item::<TestAlternatePngItemView>(cx);
14363            });
14364
14365            let fs = FakeFs::new(cx.executor());
14366            fs.insert_tree(
14367                "/root1",
14368                json!({
14369                    "one.png": "BINARYDATAHERE",
14370                    "two.ipynb": "{ totally a notebook }",
14371                    "three.txt": "editing text, sure why not?"
14372                }),
14373            )
14374            .await;
14375            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14376            let (workspace, cx) =
14377                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14378            let worktree_id = project.update(cx, |project, cx| {
14379                project.worktrees(cx).next().unwrap().read(cx).id()
14380            });
14381
14382            let handle = workspace
14383                .update_in(cx, |workspace, window, cx| {
14384                    let project_path = (worktree_id, rel_path("one.png"));
14385                    workspace.open_path(project_path, None, true, window, cx)
14386                })
14387                .await
14388                .unwrap();
14389
14390            // This _must_ be the second item registered
14391            assert_eq!(
14392                handle.to_any_view().entity_type(),
14393                TypeId::of::<TestAlternatePngItemView>()
14394            );
14395
14396            let handle = workspace
14397                .update_in(cx, |workspace, window, cx| {
14398                    let project_path = (worktree_id, rel_path("three.txt"));
14399                    workspace.open_path(project_path, None, true, window, cx)
14400                })
14401                .await;
14402            assert!(handle.is_err());
14403        }
14404    }
14405
14406    #[gpui::test]
14407    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14408        init_test(cx);
14409
14410        let fs = FakeFs::new(cx.executor());
14411        let project = Project::test(fs, [], cx).await;
14412        let (workspace, _cx) =
14413            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14414
14415        // Test with status bar shown (default)
14416        workspace.read_with(cx, |workspace, cx| {
14417            let visible = workspace.status_bar_visible(cx);
14418            assert!(visible, "Status bar should be visible by default");
14419        });
14420
14421        // Test with status bar hidden
14422        cx.update_global(|store: &mut SettingsStore, cx| {
14423            store.update_user_settings(cx, |settings| {
14424                settings.status_bar.get_or_insert_default().show = Some(false);
14425            });
14426        });
14427
14428        workspace.read_with(cx, |workspace, cx| {
14429            let visible = workspace.status_bar_visible(cx);
14430            assert!(!visible, "Status bar should be hidden when show is false");
14431        });
14432
14433        // Test with status bar shown explicitly
14434        cx.update_global(|store: &mut SettingsStore, cx| {
14435            store.update_user_settings(cx, |settings| {
14436                settings.status_bar.get_or_insert_default().show = Some(true);
14437            });
14438        });
14439
14440        workspace.read_with(cx, |workspace, cx| {
14441            let visible = workspace.status_bar_visible(cx);
14442            assert!(visible, "Status bar should be visible when show is true");
14443        });
14444    }
14445
14446    #[gpui::test]
14447    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14448        init_test(cx);
14449
14450        let fs = FakeFs::new(cx.executor());
14451        let project = Project::test(fs, [], cx).await;
14452        let (multi_workspace, cx) =
14453            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14454        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14455        let panel = workspace.update_in(cx, |workspace, window, cx| {
14456            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14457            workspace.add_panel(panel.clone(), window, cx);
14458
14459            workspace
14460                .right_dock()
14461                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14462
14463            panel
14464        });
14465
14466        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14467        let item_a = cx.new(TestItem::new);
14468        let item_b = cx.new(TestItem::new);
14469        let item_a_id = item_a.entity_id();
14470        let item_b_id = item_b.entity_id();
14471
14472        pane.update_in(cx, |pane, window, cx| {
14473            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14474            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14475        });
14476
14477        pane.read_with(cx, |pane, _| {
14478            assert_eq!(pane.items_len(), 2);
14479            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14480        });
14481
14482        workspace.update_in(cx, |workspace, window, cx| {
14483            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14484        });
14485
14486        workspace.update_in(cx, |_, window, cx| {
14487            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14488        });
14489
14490        // Assert that the `pane::CloseActiveItem` action is handled at the
14491        // workspace level when one of the dock panels is focused and, in that
14492        // case, the center pane's active item is closed but the focus is not
14493        // moved.
14494        cx.dispatch_action(pane::CloseActiveItem::default());
14495        cx.run_until_parked();
14496
14497        pane.read_with(cx, |pane, _| {
14498            assert_eq!(pane.items_len(), 1);
14499            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14500        });
14501
14502        workspace.update_in(cx, |workspace, window, cx| {
14503            assert!(workspace.right_dock().read(cx).is_open());
14504            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14505        });
14506    }
14507
14508    #[gpui::test]
14509    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14510        init_test(cx);
14511        let fs = FakeFs::new(cx.executor());
14512
14513        let project_a = Project::test(fs.clone(), [], cx).await;
14514        let project_b = Project::test(fs, [], cx).await;
14515
14516        let multi_workspace_handle =
14517            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14518        cx.run_until_parked();
14519
14520        let workspace_a = multi_workspace_handle
14521            .read_with(cx, |mw, _| mw.workspace().clone())
14522            .unwrap();
14523
14524        let _workspace_b = multi_workspace_handle
14525            .update(cx, |mw, window, cx| {
14526                mw.test_add_workspace(project_b, window, cx)
14527            })
14528            .unwrap();
14529
14530        // Switch to workspace A
14531        multi_workspace_handle
14532            .update(cx, |mw, window, cx| {
14533                let workspace = mw.workspaces()[0].clone();
14534                mw.activate(workspace, window, cx);
14535            })
14536            .unwrap();
14537
14538        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14539
14540        // Add a panel to workspace A's right dock and open the dock
14541        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14542            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14543            workspace.add_panel(panel.clone(), window, cx);
14544            workspace
14545                .right_dock()
14546                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14547            panel
14548        });
14549
14550        // Focus the panel through the workspace (matching existing test pattern)
14551        workspace_a.update_in(cx, |workspace, window, cx| {
14552            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14553        });
14554
14555        // Zoom the panel
14556        panel.update_in(cx, |panel, window, cx| {
14557            panel.set_zoomed(true, window, cx);
14558        });
14559
14560        // Verify the panel is zoomed and the dock is open
14561        workspace_a.update_in(cx, |workspace, window, cx| {
14562            assert!(
14563                workspace.right_dock().read(cx).is_open(),
14564                "dock should be open before switch"
14565            );
14566            assert!(
14567                panel.is_zoomed(window, cx),
14568                "panel should be zoomed before switch"
14569            );
14570            assert!(
14571                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14572                "panel should be focused before switch"
14573            );
14574        });
14575
14576        // Switch to workspace B
14577        multi_workspace_handle
14578            .update(cx, |mw, window, cx| {
14579                let workspace = mw.workspaces()[1].clone();
14580                mw.activate(workspace, window, cx);
14581            })
14582            .unwrap();
14583        cx.run_until_parked();
14584
14585        // Switch back to workspace A
14586        multi_workspace_handle
14587            .update(cx, |mw, window, cx| {
14588                let workspace = mw.workspaces()[0].clone();
14589                mw.activate(workspace, window, cx);
14590            })
14591            .unwrap();
14592        cx.run_until_parked();
14593
14594        // Verify the panel is still zoomed and the dock is still open
14595        workspace_a.update_in(cx, |workspace, window, cx| {
14596            assert!(
14597                workspace.right_dock().read(cx).is_open(),
14598                "dock should still be open after switching back"
14599            );
14600            assert!(
14601                panel.is_zoomed(window, cx),
14602                "panel should still be zoomed after switching back"
14603            );
14604        });
14605    }
14606
14607    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14608        pane.read(cx)
14609            .items()
14610            .flat_map(|item| {
14611                item.project_paths(cx)
14612                    .into_iter()
14613                    .map(|path| path.path.display(PathStyle::local()).into_owned())
14614            })
14615            .collect()
14616    }
14617
14618    pub fn init_test(cx: &mut TestAppContext) {
14619        cx.update(|cx| {
14620            let settings_store = SettingsStore::test(cx);
14621            cx.set_global(settings_store);
14622            cx.set_global(db::AppDatabase::test_new());
14623            theme_settings::init(theme::LoadThemes::JustBase, cx);
14624        });
14625    }
14626
14627    #[gpui::test]
14628    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14629        use settings::{ThemeName, ThemeSelection};
14630        use theme::SystemAppearance;
14631        use zed_actions::theme::ToggleMode;
14632
14633        init_test(cx);
14634
14635        let fs = FakeFs::new(cx.executor());
14636        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14637
14638        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14639            .await;
14640
14641        // Build a test project and workspace view so the test can invoke
14642        // the workspace action handler the same way the UI would.
14643        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14644        let (workspace, cx) =
14645            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14646
14647        // Seed the settings file with a plain static light theme so the
14648        // first toggle always starts from a known persisted state.
14649        workspace.update_in(cx, |_workspace, _window, cx| {
14650            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14651            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14652                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14653            });
14654        });
14655        cx.executor().advance_clock(Duration::from_millis(200));
14656        cx.run_until_parked();
14657
14658        // Confirm the initial persisted settings contain the static theme
14659        // we just wrote before any toggling happens.
14660        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14661        assert!(settings_text.contains(r#""theme": "One Light""#));
14662
14663        // Toggle once. This should migrate the persisted theme settings
14664        // into light/dark slots and enable system mode.
14665        workspace.update_in(cx, |workspace, window, cx| {
14666            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14667        });
14668        cx.executor().advance_clock(Duration::from_millis(200));
14669        cx.run_until_parked();
14670
14671        // 1. Static -> Dynamic
14672        // this assertion checks theme changed from static to dynamic.
14673        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14674        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14675        assert_eq!(
14676            parsed["theme"],
14677            serde_json::json!({
14678                "mode": "system",
14679                "light": "One Light",
14680                "dark": "One Dark"
14681            })
14682        );
14683
14684        // 2. Toggle again, suppose it will change the mode to light
14685        workspace.update_in(cx, |workspace, window, cx| {
14686            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14687        });
14688        cx.executor().advance_clock(Duration::from_millis(200));
14689        cx.run_until_parked();
14690
14691        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14692        assert!(settings_text.contains(r#""mode": "light""#));
14693    }
14694
14695    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14696        let item = TestProjectItem::new(id, path, cx);
14697        item.update(cx, |item, _| {
14698            item.is_dirty = true;
14699        });
14700        item
14701    }
14702
14703    #[gpui::test]
14704    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14705        cx: &mut gpui::TestAppContext,
14706    ) {
14707        init_test(cx);
14708        let fs = FakeFs::new(cx.executor());
14709
14710        let project = Project::test(fs, [], cx).await;
14711        let (workspace, cx) =
14712            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14713
14714        let panel = workspace.update_in(cx, |workspace, window, cx| {
14715            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14716            workspace.add_panel(panel.clone(), window, cx);
14717            workspace
14718                .right_dock()
14719                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14720            panel
14721        });
14722
14723        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14724        pane.update_in(cx, |pane, window, cx| {
14725            let item = cx.new(TestItem::new);
14726            pane.add_item(Box::new(item), true, true, None, window, cx);
14727        });
14728
14729        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14730        // mirrors the real-world flow and avoids side effects from directly
14731        // focusing the panel while the center pane is active.
14732        workspace.update_in(cx, |workspace, window, cx| {
14733            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14734        });
14735
14736        panel.update_in(cx, |panel, window, cx| {
14737            panel.set_zoomed(true, window, cx);
14738        });
14739
14740        workspace.update_in(cx, |workspace, window, cx| {
14741            assert!(workspace.right_dock().read(cx).is_open());
14742            assert!(panel.is_zoomed(window, cx));
14743            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14744        });
14745
14746        // Simulate a spurious pane::Event::Focus on the center pane while the
14747        // panel still has focus. This mirrors what happens during macOS window
14748        // activation: the center pane fires a focus event even though actual
14749        // focus remains on the dock panel.
14750        pane.update_in(cx, |_, _, cx| {
14751            cx.emit(pane::Event::Focus);
14752        });
14753
14754        // The dock must remain open because the panel had focus at the time the
14755        // event was processed. Before the fix, dock_to_preserve was None for
14756        // panels that don't implement pane(), causing the dock to close.
14757        workspace.update_in(cx, |workspace, window, cx| {
14758            assert!(
14759                workspace.right_dock().read(cx).is_open(),
14760                "Dock should stay open when its zoomed panel (without pane()) still has focus"
14761            );
14762            assert!(panel.is_zoomed(window, cx));
14763        });
14764    }
14765
14766    #[gpui::test]
14767    async fn test_panels_stay_open_after_position_change_and_settings_update(
14768        cx: &mut gpui::TestAppContext,
14769    ) {
14770        init_test(cx);
14771        let fs = FakeFs::new(cx.executor());
14772        let project = Project::test(fs, [], cx).await;
14773        let (workspace, cx) =
14774            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14775
14776        // Add two panels to the left dock and open it.
14777        let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14778            let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14779            let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14780            workspace.add_panel(panel_a.clone(), window, cx);
14781            workspace.add_panel(panel_b.clone(), window, cx);
14782            workspace.left_dock().update(cx, |dock, cx| {
14783                dock.set_open(true, window, cx);
14784                dock.activate_panel(0, window, cx);
14785            });
14786            (panel_a, panel_b)
14787        });
14788
14789        workspace.update_in(cx, |workspace, _, cx| {
14790            assert!(workspace.left_dock().read(cx).is_open());
14791        });
14792
14793        // Simulate a feature flag changing default dock positions: both panels
14794        // move from Left to Right.
14795        workspace.update_in(cx, |_workspace, _window, cx| {
14796            panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14797            panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14798            cx.update_global::<SettingsStore, _>(|_, _| {});
14799        });
14800
14801        // Both panels should now be in the right dock.
14802        workspace.update_in(cx, |workspace, _, cx| {
14803            let right_dock = workspace.right_dock().read(cx);
14804            assert_eq!(right_dock.panels_len(), 2);
14805        });
14806
14807        // Open the right dock and activate panel_b (simulating the user
14808        // opening the panel after it moved).
14809        workspace.update_in(cx, |workspace, window, cx| {
14810            workspace.right_dock().update(cx, |dock, cx| {
14811                dock.set_open(true, window, cx);
14812                dock.activate_panel(1, window, cx);
14813            });
14814        });
14815
14816        // Now trigger another SettingsStore change
14817        workspace.update_in(cx, |_workspace, _window, cx| {
14818            cx.update_global::<SettingsStore, _>(|_, _| {});
14819        });
14820
14821        workspace.update_in(cx, |workspace, _, cx| {
14822            assert!(
14823                workspace.right_dock().read(cx).is_open(),
14824                "Right dock should still be open after a settings change"
14825            );
14826            assert_eq!(
14827                workspace.right_dock().read(cx).panels_len(),
14828                2,
14829                "Both panels should still be in the right dock"
14830            );
14831        });
14832    }
14833}