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;
   22pub mod focus_follows_mouse;
   23mod status_bar;
   24pub mod tasks;
   25mod theme_preview;
   26mod toast_layer;
   27mod toolbar;
   28pub mod welcome;
   29mod workspace_settings;
   30
   31pub use crate::notifications::NotificationFrame;
   32pub use dock::Panel;
   33pub use multi_workspace::{
   34    CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MoveProjectToNewWindow,
   35    MultiWorkspace, MultiWorkspaceEvent, NewThread, NextProject, NextThread, PreviousProject,
   36    PreviousThread, ProjectGroup, ProjectGroupKey, SerializedProjectGroupState, ShowFewerThreads,
   37    ShowMoreThreads, Sidebar, SidebarEvent, SidebarHandle, SidebarRenderState, SidebarSide,
   38    ToggleWorkspaceSidebar, sidebar_side_context_menu,
   39};
   40pub use path_list::{PathList, SerializedPathList};
   41pub use remote::{
   42    RemoteConnectionIdentity, remote_connection_identity, same_remote_connection_identity,
   43};
   44pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   45
   46use anyhow::{Context as _, Result, anyhow};
   47use client::{
   48    ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
   49    proto::{self, ErrorCode, PanelId, PeerId},
   50};
   51use collections::{HashMap, HashSet, hash_map};
   52use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   53use fs::Fs;
   54use futures::{
   55    Future, FutureExt, StreamExt,
   56    channel::{
   57        mpsc::{self, UnboundedReceiver, UnboundedSender},
   58        oneshot,
   59    },
   60    future::{Shared, try_join_all},
   61};
   62use gpui::{
   63    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
   64    Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   65    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   66    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   67    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   68    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   69};
   70pub use history_manager::*;
   71pub use item::{
   72    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   73    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   74};
   75use itertools::Itertools;
   76use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   77pub use modal_layer::*;
   78use node_runtime::NodeRuntime;
   79use notifications::{
   80    DetachAndPromptErr, Notifications, dismiss_app_notification,
   81    simple_message_notification::MessageNotification,
   82};
   83pub use pane::*;
   84pub use pane_group::{
   85    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   86    SplitDirection,
   87};
   88use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
   89pub use persistence::{
   90    WorkspaceDb, delete_unloaded_items,
   91    model::{
   92        DockData, DockStructure, ItemId, MultiWorkspaceState, SerializedMultiWorkspace,
   93        SerializedProjectGroup, SerializedWorkspaceLocation, SessionWorkspace,
   94    },
   95    read_serialized_multi_workspaces, resolve_worktree_workspaces,
   96};
   97use postage::stream::Stream;
   98use project::{
   99    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
  100    WorktreeSettings,
  101    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
  102    project_settings::ProjectSettings,
  103    toolchain_store::ToolchainStoreEvent,
  104    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
  105};
  106use remote::{
  107    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
  108    remote_client::ConnectionIdentifier,
  109};
  110use schemars::JsonSchema;
  111use serde::Deserialize;
  112use session::AppSession;
  113use settings::{
  114    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  115};
  116
  117use sqlez::{
  118    bindable::{Bind, Column, StaticColumnCount},
  119    statement::Statement,
  120};
  121use status_bar::StatusBar;
  122pub use status_bar::StatusItemView;
  123use std::{
  124    any::TypeId,
  125    borrow::Cow,
  126    cell::RefCell,
  127    cmp,
  128    collections::VecDeque,
  129    env,
  130    hash::Hash,
  131    path::{Path, PathBuf},
  132    process::ExitStatus,
  133    rc::Rc,
  134    sync::{
  135        Arc, LazyLock,
  136        atomic::{AtomicBool, AtomicUsize},
  137    },
  138    time::Duration,
  139};
  140use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  141use theme::{ActiveTheme, SystemAppearance};
  142use theme_settings::ThemeSettings;
  143pub use toolbar::{
  144    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  145};
  146pub use ui;
  147use ui::{Window, prelude::*};
  148use util::{
  149    ResultExt, TryFutureExt,
  150    paths::{PathStyle, SanitizedPath},
  151    rel_path::RelPath,
  152    serde::default_true,
  153};
  154use uuid::Uuid;
  155pub use workspace_settings::{
  156    AutosaveSetting, BottomDockLayout, FocusFollowsMouse, RestoreOnStartupBehavior,
  157    StatusBarSettings, TabBarSettings, WorkspaceSettings,
  158};
  159use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
  160
  161use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::NotificationId};
  162use crate::{
  163    persistence::{
  164        SerializedAxis,
  165        model::{SerializedItem, SerializedPane, SerializedPaneGroup},
  166    },
  167    security_modal::SecurityModal,
  168};
  169
  170pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  171
  172static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  173    env::var("ZED_WINDOW_SIZE")
  174        .ok()
  175        .as_deref()
  176        .and_then(parse_pixel_size_env_var)
  177});
  178
  179static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  180    env::var("ZED_WINDOW_POSITION")
  181        .ok()
  182        .as_deref()
  183        .and_then(parse_pixel_position_env_var)
  184});
  185
  186pub trait TerminalProvider {
  187    fn spawn(
  188        &self,
  189        task: SpawnInTerminal,
  190        window: &mut Window,
  191        cx: &mut App,
  192    ) -> Task<Option<Result<ExitStatus>>>;
  193}
  194
  195pub trait DebuggerProvider {
  196    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  197    fn start_session(
  198        &self,
  199        definition: DebugScenario,
  200        task_context: SharedTaskContext,
  201        active_buffer: Option<Entity<Buffer>>,
  202        worktree_id: Option<WorktreeId>,
  203        window: &mut Window,
  204        cx: &mut App,
  205    );
  206
  207    fn spawn_task_or_modal(
  208        &self,
  209        workspace: &mut Workspace,
  210        action: &Spawn,
  211        window: &mut Window,
  212        cx: &mut Context<Workspace>,
  213    );
  214
  215    fn task_scheduled(&self, cx: &mut App);
  216    fn debug_scenario_scheduled(&self, cx: &mut App);
  217    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  218
  219    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  220}
  221
  222/// Opens a file or directory.
  223#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  224#[action(namespace = workspace)]
  225pub struct Open {
  226    /// When true, opens in a new window. When false, adds to the current
  227    /// window as a new workspace (multi-workspace).
  228    #[serde(default = "Open::default_create_new_window")]
  229    pub create_new_window: bool,
  230}
  231
  232impl Open {
  233    pub const DEFAULT: Self = Self {
  234        create_new_window: true,
  235    };
  236
  237    /// Used by `#[serde(default)]` on the `create_new_window` field so that
  238    /// the serde default and `Open::DEFAULT` stay in sync.
  239    fn default_create_new_window() -> bool {
  240        Self::DEFAULT.create_new_window
  241    }
  242}
  243
  244impl Default for Open {
  245    fn default() -> Self {
  246        Self::DEFAULT
  247    }
  248}
  249
  250actions!(
  251    workspace,
  252    [
  253        /// Activates the next pane in the workspace.
  254        ActivateNextPane,
  255        /// Activates the previous pane in the workspace.
  256        ActivatePreviousPane,
  257        /// Activates the last pane in the workspace.
  258        ActivateLastPane,
  259        /// Switches to the next window.
  260        ActivateNextWindow,
  261        /// Switches to the previous window.
  262        ActivatePreviousWindow,
  263        /// Adds a folder to the current project.
  264        AddFolderToProject,
  265        /// Clears all notifications.
  266        ClearAllNotifications,
  267        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  268        ClearNavigationHistory,
  269        /// Closes the active dock.
  270        CloseActiveDock,
  271        /// Closes all docks.
  272        CloseAllDocks,
  273        /// Toggles all docks.
  274        ToggleAllDocks,
  275        /// Closes the current window.
  276        CloseWindow,
  277        /// Closes the current project.
  278        CloseProject,
  279        /// Opens the feedback dialog.
  280        Feedback,
  281        /// Follows the next collaborator in the session.
  282        FollowNextCollaborator,
  283        /// Moves the focused panel to the next position.
  284        MoveFocusedPanelToNextPosition,
  285        /// Creates a new file.
  286        NewFile,
  287        /// Creates a new file in a vertical split.
  288        NewFileSplitVertical,
  289        /// Creates a new file in a horizontal split.
  290        NewFileSplitHorizontal,
  291        /// Opens a new search.
  292        NewSearch,
  293        /// Opens a new window.
  294        NewWindow,
  295        /// Opens multiple files.
  296        OpenFiles,
  297        /// Opens the current location in terminal.
  298        OpenInTerminal,
  299        /// Opens the component preview.
  300        OpenComponentPreview,
  301        /// Reloads the active item.
  302        ReloadActiveItem,
  303        /// Resets the active dock to its default size.
  304        ResetActiveDockSize,
  305        /// Resets all open docks to their default sizes.
  306        ResetOpenDocksSize,
  307        /// Reloads the application
  308        Reload,
  309        /// Formats and saves the current file, regardless of the format_on_save setting.
  310        FormatAndSave,
  311        /// Saves the current file with a new name.
  312        SaveAs,
  313        /// Saves without formatting.
  314        SaveWithoutFormat,
  315        /// Shuts down all debug adapters.
  316        ShutdownDebugAdapters,
  317        /// Suppresses the current notification.
  318        SuppressNotification,
  319        /// Toggles the bottom dock.
  320        ToggleBottomDock,
  321        /// Toggles centered layout mode.
  322        ToggleCenteredLayout,
  323        /// Toggles edit prediction feature globally for all files.
  324        ToggleEditPrediction,
  325        /// Toggles the left dock.
  326        ToggleLeftDock,
  327        /// Toggles the right dock.
  328        ToggleRightDock,
  329        /// Toggles zoom on the active pane.
  330        ToggleZoom,
  331        /// Toggles read-only mode for the active item (if supported by that item).
  332        ToggleReadOnlyFile,
  333        /// Zooms in on the active pane.
  334        ZoomIn,
  335        /// Zooms out of the active pane.
  336        ZoomOut,
  337        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  338        /// If the modal is shown already, closes it without trusting any worktree.
  339        ToggleWorktreeSecurity,
  340        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  341        /// Requires restart to take effect on already opened projects.
  342        ClearTrustedWorktrees,
  343        /// Stops following a collaborator.
  344        Unfollow,
  345        /// Restores the banner.
  346        RestoreBanner,
  347        /// Toggles expansion of the selected item.
  348        ToggleExpandItem,
  349    ]
  350);
  351
  352/// Activates a specific pane by its index.
  353#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  354#[action(namespace = workspace)]
  355pub struct ActivatePane(pub usize);
  356
  357/// Moves an item to a specific pane by index.
  358#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  359#[action(namespace = workspace)]
  360#[serde(deny_unknown_fields)]
  361pub struct MoveItemToPane {
  362    #[serde(default = "default_1")]
  363    pub destination: usize,
  364    #[serde(default = "default_true")]
  365    pub focus: bool,
  366    #[serde(default)]
  367    pub clone: bool,
  368}
  369
  370fn default_1() -> usize {
  371    1
  372}
  373
  374/// Moves an item to a pane in the specified direction.
  375#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  376#[action(namespace = workspace)]
  377#[serde(deny_unknown_fields)]
  378pub struct MoveItemToPaneInDirection {
  379    #[serde(default = "default_right")]
  380    pub direction: SplitDirection,
  381    #[serde(default = "default_true")]
  382    pub focus: bool,
  383    #[serde(default)]
  384    pub clone: bool,
  385}
  386
  387/// Creates a new file in a split of the desired direction.
  388#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  389#[action(namespace = workspace)]
  390#[serde(deny_unknown_fields)]
  391pub struct NewFileSplit(pub SplitDirection);
  392
  393fn default_right() -> SplitDirection {
  394    SplitDirection::Right
  395}
  396
  397/// Saves all open files in the workspace.
  398#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  399#[action(namespace = workspace)]
  400#[serde(deny_unknown_fields)]
  401pub struct SaveAll {
  402    #[serde(default)]
  403    pub save_intent: Option<SaveIntent>,
  404}
  405
  406/// Saves the current file with the specified options.
  407#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  408#[action(namespace = workspace)]
  409#[serde(deny_unknown_fields)]
  410pub struct Save {
  411    #[serde(default)]
  412    pub save_intent: Option<SaveIntent>,
  413}
  414
  415/// Moves Focus to the central panes in the workspace.
  416#[derive(Clone, Debug, PartialEq, Eq, Action)]
  417#[action(namespace = workspace)]
  418pub struct FocusCenterPane;
  419
  420///  Closes all items and panes in the workspace.
  421#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  422#[action(namespace = workspace)]
  423#[serde(deny_unknown_fields)]
  424pub struct CloseAllItemsAndPanes {
  425    #[serde(default)]
  426    pub save_intent: Option<SaveIntent>,
  427}
  428
  429/// Closes all inactive tabs and panes in the workspace.
  430#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  431#[action(namespace = workspace)]
  432#[serde(deny_unknown_fields)]
  433pub struct CloseInactiveTabsAndPanes {
  434    #[serde(default)]
  435    pub save_intent: Option<SaveIntent>,
  436}
  437
  438/// Closes the active item across all panes.
  439#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  440#[action(namespace = workspace)]
  441#[serde(deny_unknown_fields)]
  442pub struct CloseItemInAllPanes {
  443    #[serde(default)]
  444    pub save_intent: Option<SaveIntent>,
  445    #[serde(default)]
  446    pub close_pinned: bool,
  447}
  448
  449/// Sends a sequence of keystrokes to the active element.
  450#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  451#[action(namespace = workspace)]
  452pub struct SendKeystrokes(pub String);
  453
  454actions!(
  455    project_symbols,
  456    [
  457        /// Toggles the project symbols search.
  458        #[action(name = "Toggle")]
  459        ToggleProjectSymbols
  460    ]
  461);
  462
  463/// Toggles the file finder interface.
  464#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  465#[action(namespace = file_finder, name = "Toggle")]
  466#[serde(deny_unknown_fields)]
  467pub struct ToggleFileFinder {
  468    #[serde(default)]
  469    pub separate_history: bool,
  470}
  471
  472/// Opens a new terminal in the center.
  473#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  474#[action(namespace = workspace)]
  475#[serde(deny_unknown_fields)]
  476pub struct NewCenterTerminal {
  477    /// If true, creates a local terminal even in remote projects.
  478    #[serde(default)]
  479    pub local: bool,
  480}
  481
  482/// Opens a new terminal.
  483#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  484#[action(namespace = workspace)]
  485#[serde(deny_unknown_fields)]
  486pub struct NewTerminal {
  487    /// If true, creates a local terminal even in remote projects.
  488    #[serde(default)]
  489    pub local: bool,
  490}
  491
  492/// Increases size of a currently focused dock by a given amount of pixels.
  493#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  494#[action(namespace = workspace)]
  495#[serde(deny_unknown_fields)]
  496pub struct IncreaseActiveDockSize {
  497    /// For 0px parameter, uses UI font size value.
  498    #[serde(default)]
  499    pub px: u32,
  500}
  501
  502/// Decreases size of a currently focused dock by a given amount of pixels.
  503#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  504#[action(namespace = workspace)]
  505#[serde(deny_unknown_fields)]
  506pub struct DecreaseActiveDockSize {
  507    /// For 0px parameter, uses UI font size value.
  508    #[serde(default)]
  509    pub px: u32,
  510}
  511
  512/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  513#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  514#[action(namespace = workspace)]
  515#[serde(deny_unknown_fields)]
  516pub struct IncreaseOpenDocksSize {
  517    /// For 0px parameter, uses UI font size value.
  518    #[serde(default)]
  519    pub px: u32,
  520}
  521
  522/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  523#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  524#[action(namespace = workspace)]
  525#[serde(deny_unknown_fields)]
  526pub struct DecreaseOpenDocksSize {
  527    /// For 0px parameter, uses UI font size value.
  528    #[serde(default)]
  529    pub px: u32,
  530}
  531
  532actions!(
  533    workspace,
  534    [
  535        /// Activates the pane to the left.
  536        ActivatePaneLeft,
  537        /// Activates the pane to the right.
  538        ActivatePaneRight,
  539        /// Activates the pane above.
  540        ActivatePaneUp,
  541        /// Activates the pane below.
  542        ActivatePaneDown,
  543        /// Swaps the current pane with the one to the left.
  544        SwapPaneLeft,
  545        /// Swaps the current pane with the one to the right.
  546        SwapPaneRight,
  547        /// Swaps the current pane with the one above.
  548        SwapPaneUp,
  549        /// Swaps the current pane with the one below.
  550        SwapPaneDown,
  551        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  552        SwapPaneAdjacent,
  553        /// Move the current pane to be at the far left.
  554        MovePaneLeft,
  555        /// Move the current pane to be at the far right.
  556        MovePaneRight,
  557        /// Move the current pane to be at the very top.
  558        MovePaneUp,
  559        /// Move the current pane to be at the very bottom.
  560        MovePaneDown,
  561    ]
  562);
  563
  564#[derive(PartialEq, Eq, Debug)]
  565pub enum CloseIntent {
  566    /// Quit the program entirely.
  567    Quit,
  568    /// Close a window.
  569    CloseWindow,
  570    /// Replace the workspace in an existing window.
  571    ReplaceWindow,
  572}
  573
  574#[derive(Clone)]
  575pub struct Toast {
  576    id: NotificationId,
  577    msg: Cow<'static, str>,
  578    autohide: bool,
  579    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  580}
  581
  582impl Toast {
  583    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  584        Toast {
  585            id,
  586            msg: msg.into(),
  587            on_click: None,
  588            autohide: false,
  589        }
  590    }
  591
  592    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  593    where
  594        M: Into<Cow<'static, str>>,
  595        F: Fn(&mut Window, &mut App) + 'static,
  596    {
  597        self.on_click = Some((message.into(), Arc::new(on_click)));
  598        self
  599    }
  600
  601    pub fn autohide(mut self) -> Self {
  602        self.autohide = true;
  603        self
  604    }
  605}
  606
  607impl PartialEq for Toast {
  608    fn eq(&self, other: &Self) -> bool {
  609        self.id == other.id
  610            && self.msg == other.msg
  611            && self.on_click.is_some() == other.on_click.is_some()
  612    }
  613}
  614
  615/// Opens a new terminal with the specified working directory.
  616#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  617#[action(namespace = workspace)]
  618#[serde(deny_unknown_fields)]
  619pub struct OpenTerminal {
  620    pub working_directory: PathBuf,
  621    /// If true, creates a local terminal even in remote projects.
  622    #[serde(default)]
  623    pub local: bool,
  624}
  625
  626#[derive(
  627    Clone,
  628    Copy,
  629    Debug,
  630    Default,
  631    Hash,
  632    PartialEq,
  633    Eq,
  634    PartialOrd,
  635    Ord,
  636    serde::Serialize,
  637    serde::Deserialize,
  638)]
  639pub struct WorkspaceId(i64);
  640
  641impl WorkspaceId {
  642    pub fn from_i64(value: i64) -> Self {
  643        Self(value)
  644    }
  645}
  646
  647impl StaticColumnCount for WorkspaceId {}
  648impl Bind for WorkspaceId {
  649    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  650        self.0.bind(statement, start_index)
  651    }
  652}
  653impl Column for WorkspaceId {
  654    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  655        i64::column(statement, start_index)
  656            .map(|(i, next_index)| (Self(i), next_index))
  657            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  658    }
  659}
  660impl From<WorkspaceId> for i64 {
  661    fn from(val: WorkspaceId) -> Self {
  662        val.0
  663    }
  664}
  665
  666fn prompt_and_open_paths(
  667    app_state: Arc<AppState>,
  668    options: PathPromptOptions,
  669    create_new_window: bool,
  670    cx: &mut App,
  671) {
  672    if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
  673        workspace_window
  674            .update(cx, |multi_workspace, window, cx| {
  675                let workspace = multi_workspace.workspace().clone();
  676                workspace.update(cx, |workspace, cx| {
  677                    prompt_for_open_path_and_open(
  678                        workspace,
  679                        app_state,
  680                        options,
  681                        create_new_window,
  682                        window,
  683                        cx,
  684                    );
  685                });
  686            })
  687            .ok();
  688    } else {
  689        let task = Workspace::new_local(
  690            Vec::new(),
  691            app_state.clone(),
  692            None,
  693            None,
  694            None,
  695            OpenMode::Activate,
  696            cx,
  697        );
  698        cx.spawn(async move |cx| {
  699            let OpenResult { window, .. } = task.await?;
  700            window.update(cx, |multi_workspace, window, cx| {
  701                window.activate_window();
  702                let workspace = multi_workspace.workspace().clone();
  703                workspace.update(cx, |workspace, cx| {
  704                    prompt_for_open_path_and_open(
  705                        workspace,
  706                        app_state,
  707                        options,
  708                        create_new_window,
  709                        window,
  710                        cx,
  711                    );
  712                });
  713            })?;
  714            anyhow::Ok(())
  715        })
  716        .detach_and_log_err(cx);
  717    }
  718}
  719
  720pub fn prompt_for_open_path_and_open(
  721    workspace: &mut Workspace,
  722    app_state: Arc<AppState>,
  723    options: PathPromptOptions,
  724    create_new_window: bool,
  725    window: &mut Window,
  726    cx: &mut Context<Workspace>,
  727) {
  728    let paths = workspace.prompt_for_open_path(
  729        options,
  730        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  731        window,
  732        cx,
  733    );
  734    let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
  735    cx.spawn_in(window, async move |this, cx| {
  736        let Some(paths) = paths.await.log_err().flatten() else {
  737            return;
  738        };
  739        if !create_new_window {
  740            if let Some(handle) = multi_workspace_handle {
  741                if let Some(task) = handle
  742                    .update(cx, |multi_workspace, window, cx| {
  743                        multi_workspace.open_project(paths, OpenMode::Activate, window, cx)
  744                    })
  745                    .log_err()
  746                {
  747                    task.await.log_err();
  748                }
  749                return;
  750            }
  751        }
  752        if let Some(task) = this
  753            .update_in(cx, |this, window, cx| {
  754                this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
  755            })
  756            .log_err()
  757        {
  758            task.await.log_err();
  759        }
  760    })
  761    .detach();
  762}
  763
  764pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  765    component::init();
  766    theme_preview::init(cx);
  767    toast_layer::init(cx);
  768    history_manager::init(app_state.fs.clone(), cx);
  769
  770    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  771        .on_action(|_: &Reload, cx| reload(cx))
  772        .on_action(|action: &Open, cx: &mut App| {
  773            let app_state = AppState::global(cx);
  774            prompt_and_open_paths(
  775                app_state,
  776                PathPromptOptions {
  777                    files: true,
  778                    directories: true,
  779                    multiple: true,
  780                    prompt: None,
  781                },
  782                action.create_new_window,
  783                cx,
  784            );
  785        })
  786        .on_action(|_: &OpenFiles, cx: &mut App| {
  787            let directories = cx.can_select_mixed_files_and_dirs();
  788            let app_state = AppState::global(cx);
  789            prompt_and_open_paths(
  790                app_state,
  791                PathPromptOptions {
  792                    files: true,
  793                    directories,
  794                    multiple: true,
  795                    prompt: None,
  796                },
  797                true,
  798                cx,
  799            );
  800        });
  801}
  802
  803type BuildProjectItemFn =
  804    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  805
  806type BuildProjectItemForPathFn =
  807    fn(
  808        &Entity<Project>,
  809        &ProjectPath,
  810        &mut Window,
  811        &mut App,
  812    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  813
  814#[derive(Clone, Default)]
  815struct ProjectItemRegistry {
  816    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  817    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  818}
  819
  820impl ProjectItemRegistry {
  821    fn register<T: ProjectItem>(&mut self) {
  822        self.build_project_item_fns_by_type.insert(
  823            TypeId::of::<T::Item>(),
  824            |item, project, pane, window, cx| {
  825                let item = item.downcast().unwrap();
  826                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  827                    as Box<dyn ItemHandle>
  828            },
  829        );
  830        self.build_project_item_for_path_fns
  831            .push(|project, project_path, window, cx| {
  832                let project_path = project_path.clone();
  833                let is_file = project
  834                    .read(cx)
  835                    .entry_for_path(&project_path, cx)
  836                    .is_some_and(|entry| entry.is_file());
  837                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  838                let is_local = project.read(cx).is_local();
  839                let project_item =
  840                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  841                let project = project.clone();
  842                Some(window.spawn(cx, async move |cx| {
  843                    match project_item.await.with_context(|| {
  844                        format!(
  845                            "opening project path {:?}",
  846                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  847                        )
  848                    }) {
  849                        Ok(project_item) => {
  850                            let project_item = project_item;
  851                            let project_entry_id: Option<ProjectEntryId> =
  852                                project_item.read_with(cx, project::ProjectItem::entry_id);
  853                            let build_workspace_item = Box::new(
  854                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  855                                    Box::new(cx.new(|cx| {
  856                                        T::for_project_item(
  857                                            project,
  858                                            Some(pane),
  859                                            project_item,
  860                                            window,
  861                                            cx,
  862                                        )
  863                                    })) as Box<dyn ItemHandle>
  864                                },
  865                            ) as Box<_>;
  866                            Ok((project_entry_id, build_workspace_item))
  867                        }
  868                        Err(e) => {
  869                            log::warn!("Failed to open a project item: {e:#}");
  870                            if e.error_code() == ErrorCode::Internal {
  871                                if let Some(abs_path) =
  872                                    entry_abs_path.as_deref().filter(|_| is_file)
  873                                {
  874                                    if let Some(broken_project_item_view) =
  875                                        cx.update(|window, cx| {
  876                                            T::for_broken_project_item(
  877                                                abs_path, is_local, &e, window, cx,
  878                                            )
  879                                        })?
  880                                    {
  881                                        let build_workspace_item = Box::new(
  882                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  883                                                cx.new(|_| broken_project_item_view).boxed_clone()
  884                                            },
  885                                        )
  886                                        as Box<_>;
  887                                        return Ok((None, build_workspace_item));
  888                                    }
  889                                }
  890                            }
  891                            Err(e)
  892                        }
  893                    }
  894                }))
  895            });
  896    }
  897
  898    fn open_path(
  899        &self,
  900        project: &Entity<Project>,
  901        path: &ProjectPath,
  902        window: &mut Window,
  903        cx: &mut App,
  904    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  905        let Some(open_project_item) = self
  906            .build_project_item_for_path_fns
  907            .iter()
  908            .rev()
  909            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  910        else {
  911            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  912        };
  913        open_project_item
  914    }
  915
  916    fn build_item<T: project::ProjectItem>(
  917        &self,
  918        item: Entity<T>,
  919        project: Entity<Project>,
  920        pane: Option<&Pane>,
  921        window: &mut Window,
  922        cx: &mut App,
  923    ) -> Option<Box<dyn ItemHandle>> {
  924        let build = self
  925            .build_project_item_fns_by_type
  926            .get(&TypeId::of::<T>())?;
  927        Some(build(item.into_any(), project, pane, window, cx))
  928    }
  929}
  930
  931type WorkspaceItemBuilder =
  932    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  933
  934impl Global for ProjectItemRegistry {}
  935
  936/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  937/// items will get a chance to open the file, starting from the project item that
  938/// was added last.
  939pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  940    cx.default_global::<ProjectItemRegistry>().register::<I>();
  941}
  942
  943#[derive(Default)]
  944pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  945
  946struct FollowableViewDescriptor {
  947    from_state_proto: fn(
  948        Entity<Workspace>,
  949        ViewId,
  950        &mut Option<proto::view::Variant>,
  951        &mut Window,
  952        &mut App,
  953    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  954    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  955}
  956
  957impl Global for FollowableViewRegistry {}
  958
  959impl FollowableViewRegistry {
  960    pub fn register<I: FollowableItem>(cx: &mut App) {
  961        cx.default_global::<Self>().0.insert(
  962            TypeId::of::<I>(),
  963            FollowableViewDescriptor {
  964                from_state_proto: |workspace, id, state, window, cx| {
  965                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  966                        cx.foreground_executor()
  967                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  968                    })
  969                },
  970                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  971            },
  972        );
  973    }
  974
  975    pub fn from_state_proto(
  976        workspace: Entity<Workspace>,
  977        view_id: ViewId,
  978        mut state: Option<proto::view::Variant>,
  979        window: &mut Window,
  980        cx: &mut App,
  981    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  982        cx.update_default_global(|this: &mut Self, cx| {
  983            this.0.values().find_map(|descriptor| {
  984                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  985            })
  986        })
  987    }
  988
  989    pub fn to_followable_view(
  990        view: impl Into<AnyView>,
  991        cx: &App,
  992    ) -> Option<Box<dyn FollowableItemHandle>> {
  993        let this = cx.try_global::<Self>()?;
  994        let view = view.into();
  995        let descriptor = this.0.get(&view.entity_type())?;
  996        Some((descriptor.to_followable_view)(&view))
  997    }
  998}
  999
 1000#[derive(Copy, Clone)]
 1001struct SerializableItemDescriptor {
 1002    deserialize: fn(
 1003        Entity<Project>,
 1004        WeakEntity<Workspace>,
 1005        WorkspaceId,
 1006        ItemId,
 1007        &mut Window,
 1008        &mut Context<Pane>,
 1009    ) -> Task<Result<Box<dyn ItemHandle>>>,
 1010    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
 1011    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
 1012}
 1013
 1014#[derive(Default)]
 1015struct SerializableItemRegistry {
 1016    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
 1017    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
 1018}
 1019
 1020impl Global for SerializableItemRegistry {}
 1021
 1022impl SerializableItemRegistry {
 1023    fn deserialize(
 1024        item_kind: &str,
 1025        project: Entity<Project>,
 1026        workspace: WeakEntity<Workspace>,
 1027        workspace_id: WorkspaceId,
 1028        item_item: ItemId,
 1029        window: &mut Window,
 1030        cx: &mut Context<Pane>,
 1031    ) -> Task<Result<Box<dyn ItemHandle>>> {
 1032        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1033            return Task::ready(Err(anyhow!(
 1034                "cannot deserialize {}, descriptor not found",
 1035                item_kind
 1036            )));
 1037        };
 1038
 1039        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
 1040    }
 1041
 1042    fn cleanup(
 1043        item_kind: &str,
 1044        workspace_id: WorkspaceId,
 1045        loaded_items: Vec<ItemId>,
 1046        window: &mut Window,
 1047        cx: &mut App,
 1048    ) -> Task<Result<()>> {
 1049        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1050            return Task::ready(Err(anyhow!(
 1051                "cannot cleanup {}, descriptor not found",
 1052                item_kind
 1053            )));
 1054        };
 1055
 1056        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
 1057    }
 1058
 1059    fn view_to_serializable_item_handle(
 1060        view: AnyView,
 1061        cx: &App,
 1062    ) -> Option<Box<dyn SerializableItemHandle>> {
 1063        let this = cx.try_global::<Self>()?;
 1064        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
 1065        Some((descriptor.view_to_serializable_item)(view))
 1066    }
 1067
 1068    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
 1069        let this = cx.try_global::<Self>()?;
 1070        this.descriptors_by_kind.get(item_kind).copied()
 1071    }
 1072}
 1073
 1074pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
 1075    let serialized_item_kind = I::serialized_item_kind();
 1076
 1077    let registry = cx.default_global::<SerializableItemRegistry>();
 1078    let descriptor = SerializableItemDescriptor {
 1079        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
 1080            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
 1081            cx.foreground_executor()
 1082                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 1083        },
 1084        cleanup: |workspace_id, loaded_items, window, cx| {
 1085            I::cleanup(workspace_id, loaded_items, window, cx)
 1086        },
 1087        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1088    };
 1089    registry
 1090        .descriptors_by_kind
 1091        .insert(Arc::from(serialized_item_kind), descriptor);
 1092    registry
 1093        .descriptors_by_type
 1094        .insert(TypeId::of::<I>(), descriptor);
 1095}
 1096
 1097pub struct AppState {
 1098    pub languages: Arc<LanguageRegistry>,
 1099    pub client: Arc<Client>,
 1100    pub user_store: Entity<UserStore>,
 1101    pub workspace_store: Entity<WorkspaceStore>,
 1102    pub fs: Arc<dyn fs::Fs>,
 1103    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1104    pub node_runtime: NodeRuntime,
 1105    pub session: Entity<AppSession>,
 1106}
 1107
 1108struct GlobalAppState(Arc<AppState>);
 1109
 1110impl Global for GlobalAppState {}
 1111
 1112pub struct WorkspaceStore {
 1113    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1114    client: Arc<Client>,
 1115    _subscriptions: Vec<client::Subscription>,
 1116}
 1117
 1118#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1119pub enum CollaboratorId {
 1120    PeerId(PeerId),
 1121    Agent,
 1122}
 1123
 1124impl From<PeerId> for CollaboratorId {
 1125    fn from(peer_id: PeerId) -> Self {
 1126        CollaboratorId::PeerId(peer_id)
 1127    }
 1128}
 1129
 1130impl From<&PeerId> for CollaboratorId {
 1131    fn from(peer_id: &PeerId) -> Self {
 1132        CollaboratorId::PeerId(*peer_id)
 1133    }
 1134}
 1135
 1136#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1137struct Follower {
 1138    project_id: Option<u64>,
 1139    peer_id: PeerId,
 1140}
 1141
 1142impl AppState {
 1143    #[track_caller]
 1144    pub fn global(cx: &App) -> Arc<Self> {
 1145        cx.global::<GlobalAppState>().0.clone()
 1146    }
 1147    pub fn try_global(cx: &App) -> Option<Arc<Self>> {
 1148        cx.try_global::<GlobalAppState>()
 1149            .map(|state| state.0.clone())
 1150    }
 1151    pub fn set_global(state: Arc<AppState>, cx: &mut App) {
 1152        cx.set_global(GlobalAppState(state));
 1153    }
 1154
 1155    #[cfg(any(test, feature = "test-support"))]
 1156    pub fn test(cx: &mut App) -> Arc<Self> {
 1157        use fs::Fs;
 1158        use node_runtime::NodeRuntime;
 1159        use session::Session;
 1160        use settings::SettingsStore;
 1161
 1162        if !cx.has_global::<SettingsStore>() {
 1163            let settings_store = SettingsStore::test(cx);
 1164            cx.set_global(settings_store);
 1165        }
 1166
 1167        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1168        <dyn Fs>::set_global(fs.clone(), cx);
 1169        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1170        let clock = Arc::new(clock::FakeSystemClock::new());
 1171        let http_client = http_client::FakeHttpClient::with_404_response();
 1172        let client = Client::new(clock, http_client, cx);
 1173        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1174        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1175        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1176
 1177        theme_settings::init(theme::LoadThemes::JustBase, cx);
 1178        client::init(&client, cx);
 1179
 1180        Arc::new(Self {
 1181            client,
 1182            fs,
 1183            languages,
 1184            user_store,
 1185            workspace_store,
 1186            node_runtime: NodeRuntime::unavailable(),
 1187            build_window_options: |_, _| Default::default(),
 1188            session,
 1189        })
 1190    }
 1191}
 1192
 1193struct DelayedDebouncedEditAction {
 1194    task: Option<Task<()>>,
 1195    cancel_channel: Option<oneshot::Sender<()>>,
 1196}
 1197
 1198impl DelayedDebouncedEditAction {
 1199    fn new() -> DelayedDebouncedEditAction {
 1200        DelayedDebouncedEditAction {
 1201            task: None,
 1202            cancel_channel: None,
 1203        }
 1204    }
 1205
 1206    fn fire_new<F>(
 1207        &mut self,
 1208        delay: Duration,
 1209        window: &mut Window,
 1210        cx: &mut Context<Workspace>,
 1211        func: F,
 1212    ) where
 1213        F: 'static
 1214            + Send
 1215            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1216    {
 1217        if let Some(channel) = self.cancel_channel.take() {
 1218            _ = channel.send(());
 1219        }
 1220
 1221        let (sender, mut receiver) = oneshot::channel::<()>();
 1222        self.cancel_channel = Some(sender);
 1223
 1224        let previous_task = self.task.take();
 1225        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1226            let mut timer = cx.background_executor().timer(delay).fuse();
 1227            if let Some(previous_task) = previous_task {
 1228                previous_task.await;
 1229            }
 1230
 1231            futures::select_biased! {
 1232                _ = receiver => return,
 1233                    _ = timer => {}
 1234            }
 1235
 1236            if let Some(result) = workspace
 1237                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1238                .log_err()
 1239            {
 1240                result.await.log_err();
 1241            }
 1242        }));
 1243    }
 1244}
 1245
 1246pub enum Event {
 1247    PaneAdded(Entity<Pane>),
 1248    PaneRemoved,
 1249    ItemAdded {
 1250        item: Box<dyn ItemHandle>,
 1251    },
 1252    ActiveItemChanged,
 1253    ItemRemoved {
 1254        item_id: EntityId,
 1255    },
 1256    UserSavedItem {
 1257        pane: WeakEntity<Pane>,
 1258        item: Box<dyn WeakItemHandle>,
 1259        save_intent: SaveIntent,
 1260    },
 1261    ContactRequestedJoin(u64),
 1262    WorkspaceCreated(WeakEntity<Workspace>),
 1263    OpenBundledFile {
 1264        text: Cow<'static, str>,
 1265        title: &'static str,
 1266        language: &'static str,
 1267    },
 1268    ZoomChanged,
 1269    ModalOpened,
 1270    Activate,
 1271    PanelAdded(AnyView),
 1272}
 1273
 1274#[derive(Debug, Clone)]
 1275pub enum OpenVisible {
 1276    All,
 1277    None,
 1278    OnlyFiles,
 1279    OnlyDirectories,
 1280}
 1281
 1282enum WorkspaceLocation {
 1283    // Valid local paths or SSH project to serialize
 1284    Location(SerializedWorkspaceLocation, PathList),
 1285    // No valid location found hence clear session id
 1286    DetachFromSession,
 1287    // No valid location found to serialize
 1288    None,
 1289}
 1290
 1291type PromptForNewPath = Box<
 1292    dyn Fn(
 1293        &mut Workspace,
 1294        DirectoryLister,
 1295        Option<String>,
 1296        &mut Window,
 1297        &mut Context<Workspace>,
 1298    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1299>;
 1300
 1301type PromptForOpenPath = Box<
 1302    dyn Fn(
 1303        &mut Workspace,
 1304        DirectoryLister,
 1305        &mut Window,
 1306        &mut Context<Workspace>,
 1307    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1308>;
 1309
 1310#[derive(Default)]
 1311struct DispatchingKeystrokes {
 1312    dispatched: HashSet<Vec<Keystroke>>,
 1313    queue: VecDeque<Keystroke>,
 1314    task: Option<Shared<Task<()>>>,
 1315}
 1316
 1317/// Collects everything project-related for a certain window opened.
 1318/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1319///
 1320/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1321/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1322/// that can be used to register a global action to be triggered from any place in the window.
 1323pub struct Workspace {
 1324    weak_self: WeakEntity<Self>,
 1325    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1326    zoomed: Option<AnyWeakView>,
 1327    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1328    zoomed_position: Option<DockPosition>,
 1329    center: PaneGroup,
 1330    left_dock: Entity<Dock>,
 1331    bottom_dock: Entity<Dock>,
 1332    right_dock: Entity<Dock>,
 1333    panes: Vec<Entity<Pane>>,
 1334    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1335    active_pane: Entity<Pane>,
 1336    last_active_center_pane: Option<WeakEntity<Pane>>,
 1337    last_active_view_id: Option<proto::ViewId>,
 1338    status_bar: Entity<StatusBar>,
 1339    pub(crate) modal_layer: Entity<ModalLayer>,
 1340    toast_layer: Entity<ToastLayer>,
 1341    titlebar_item: Option<AnyView>,
 1342    notifications: Notifications,
 1343    suppressed_notifications: HashSet<NotificationId>,
 1344    project: Entity<Project>,
 1345    follower_states: HashMap<CollaboratorId, FollowerState>,
 1346    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1347    window_edited: bool,
 1348    last_window_title: Option<String>,
 1349    dirty_items: HashMap<EntityId, Subscription>,
 1350    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1351    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1352    database_id: Option<WorkspaceId>,
 1353    app_state: Arc<AppState>,
 1354    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1355    _subscriptions: Vec<Subscription>,
 1356    _apply_leader_updates: Task<Result<()>>,
 1357    _observe_current_user: Task<Result<()>>,
 1358    _schedule_serialize_workspace: Option<Task<()>>,
 1359    _serialize_workspace_task: Option<Task<()>>,
 1360    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1361    pane_history_timestamp: Arc<AtomicUsize>,
 1362    bounds: Bounds<Pixels>,
 1363    pub centered_layout: bool,
 1364    bounds_save_task_queued: Option<Task<()>>,
 1365    on_prompt_for_new_path: Option<PromptForNewPath>,
 1366    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1367    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1368    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1369    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1370    _items_serializer: Task<Result<()>>,
 1371    session_id: Option<String>,
 1372    scheduled_tasks: Vec<Task<()>>,
 1373    last_open_dock_positions: Vec<DockPosition>,
 1374    removing: bool,
 1375    open_in_dev_container: bool,
 1376    _dev_container_task: Option<Task<Result<()>>>,
 1377    _panels_task: Option<Task<Result<()>>>,
 1378    sidebar_focus_handle: Option<FocusHandle>,
 1379    multi_workspace: Option<WeakEntity<MultiWorkspace>>,
 1380}
 1381
 1382impl EventEmitter<Event> for Workspace {}
 1383
 1384#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1385pub struct ViewId {
 1386    pub creator: CollaboratorId,
 1387    pub id: u64,
 1388}
 1389
 1390pub struct FollowerState {
 1391    center_pane: Entity<Pane>,
 1392    dock_pane: Option<Entity<Pane>>,
 1393    active_view_id: Option<ViewId>,
 1394    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1395}
 1396
 1397struct FollowerView {
 1398    view: Box<dyn FollowableItemHandle>,
 1399    location: Option<proto::PanelId>,
 1400}
 1401
 1402#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
 1403pub enum OpenMode {
 1404    /// Open the workspace in a new window.
 1405    NewWindow,
 1406    /// Add to the window's multi workspace without activating it (used during deserialization).
 1407    Add,
 1408    /// Add to the window's multi workspace and activate it.
 1409    #[default]
 1410    Activate,
 1411}
 1412
 1413impl Workspace {
 1414    pub fn new(
 1415        workspace_id: Option<WorkspaceId>,
 1416        project: Entity<Project>,
 1417        app_state: Arc<AppState>,
 1418        window: &mut Window,
 1419        cx: &mut Context<Self>,
 1420    ) -> Self {
 1421        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1422            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1423                if let TrustedWorktreesEvent::Trusted(..) = e {
 1424                    // Do not persist auto trusted worktrees
 1425                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1426                        worktrees_store.update(cx, |worktrees_store, cx| {
 1427                            worktrees_store.schedule_serialization(
 1428                                cx,
 1429                                |new_trusted_worktrees, cx| {
 1430                                    let timeout =
 1431                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1432                                    let db = WorkspaceDb::global(cx);
 1433                                    cx.background_spawn(async move {
 1434                                        timeout.await;
 1435                                        db.save_trusted_worktrees(new_trusted_worktrees)
 1436                                            .await
 1437                                            .log_err();
 1438                                    })
 1439                                },
 1440                            )
 1441                        });
 1442                    }
 1443                }
 1444            })
 1445            .detach();
 1446
 1447            cx.observe_global::<SettingsStore>(|_, cx| {
 1448                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1449                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1450                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1451                            trusted_worktrees.auto_trust_all(cx);
 1452                        })
 1453                    }
 1454                }
 1455            })
 1456            .detach();
 1457        }
 1458
 1459        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1460            match event {
 1461                project::Event::RemoteIdChanged(_) => {
 1462                    this.update_window_title(window, cx);
 1463                }
 1464
 1465                project::Event::CollaboratorLeft(peer_id) => {
 1466                    this.collaborator_left(*peer_id, window, cx);
 1467                }
 1468
 1469                &project::Event::WorktreeRemoved(_) => {
 1470                    this.update_window_title(window, cx);
 1471                    this.serialize_workspace(window, cx);
 1472                    this.update_history(cx);
 1473                }
 1474
 1475                &project::Event::WorktreeAdded(id) => {
 1476                    this.update_window_title(window, cx);
 1477                    if this
 1478                        .project()
 1479                        .read(cx)
 1480                        .worktree_for_id(id, cx)
 1481                        .is_some_and(|wt| wt.read(cx).is_visible())
 1482                    {
 1483                        this.serialize_workspace(window, cx);
 1484                        this.update_history(cx);
 1485                    }
 1486                }
 1487                project::Event::WorktreeUpdatedEntries(..) => {
 1488                    this.update_window_title(window, cx);
 1489                    this.serialize_workspace(window, cx);
 1490                }
 1491
 1492                project::Event::DisconnectedFromHost => {
 1493                    this.update_window_edited(window, cx);
 1494                    let leaders_to_unfollow =
 1495                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1496                    for leader_id in leaders_to_unfollow {
 1497                        this.unfollow(leader_id, window, cx);
 1498                    }
 1499                }
 1500
 1501                project::Event::DisconnectedFromRemote {
 1502                    server_not_running: _,
 1503                } => {
 1504                    this.update_window_edited(window, cx);
 1505                }
 1506
 1507                project::Event::Closed => {
 1508                    window.remove_window();
 1509                }
 1510
 1511                project::Event::DeletedEntry(_, entry_id) => {
 1512                    for pane in this.panes.iter() {
 1513                        pane.update(cx, |pane, cx| {
 1514                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1515                        });
 1516                    }
 1517                }
 1518
 1519                project::Event::Toast {
 1520                    notification_id,
 1521                    message,
 1522                    link,
 1523                } => this.show_notification(
 1524                    NotificationId::named(notification_id.clone()),
 1525                    cx,
 1526                    |cx| {
 1527                        let mut notification = MessageNotification::new(message.clone(), cx);
 1528                        if let Some(link) = link {
 1529                            notification = notification
 1530                                .more_info_message(link.label)
 1531                                .more_info_url(link.url);
 1532                        }
 1533
 1534                        cx.new(|_| notification)
 1535                    },
 1536                ),
 1537
 1538                project::Event::HideToast { notification_id } => {
 1539                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1540                }
 1541
 1542                project::Event::LanguageServerPrompt(request) => {
 1543                    struct LanguageServerPrompt;
 1544
 1545                    this.show_notification(
 1546                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1547                        cx,
 1548                        |cx| {
 1549                            cx.new(|cx| {
 1550                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1551                            })
 1552                        },
 1553                    );
 1554                }
 1555
 1556                project::Event::AgentLocationChanged => {
 1557                    this.handle_agent_location_changed(window, cx)
 1558                }
 1559
 1560                _ => {}
 1561            }
 1562            cx.notify()
 1563        })
 1564        .detach();
 1565
 1566        cx.subscribe_in(
 1567            &project.read(cx).breakpoint_store(),
 1568            window,
 1569            |workspace, _, event, window, cx| match event {
 1570                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1571                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1572                    workspace.serialize_workspace(window, cx);
 1573                }
 1574                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1575            },
 1576        )
 1577        .detach();
 1578        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1579            cx.subscribe_in(
 1580                &toolchain_store,
 1581                window,
 1582                |workspace, _, event, window, cx| match event {
 1583                    ToolchainStoreEvent::CustomToolchainsModified => {
 1584                        workspace.serialize_workspace(window, cx);
 1585                    }
 1586                    _ => {}
 1587                },
 1588            )
 1589            .detach();
 1590        }
 1591
 1592        cx.on_focus_lost(window, |this, window, cx| {
 1593            let focus_handle = this.focus_handle(cx);
 1594            window.focus(&focus_handle, cx);
 1595        })
 1596        .detach();
 1597
 1598        let weak_handle = cx.entity().downgrade();
 1599        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1600
 1601        let center_pane = cx.new(|cx| {
 1602            let mut center_pane = Pane::new(
 1603                weak_handle.clone(),
 1604                project.clone(),
 1605                pane_history_timestamp.clone(),
 1606                None,
 1607                NewFile.boxed_clone(),
 1608                true,
 1609                window,
 1610                cx,
 1611            );
 1612            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1613            center_pane.set_should_display_welcome_page(true);
 1614            center_pane
 1615        });
 1616        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1617            .detach();
 1618
 1619        window.focus(&center_pane.focus_handle(cx), cx);
 1620
 1621        cx.emit(Event::PaneAdded(center_pane.clone()));
 1622
 1623        let any_window_handle = window.window_handle();
 1624        app_state.workspace_store.update(cx, |store, _| {
 1625            store
 1626                .workspaces
 1627                .insert((any_window_handle, weak_handle.clone()));
 1628        });
 1629
 1630        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1631        let mut connection_status = app_state.client.status();
 1632        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1633            current_user.next().await;
 1634            connection_status.next().await;
 1635            let mut stream =
 1636                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1637
 1638            while stream.recv().await.is_some() {
 1639                this.update(cx, |_, cx| cx.notify())?;
 1640            }
 1641            anyhow::Ok(())
 1642        });
 1643
 1644        // All leader updates are enqueued and then processed in a single task, so
 1645        // that each asynchronous operation can be run in order.
 1646        let (leader_updates_tx, mut leader_updates_rx) =
 1647            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1648        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1649            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1650                Self::process_leader_update(&this, leader_id, update, cx)
 1651                    .await
 1652                    .log_err();
 1653            }
 1654
 1655            Ok(())
 1656        });
 1657
 1658        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1659        let modal_layer = cx.new(|_| ModalLayer::new());
 1660        let toast_layer = cx.new(|_| ToastLayer::new());
 1661        cx.subscribe(
 1662            &modal_layer,
 1663            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1664                cx.emit(Event::ModalOpened);
 1665            },
 1666        )
 1667        .detach();
 1668
 1669        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1670        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1671        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1672        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1673        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1674        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1675        let multi_workspace = window
 1676            .root::<MultiWorkspace>()
 1677            .flatten()
 1678            .map(|mw| mw.downgrade());
 1679        let status_bar = cx.new(|cx| {
 1680            let mut status_bar =
 1681                StatusBar::new(&center_pane.clone(), multi_workspace.clone(), window, cx);
 1682            status_bar.add_left_item(left_dock_buttons, window, cx);
 1683            status_bar.add_right_item(right_dock_buttons, window, cx);
 1684            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1685            status_bar
 1686        });
 1687
 1688        let session_id = app_state.session.read(cx).id().to_owned();
 1689
 1690        let mut active_call = None;
 1691        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1692            let subscriptions =
 1693                vec![
 1694                    call.0
 1695                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1696                ];
 1697            active_call = Some((call, subscriptions));
 1698        }
 1699
 1700        let (serializable_items_tx, serializable_items_rx) =
 1701            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1702        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1703            Self::serialize_items(&this, serializable_items_rx, cx).await
 1704        });
 1705
 1706        let subscriptions = vec![
 1707            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1708            cx.observe_window_bounds(window, move |this, window, cx| {
 1709                if this.bounds_save_task_queued.is_some() {
 1710                    return;
 1711                }
 1712                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1713                    cx.background_executor()
 1714                        .timer(Duration::from_millis(100))
 1715                        .await;
 1716                    this.update_in(cx, |this, window, cx| {
 1717                        this.save_window_bounds(window, cx).detach();
 1718                        this.bounds_save_task_queued.take();
 1719                    })
 1720                    .ok();
 1721                }));
 1722                cx.notify();
 1723            }),
 1724            cx.observe_window_appearance(window, |_, window, cx| {
 1725                let window_appearance = window.appearance();
 1726
 1727                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1728
 1729                theme_settings::reload_theme(cx);
 1730                theme_settings::reload_icon_theme(cx);
 1731            }),
 1732            cx.on_release({
 1733                let weak_handle = weak_handle.clone();
 1734                move |this, cx| {
 1735                    this.app_state.workspace_store.update(cx, move |store, _| {
 1736                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1737                    })
 1738                }
 1739            }),
 1740        ];
 1741
 1742        cx.defer_in(window, move |this, window, cx| {
 1743            this.update_window_title(window, cx);
 1744            this.show_initial_notifications(cx);
 1745        });
 1746
 1747        let mut center = PaneGroup::new(center_pane.clone());
 1748        center.set_is_center(true);
 1749        center.mark_positions(cx);
 1750
 1751        Workspace {
 1752            weak_self: weak_handle.clone(),
 1753            zoomed: None,
 1754            zoomed_position: None,
 1755            previous_dock_drag_coordinates: None,
 1756            center,
 1757            panes: vec![center_pane.clone()],
 1758            panes_by_item: Default::default(),
 1759            active_pane: center_pane.clone(),
 1760            last_active_center_pane: Some(center_pane.downgrade()),
 1761            last_active_view_id: None,
 1762            status_bar,
 1763            modal_layer,
 1764            toast_layer,
 1765            titlebar_item: None,
 1766            notifications: Notifications::default(),
 1767            suppressed_notifications: HashSet::default(),
 1768            left_dock,
 1769            bottom_dock,
 1770            right_dock,
 1771            _panels_task: None,
 1772            project: project.clone(),
 1773            follower_states: Default::default(),
 1774            last_leaders_by_pane: Default::default(),
 1775            dispatching_keystrokes: Default::default(),
 1776            window_edited: false,
 1777            last_window_title: None,
 1778            dirty_items: Default::default(),
 1779            active_call,
 1780            database_id: workspace_id,
 1781            app_state,
 1782            _observe_current_user,
 1783            _apply_leader_updates,
 1784            _schedule_serialize_workspace: None,
 1785            _serialize_workspace_task: None,
 1786            _schedule_serialize_ssh_paths: None,
 1787            leader_updates_tx,
 1788            _subscriptions: subscriptions,
 1789            pane_history_timestamp,
 1790            workspace_actions: Default::default(),
 1791            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1792            bounds: Default::default(),
 1793            centered_layout: false,
 1794            bounds_save_task_queued: None,
 1795            on_prompt_for_new_path: None,
 1796            on_prompt_for_open_path: None,
 1797            terminal_provider: None,
 1798            debugger_provider: None,
 1799            serializable_items_tx,
 1800            _items_serializer,
 1801            session_id: Some(session_id),
 1802
 1803            scheduled_tasks: Vec::new(),
 1804            last_open_dock_positions: Vec::new(),
 1805            removing: false,
 1806            sidebar_focus_handle: None,
 1807            multi_workspace,
 1808            open_in_dev_container: false,
 1809            _dev_container_task: None,
 1810        }
 1811    }
 1812
 1813    pub fn new_local(
 1814        abs_paths: Vec<PathBuf>,
 1815        app_state: Arc<AppState>,
 1816        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1817        env: Option<HashMap<String, String>>,
 1818        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1819        open_mode: OpenMode,
 1820        cx: &mut App,
 1821    ) -> Task<anyhow::Result<OpenResult>> {
 1822        let project_handle = Project::local(
 1823            app_state.client.clone(),
 1824            app_state.node_runtime.clone(),
 1825            app_state.user_store.clone(),
 1826            app_state.languages.clone(),
 1827            app_state.fs.clone(),
 1828            env,
 1829            Default::default(),
 1830            cx,
 1831        );
 1832
 1833        let db = WorkspaceDb::global(cx);
 1834        let kvp = db::kvp::KeyValueStore::global(cx);
 1835        cx.spawn(async move |cx| {
 1836            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1837            for path in abs_paths.into_iter() {
 1838                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1839                    paths_to_open.push(canonical)
 1840                } else {
 1841                    paths_to_open.push(path)
 1842                }
 1843            }
 1844
 1845            let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
 1846
 1847            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1848                paths_to_open = paths.ordered_paths().cloned().collect();
 1849                if !paths.is_lexicographically_ordered() {
 1850                    project_handle.update(cx, |project, cx| {
 1851                        project.set_worktrees_reordered(true, cx);
 1852                    });
 1853                }
 1854            }
 1855
 1856            // Get project paths for all of the abs_paths
 1857            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1858                Vec::with_capacity(paths_to_open.len());
 1859
 1860            for path in paths_to_open.into_iter() {
 1861                if let Some((_, project_entry)) = cx
 1862                    .update(|cx| {
 1863                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1864                    })
 1865                    .await
 1866                    .log_err()
 1867                {
 1868                    project_paths.push((path, Some(project_entry)));
 1869                } else {
 1870                    project_paths.push((path, None));
 1871                }
 1872            }
 1873
 1874            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1875                serialized_workspace.id
 1876            } else {
 1877                db.next_id().await.unwrap_or_else(|_| Default::default())
 1878            };
 1879
 1880            let toolchains = db.toolchains(workspace_id).await?;
 1881
 1882            for (toolchain, worktree_path, path) in toolchains {
 1883                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1884                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1885                    this.find_worktree(&worktree_path, cx)
 1886                        .and_then(|(worktree, rel_path)| {
 1887                            if rel_path.is_empty() {
 1888                                Some(worktree.read(cx).id())
 1889                            } else {
 1890                                None
 1891                            }
 1892                        })
 1893                }) else {
 1894                    // We did not find a worktree with a given path, but that's whatever.
 1895                    continue;
 1896                };
 1897                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1898                    continue;
 1899                }
 1900
 1901                project_handle
 1902                    .update(cx, |this, cx| {
 1903                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1904                    })
 1905                    .await;
 1906            }
 1907            if let Some(workspace) = serialized_workspace.as_ref() {
 1908                project_handle.update(cx, |this, cx| {
 1909                    for (scope, toolchains) in &workspace.user_toolchains {
 1910                        for toolchain in toolchains {
 1911                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1912                        }
 1913                    }
 1914                });
 1915            }
 1916
 1917            let window_to_replace = match open_mode {
 1918                OpenMode::NewWindow => None,
 1919                _ => requesting_window,
 1920            };
 1921
 1922            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1923                if let Some(window) = window_to_replace {
 1924                    let centered_layout = serialized_workspace
 1925                        .as_ref()
 1926                        .map(|w| w.centered_layout)
 1927                        .unwrap_or(false);
 1928
 1929                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1930                        let workspace = cx.new(|cx| {
 1931                            let mut workspace = Workspace::new(
 1932                                Some(workspace_id),
 1933                                project_handle.clone(),
 1934                                app_state.clone(),
 1935                                window,
 1936                                cx,
 1937                            );
 1938
 1939                            workspace.centered_layout = centered_layout;
 1940
 1941                            // Call init callback to add items before window renders
 1942                            if let Some(init) = init {
 1943                                init(&mut workspace, window, cx);
 1944                            }
 1945
 1946                            workspace
 1947                        });
 1948                        match open_mode {
 1949                            OpenMode::Activate => {
 1950                                multi_workspace.activate(workspace.clone(), window, cx);
 1951                            }
 1952                            OpenMode::Add => {
 1953                                multi_workspace.add(workspace.clone(), &*window, cx);
 1954                            }
 1955                            OpenMode::NewWindow => {
 1956                                unreachable!()
 1957                            }
 1958                        }
 1959                        workspace
 1960                    })?;
 1961                    (window, workspace)
 1962                } else {
 1963                    let window_bounds_override = window_bounds_env_override();
 1964
 1965                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1966                        (Some(WindowBounds::Windowed(bounds)), None)
 1967                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1968                        && let Some(display) = workspace.display
 1969                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1970                    {
 1971                        // Reopening an existing workspace - restore its saved bounds
 1972                        (Some(bounds.0), Some(display))
 1973                    } else if let Some((display, bounds)) =
 1974                        persistence::read_default_window_bounds(&kvp)
 1975                    {
 1976                        // New or empty workspace - use the last known window bounds
 1977                        (Some(bounds), Some(display))
 1978                    } else {
 1979                        // New window - let GPUI's default_bounds() handle cascading
 1980                        (None, None)
 1981                    };
 1982
 1983                    // Use the serialized workspace to construct the new window
 1984                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1985                    options.window_bounds = window_bounds;
 1986                    let centered_layout = serialized_workspace
 1987                        .as_ref()
 1988                        .map(|w| w.centered_layout)
 1989                        .unwrap_or(false);
 1990                    let window = cx.open_window(options, {
 1991                        let app_state = app_state.clone();
 1992                        let project_handle = project_handle.clone();
 1993                        move |window, cx| {
 1994                            let workspace = cx.new(|cx| {
 1995                                let mut workspace = Workspace::new(
 1996                                    Some(workspace_id),
 1997                                    project_handle,
 1998                                    app_state,
 1999                                    window,
 2000                                    cx,
 2001                                );
 2002                                workspace.centered_layout = centered_layout;
 2003
 2004                                // Call init callback to add items before window renders
 2005                                if let Some(init) = init {
 2006                                    init(&mut workspace, window, cx);
 2007                                }
 2008
 2009                                workspace
 2010                            });
 2011                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 2012                        }
 2013                    })?;
 2014                    let workspace =
 2015                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 2016                            multi_workspace.workspace().clone()
 2017                        })?;
 2018                    (window, workspace)
 2019                };
 2020
 2021            notify_if_database_failed(window, cx);
 2022            // Check if this is an empty workspace (no paths to open)
 2023            // An empty workspace is one where project_paths is empty
 2024            let is_empty_workspace = project_paths.is_empty();
 2025            // Check if serialized workspace has paths before it's moved
 2026            let serialized_workspace_has_paths = serialized_workspace
 2027                .as_ref()
 2028                .map(|ws| !ws.paths.is_empty())
 2029                .unwrap_or(false);
 2030
 2031            let opened_items = window
 2032                .update(cx, |_, window, cx| {
 2033                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 2034                        open_items(serialized_workspace, project_paths, window, cx)
 2035                    })
 2036                })?
 2037                .await
 2038                .unwrap_or_default();
 2039
 2040            // Restore default dock state for empty workspaces
 2041            // Only restore if:
 2042            // 1. This is an empty workspace (no paths), AND
 2043            // 2. The serialized workspace either doesn't exist or has no paths
 2044            if is_empty_workspace && !serialized_workspace_has_paths {
 2045                if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
 2046                    window
 2047                        .update(cx, |_, window, cx| {
 2048                            workspace.update(cx, |workspace, cx| {
 2049                                for (dock, serialized_dock) in [
 2050                                    (&workspace.right_dock, &default_docks.right),
 2051                                    (&workspace.left_dock, &default_docks.left),
 2052                                    (&workspace.bottom_dock, &default_docks.bottom),
 2053                                ] {
 2054                                    dock.update(cx, |dock, cx| {
 2055                                        dock.serialized_dock = Some(serialized_dock.clone());
 2056                                        dock.restore_state(window, cx);
 2057                                    });
 2058                                }
 2059                                cx.notify();
 2060                            });
 2061                        })
 2062                        .log_err();
 2063                }
 2064            }
 2065
 2066            window
 2067                .update(cx, |_, _window, cx| {
 2068                    workspace.update(cx, |this: &mut Workspace, cx| {
 2069                        this.update_history(cx);
 2070                    });
 2071                })
 2072                .log_err();
 2073            Ok(OpenResult {
 2074                window,
 2075                workspace,
 2076                opened_items,
 2077            })
 2078        })
 2079    }
 2080
 2081    pub fn project_group_key(&self, cx: &App) -> ProjectGroupKey {
 2082        self.project.read(cx).project_group_key(cx)
 2083    }
 2084
 2085    pub fn weak_handle(&self) -> WeakEntity<Self> {
 2086        self.weak_self.clone()
 2087    }
 2088
 2089    pub fn left_dock(&self) -> &Entity<Dock> {
 2090        &self.left_dock
 2091    }
 2092
 2093    pub fn bottom_dock(&self) -> &Entity<Dock> {
 2094        &self.bottom_dock
 2095    }
 2096
 2097    pub fn set_bottom_dock_layout(
 2098        &mut self,
 2099        layout: BottomDockLayout,
 2100        window: &mut Window,
 2101        cx: &mut Context<Self>,
 2102    ) {
 2103        let fs = self.project().read(cx).fs();
 2104        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 2105            content.workspace.bottom_dock_layout = Some(layout);
 2106        });
 2107
 2108        cx.notify();
 2109        self.serialize_workspace(window, cx);
 2110    }
 2111
 2112    pub fn right_dock(&self) -> &Entity<Dock> {
 2113        &self.right_dock
 2114    }
 2115
 2116    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 2117        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 2118    }
 2119
 2120    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 2121        let left_dock = self.left_dock.read(cx);
 2122        let left_visible = left_dock.is_open();
 2123        let left_active_panel = left_dock
 2124            .active_panel()
 2125            .map(|panel| panel.persistent_name().to_string());
 2126        // `zoomed_position` is kept in sync with individual panel zoom state
 2127        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2128        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2129
 2130        let right_dock = self.right_dock.read(cx);
 2131        let right_visible = right_dock.is_open();
 2132        let right_active_panel = right_dock
 2133            .active_panel()
 2134            .map(|panel| panel.persistent_name().to_string());
 2135        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2136
 2137        let bottom_dock = self.bottom_dock.read(cx);
 2138        let bottom_visible = bottom_dock.is_open();
 2139        let bottom_active_panel = bottom_dock
 2140            .active_panel()
 2141            .map(|panel| panel.persistent_name().to_string());
 2142        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2143
 2144        DockStructure {
 2145            left: DockData {
 2146                visible: left_visible,
 2147                active_panel: left_active_panel,
 2148                zoom: left_dock_zoom,
 2149            },
 2150            right: DockData {
 2151                visible: right_visible,
 2152                active_panel: right_active_panel,
 2153                zoom: right_dock_zoom,
 2154            },
 2155            bottom: DockData {
 2156                visible: bottom_visible,
 2157                active_panel: bottom_active_panel,
 2158                zoom: bottom_dock_zoom,
 2159            },
 2160        }
 2161    }
 2162
 2163    pub fn set_dock_structure(
 2164        &self,
 2165        docks: DockStructure,
 2166        window: &mut Window,
 2167        cx: &mut Context<Self>,
 2168    ) {
 2169        for (dock, data) in [
 2170            (&self.left_dock, docks.left),
 2171            (&self.bottom_dock, docks.bottom),
 2172            (&self.right_dock, docks.right),
 2173        ] {
 2174            dock.update(cx, |dock, cx| {
 2175                dock.serialized_dock = Some(data);
 2176                dock.restore_state(window, cx);
 2177            });
 2178        }
 2179    }
 2180
 2181    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2182        self.items(cx)
 2183            .filter_map(|item| {
 2184                let project_path = item.project_path(cx)?;
 2185                self.project.read(cx).absolute_path(&project_path, cx)
 2186            })
 2187            .collect()
 2188    }
 2189
 2190    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2191        match position {
 2192            DockPosition::Left => &self.left_dock,
 2193            DockPosition::Bottom => &self.bottom_dock,
 2194            DockPosition::Right => &self.right_dock,
 2195        }
 2196    }
 2197
 2198    pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
 2199        self.all_docks().into_iter().find_map(|dock| {
 2200            let dock = dock.read(cx);
 2201            dock.has_agent_panel(cx).then_some(dock.position())
 2202        })
 2203    }
 2204
 2205    pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
 2206        self.all_docks().into_iter().find_map(|dock| {
 2207            let dock = dock.read(cx);
 2208            let panel = dock.panel::<T>()?;
 2209            dock.stored_panel_size_state(&panel)
 2210        })
 2211    }
 2212
 2213    pub fn persisted_panel_size_state(
 2214        &self,
 2215        panel_key: &'static str,
 2216        cx: &App,
 2217    ) -> Option<dock::PanelSizeState> {
 2218        dock::Dock::load_persisted_size_state(self, panel_key, cx)
 2219    }
 2220
 2221    pub fn persist_panel_size_state(
 2222        &self,
 2223        panel_key: &str,
 2224        size_state: dock::PanelSizeState,
 2225        cx: &mut App,
 2226    ) {
 2227        let Some(workspace_id) = self
 2228            .database_id()
 2229            .map(|id| i64::from(id).to_string())
 2230            .or(self.session_id())
 2231        else {
 2232            return;
 2233        };
 2234
 2235        let kvp = db::kvp::KeyValueStore::global(cx);
 2236        let panel_key = panel_key.to_string();
 2237        cx.background_spawn(async move {
 2238            let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
 2239            scope
 2240                .write(
 2241                    format!("{workspace_id}:{panel_key}"),
 2242                    serde_json::to_string(&size_state)?,
 2243                )
 2244                .await
 2245        })
 2246        .detach_and_log_err(cx);
 2247    }
 2248
 2249    pub fn set_panel_size_state<T: Panel>(
 2250        &mut self,
 2251        size_state: dock::PanelSizeState,
 2252        window: &mut Window,
 2253        cx: &mut Context<Self>,
 2254    ) -> bool {
 2255        let Some(panel) = self.panel::<T>(cx) else {
 2256            return false;
 2257        };
 2258
 2259        let dock = self.dock_at_position(panel.position(window, cx));
 2260        let did_set = dock.update(cx, |dock, cx| {
 2261            dock.set_panel_size_state(&panel, size_state, cx)
 2262        });
 2263
 2264        if did_set {
 2265            self.persist_panel_size_state(T::panel_key(), size_state, cx);
 2266        }
 2267
 2268        did_set
 2269    }
 2270
 2271    pub fn toggle_dock_panel_flexible_size(
 2272        &self,
 2273        dock: &Entity<Dock>,
 2274        panel: &dyn PanelHandle,
 2275        window: &mut Window,
 2276        cx: &mut App,
 2277    ) {
 2278        let position = dock.read(cx).position();
 2279        let current_size = self.dock_size(&dock.read(cx), window, cx);
 2280        let current_flex =
 2281            current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
 2282        dock.update(cx, |dock, cx| {
 2283            dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
 2284        });
 2285    }
 2286
 2287    fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
 2288        let panel = dock.active_panel()?;
 2289        let size_state = dock
 2290            .stored_panel_size_state(panel.as_ref())
 2291            .unwrap_or_default();
 2292        let position = dock.position();
 2293
 2294        let use_flex = panel.has_flexible_size(window, cx);
 2295
 2296        if position.axis() == Axis::Horizontal
 2297            && use_flex
 2298            && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
 2299        {
 2300            let workspace_width = self.bounds.size.width;
 2301            if workspace_width <= Pixels::ZERO {
 2302                return None;
 2303            }
 2304            let flex = flex.max(0.001);
 2305            let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2306            if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2307                // Both docks are flex items sharing the full workspace width.
 2308                let total_flex = flex + 1.0 + opposite_flex;
 2309                return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
 2310            } else {
 2311                // Opposite dock is fixed-width; flex items share (W - fixed).
 2312                let opposite_fixed = opposite
 2313                    .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2314                    .unwrap_or_default();
 2315                let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
 2316                return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
 2317            }
 2318        }
 2319
 2320        Some(
 2321            size_state
 2322                .size
 2323                .unwrap_or_else(|| panel.default_size(window, cx)),
 2324        )
 2325    }
 2326
 2327    pub fn dock_flex_for_size(
 2328        &self,
 2329        position: DockPosition,
 2330        size: Pixels,
 2331        window: &Window,
 2332        cx: &App,
 2333    ) -> Option<f32> {
 2334        if position.axis() != Axis::Horizontal {
 2335            return None;
 2336        }
 2337
 2338        let workspace_width = self.bounds.size.width;
 2339        if workspace_width <= Pixels::ZERO {
 2340            return None;
 2341        }
 2342
 2343        let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2344        if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2345            let size = size.clamp(px(0.), workspace_width - px(1.));
 2346            Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
 2347        } else {
 2348            let opposite_width = opposite
 2349                .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2350                .unwrap_or_default();
 2351            let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
 2352            let remaining = (available - size).max(px(1.));
 2353            Some((size / remaining).max(0.0))
 2354        }
 2355    }
 2356
 2357    fn opposite_dock_panel_and_size_state(
 2358        &self,
 2359        position: DockPosition,
 2360        window: &Window,
 2361        cx: &App,
 2362    ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
 2363        let opposite_position = match position {
 2364            DockPosition::Left => DockPosition::Right,
 2365            DockPosition::Right => DockPosition::Left,
 2366            DockPosition::Bottom => return None,
 2367        };
 2368
 2369        let opposite_dock = self.dock_at_position(opposite_position).read(cx);
 2370        let panel = opposite_dock.visible_panel()?;
 2371        let mut size_state = opposite_dock
 2372            .stored_panel_size_state(panel.as_ref())
 2373            .unwrap_or_default();
 2374        if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
 2375            size_state.flex = self.default_dock_flex(opposite_position);
 2376        }
 2377        Some((panel.clone(), size_state))
 2378    }
 2379
 2380    pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
 2381        if position.axis() != Axis::Horizontal {
 2382            return None;
 2383        }
 2384
 2385        let pane = self.last_active_center_pane.clone()?.upgrade()?;
 2386        Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
 2387    }
 2388
 2389    pub fn is_edited(&self) -> bool {
 2390        self.window_edited
 2391    }
 2392
 2393    pub fn add_panel<T: Panel>(
 2394        &mut self,
 2395        panel: Entity<T>,
 2396        window: &mut Window,
 2397        cx: &mut Context<Self>,
 2398    ) {
 2399        let focus_handle = panel.panel_focus_handle(cx);
 2400        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2401            .detach();
 2402
 2403        let dock_position = panel.position(window, cx);
 2404        let dock = self.dock_at_position(dock_position);
 2405        let any_panel = panel.to_any();
 2406        let persisted_size_state =
 2407            self.persisted_panel_size_state(T::panel_key(), cx)
 2408                .or_else(|| {
 2409                    load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
 2410                        let state = dock::PanelSizeState {
 2411                            size: Some(size),
 2412                            flex: None,
 2413                        };
 2414                        self.persist_panel_size_state(T::panel_key(), state, cx);
 2415                        state
 2416                    })
 2417                });
 2418
 2419        dock.update(cx, |dock, cx| {
 2420            let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
 2421            if let Some(size_state) = persisted_size_state {
 2422                dock.set_panel_size_state(&panel, size_state, cx);
 2423            }
 2424            index
 2425        });
 2426
 2427        cx.emit(Event::PanelAdded(any_panel));
 2428    }
 2429
 2430    pub fn remove_panel<T: Panel>(
 2431        &mut self,
 2432        panel: &Entity<T>,
 2433        window: &mut Window,
 2434        cx: &mut Context<Self>,
 2435    ) {
 2436        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2437            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2438        }
 2439    }
 2440
 2441    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2442        &self.status_bar
 2443    }
 2444
 2445    pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
 2446        self.sidebar_focus_handle = handle;
 2447    }
 2448
 2449    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2450        StatusBarSettings::get_global(cx).show
 2451    }
 2452
 2453    pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
 2454        self.multi_workspace.as_ref()
 2455    }
 2456
 2457    pub fn set_multi_workspace(
 2458        &mut self,
 2459        multi_workspace: WeakEntity<MultiWorkspace>,
 2460        cx: &mut App,
 2461    ) {
 2462        self.status_bar.update(cx, |status_bar, cx| {
 2463            status_bar.set_multi_workspace(multi_workspace.clone(), cx);
 2464        });
 2465        self.multi_workspace = Some(multi_workspace);
 2466    }
 2467
 2468    pub fn app_state(&self) -> &Arc<AppState> {
 2469        &self.app_state
 2470    }
 2471
 2472    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2473        self._panels_task = Some(task);
 2474    }
 2475
 2476    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2477        self._panels_task.take()
 2478    }
 2479
 2480    pub fn user_store(&self) -> &Entity<UserStore> {
 2481        &self.app_state.user_store
 2482    }
 2483
 2484    pub fn project(&self) -> &Entity<Project> {
 2485        &self.project
 2486    }
 2487
 2488    pub fn path_style(&self, cx: &App) -> PathStyle {
 2489        self.project.read(cx).path_style(cx)
 2490    }
 2491
 2492    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2493        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2494
 2495        for pane_handle in &self.panes {
 2496            let pane = pane_handle.read(cx);
 2497
 2498            for entry in pane.activation_history() {
 2499                history.insert(
 2500                    entry.entity_id,
 2501                    history
 2502                        .get(&entry.entity_id)
 2503                        .cloned()
 2504                        .unwrap_or(0)
 2505                        .max(entry.timestamp),
 2506                );
 2507            }
 2508        }
 2509
 2510        history
 2511    }
 2512
 2513    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2514        let mut recent_item: Option<Entity<T>> = None;
 2515        let mut recent_timestamp = 0;
 2516        for pane_handle in &self.panes {
 2517            let pane = pane_handle.read(cx);
 2518            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2519                pane.items().map(|item| (item.item_id(), item)).collect();
 2520            for entry in pane.activation_history() {
 2521                if entry.timestamp > recent_timestamp
 2522                    && let Some(&item) = item_map.get(&entry.entity_id)
 2523                    && let Some(typed_item) = item.act_as::<T>(cx)
 2524                {
 2525                    recent_timestamp = entry.timestamp;
 2526                    recent_item = Some(typed_item);
 2527                }
 2528            }
 2529        }
 2530        recent_item
 2531    }
 2532
 2533    pub fn recent_navigation_history_iter(
 2534        &self,
 2535        cx: &App,
 2536    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2537        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2538        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2539
 2540        for pane in &self.panes {
 2541            let pane = pane.read(cx);
 2542
 2543            pane.nav_history()
 2544                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2545                    if let Some(fs_path) = &fs_path {
 2546                        abs_paths_opened
 2547                            .entry(fs_path.clone())
 2548                            .or_default()
 2549                            .insert(project_path.clone());
 2550                    }
 2551                    let timestamp = entry.timestamp;
 2552                    match history.entry(project_path) {
 2553                        hash_map::Entry::Occupied(mut entry) => {
 2554                            let (_, old_timestamp) = entry.get();
 2555                            if &timestamp > old_timestamp {
 2556                                entry.insert((fs_path, timestamp));
 2557                            }
 2558                        }
 2559                        hash_map::Entry::Vacant(entry) => {
 2560                            entry.insert((fs_path, timestamp));
 2561                        }
 2562                    }
 2563                });
 2564
 2565            if let Some(item) = pane.active_item()
 2566                && let Some(project_path) = item.project_path(cx)
 2567            {
 2568                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2569
 2570                if let Some(fs_path) = &fs_path {
 2571                    abs_paths_opened
 2572                        .entry(fs_path.clone())
 2573                        .or_default()
 2574                        .insert(project_path.clone());
 2575                }
 2576
 2577                history.insert(project_path, (fs_path, std::usize::MAX));
 2578            }
 2579        }
 2580
 2581        history
 2582            .into_iter()
 2583            .sorted_by_key(|(_, (_, order))| *order)
 2584            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2585            .rev()
 2586            .filter(move |(history_path, abs_path)| {
 2587                let latest_project_path_opened = abs_path
 2588                    .as_ref()
 2589                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2590                    .and_then(|project_paths| {
 2591                        project_paths
 2592                            .iter()
 2593                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2594                    });
 2595
 2596                latest_project_path_opened.is_none_or(|path| path == history_path)
 2597            })
 2598    }
 2599
 2600    pub fn recent_navigation_history(
 2601        &self,
 2602        limit: Option<usize>,
 2603        cx: &App,
 2604    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2605        self.recent_navigation_history_iter(cx)
 2606            .take(limit.unwrap_or(usize::MAX))
 2607            .collect()
 2608    }
 2609
 2610    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2611        for pane in &self.panes {
 2612            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2613        }
 2614    }
 2615
 2616    fn navigate_history(
 2617        &mut self,
 2618        pane: WeakEntity<Pane>,
 2619        mode: NavigationMode,
 2620        window: &mut Window,
 2621        cx: &mut Context<Workspace>,
 2622    ) -> Task<Result<()>> {
 2623        self.navigate_history_impl(
 2624            pane,
 2625            mode,
 2626            window,
 2627            &mut |history, cx| history.pop(mode, cx),
 2628            cx,
 2629        )
 2630    }
 2631
 2632    fn navigate_tag_history(
 2633        &mut self,
 2634        pane: WeakEntity<Pane>,
 2635        mode: TagNavigationMode,
 2636        window: &mut Window,
 2637        cx: &mut Context<Workspace>,
 2638    ) -> Task<Result<()>> {
 2639        self.navigate_history_impl(
 2640            pane,
 2641            NavigationMode::Normal,
 2642            window,
 2643            &mut |history, _cx| history.pop_tag(mode),
 2644            cx,
 2645        )
 2646    }
 2647
 2648    fn navigate_history_impl(
 2649        &mut self,
 2650        pane: WeakEntity<Pane>,
 2651        mode: NavigationMode,
 2652        window: &mut Window,
 2653        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2654        cx: &mut Context<Workspace>,
 2655    ) -> Task<Result<()>> {
 2656        let to_load = if let Some(pane) = pane.upgrade() {
 2657            pane.update(cx, |pane, cx| {
 2658                window.focus(&pane.focus_handle(cx), cx);
 2659                loop {
 2660                    // Retrieve the weak item handle from the history.
 2661                    let entry = cb(pane.nav_history_mut(), cx)?;
 2662
 2663                    // If the item is still present in this pane, then activate it.
 2664                    if let Some(index) = entry
 2665                        .item
 2666                        .upgrade()
 2667                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2668                    {
 2669                        let prev_active_item_index = pane.active_item_index();
 2670                        pane.nav_history_mut().set_mode(mode);
 2671                        pane.activate_item(index, true, true, window, cx);
 2672                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2673
 2674                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2675                        if let Some(data) = entry.data {
 2676                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2677                        }
 2678
 2679                        if navigated {
 2680                            break None;
 2681                        }
 2682                    } else {
 2683                        // If the item is no longer present in this pane, then retrieve its
 2684                        // path info in order to reopen it.
 2685                        break pane
 2686                            .nav_history()
 2687                            .path_for_item(entry.item.id())
 2688                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2689                    }
 2690                }
 2691            })
 2692        } else {
 2693            None
 2694        };
 2695
 2696        if let Some((project_path, abs_path, entry)) = to_load {
 2697            // If the item was no longer present, then load it again from its previous path, first try the local path
 2698            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2699
 2700            cx.spawn_in(window, async move  |workspace, cx| {
 2701                let open_by_project_path = open_by_project_path.await;
 2702                let mut navigated = false;
 2703                match open_by_project_path
 2704                    .with_context(|| format!("Navigating to {project_path:?}"))
 2705                {
 2706                    Ok((project_entry_id, build_item)) => {
 2707                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2708                            pane.nav_history_mut().set_mode(mode);
 2709                            pane.active_item().map(|p| p.item_id())
 2710                        })?;
 2711
 2712                        pane.update_in(cx, |pane, window, cx| {
 2713                            let item = pane.open_item(
 2714                                project_entry_id,
 2715                                project_path,
 2716                                true,
 2717                                entry.is_preview,
 2718                                true,
 2719                                None,
 2720                                window, cx,
 2721                                build_item,
 2722                            );
 2723                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2724                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2725                            if let Some(data) = entry.data {
 2726                                navigated |= item.navigate(data, window, cx);
 2727                            }
 2728                        })?;
 2729                    }
 2730                    Err(open_by_project_path_e) => {
 2731                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2732                        // and its worktree is now dropped
 2733                        if let Some(abs_path) = abs_path {
 2734                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2735                                pane.nav_history_mut().set_mode(mode);
 2736                                pane.active_item().map(|p| p.item_id())
 2737                            })?;
 2738                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2739                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2740                            })?;
 2741                            match open_by_abs_path
 2742                                .await
 2743                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2744                            {
 2745                                Ok(item) => {
 2746                                    pane.update_in(cx, |pane, window, cx| {
 2747                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2748                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2749                                        if let Some(data) = entry.data {
 2750                                            navigated |= item.navigate(data, window, cx);
 2751                                        }
 2752                                    })?;
 2753                                }
 2754                                Err(open_by_abs_path_e) => {
 2755                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2756                                }
 2757                            }
 2758                        }
 2759                    }
 2760                }
 2761
 2762                if !navigated {
 2763                    workspace
 2764                        .update_in(cx, |workspace, window, cx| {
 2765                            Self::navigate_history(workspace, pane, mode, window, cx)
 2766                        })?
 2767                        .await?;
 2768                }
 2769
 2770                Ok(())
 2771            })
 2772        } else {
 2773            Task::ready(Ok(()))
 2774        }
 2775    }
 2776
 2777    pub fn go_back(
 2778        &mut self,
 2779        pane: WeakEntity<Pane>,
 2780        window: &mut Window,
 2781        cx: &mut Context<Workspace>,
 2782    ) -> Task<Result<()>> {
 2783        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2784    }
 2785
 2786    pub fn go_forward(
 2787        &mut self,
 2788        pane: WeakEntity<Pane>,
 2789        window: &mut Window,
 2790        cx: &mut Context<Workspace>,
 2791    ) -> Task<Result<()>> {
 2792        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2793    }
 2794
 2795    pub fn reopen_closed_item(
 2796        &mut self,
 2797        window: &mut Window,
 2798        cx: &mut Context<Workspace>,
 2799    ) -> Task<Result<()>> {
 2800        self.navigate_history(
 2801            self.active_pane().downgrade(),
 2802            NavigationMode::ReopeningClosedItem,
 2803            window,
 2804            cx,
 2805        )
 2806    }
 2807
 2808    pub fn client(&self) -> &Arc<Client> {
 2809        &self.app_state.client
 2810    }
 2811
 2812    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2813        self.titlebar_item = Some(item);
 2814        cx.notify();
 2815    }
 2816
 2817    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2818        self.on_prompt_for_new_path = Some(prompt)
 2819    }
 2820
 2821    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2822        self.on_prompt_for_open_path = Some(prompt)
 2823    }
 2824
 2825    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2826        self.terminal_provider = Some(Box::new(provider));
 2827    }
 2828
 2829    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2830        self.debugger_provider = Some(Arc::new(provider));
 2831    }
 2832
 2833    pub fn set_open_in_dev_container(&mut self, value: bool) {
 2834        self.open_in_dev_container = value;
 2835    }
 2836
 2837    pub fn open_in_dev_container(&self) -> bool {
 2838        self.open_in_dev_container
 2839    }
 2840
 2841    pub fn set_dev_container_task(&mut self, task: Task<Result<()>>) {
 2842        self._dev_container_task = Some(task);
 2843    }
 2844
 2845    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2846        self.debugger_provider.clone()
 2847    }
 2848
 2849    pub fn prompt_for_open_path(
 2850        &mut self,
 2851        path_prompt_options: PathPromptOptions,
 2852        lister: DirectoryLister,
 2853        window: &mut Window,
 2854        cx: &mut Context<Self>,
 2855    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2856        // TODO: If `on_prompt_for_open_path` is set, we should always use it
 2857        // rather than gating on `use_system_path_prompts`. This would let tests
 2858        // inject a mock without also having to disable the setting.
 2859        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2860            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2861            let rx = prompt(self, lister, window, cx);
 2862            self.on_prompt_for_open_path = Some(prompt);
 2863            rx
 2864        } else {
 2865            let (tx, rx) = oneshot::channel();
 2866            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2867
 2868            cx.spawn_in(window, async move |workspace, cx| {
 2869                let Ok(result) = abs_path.await else {
 2870                    return Ok(());
 2871                };
 2872
 2873                match result {
 2874                    Ok(result) => {
 2875                        tx.send(result).ok();
 2876                    }
 2877                    Err(err) => {
 2878                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2879                            workspace.show_portal_error(err.to_string(), cx);
 2880                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2881                            let rx = prompt(workspace, lister, window, cx);
 2882                            workspace.on_prompt_for_open_path = Some(prompt);
 2883                            rx
 2884                        })?;
 2885                        if let Ok(path) = rx.await {
 2886                            tx.send(path).ok();
 2887                        }
 2888                    }
 2889                };
 2890                anyhow::Ok(())
 2891            })
 2892            .detach();
 2893
 2894            rx
 2895        }
 2896    }
 2897
 2898    pub fn prompt_for_new_path(
 2899        &mut self,
 2900        lister: DirectoryLister,
 2901        suggested_name: Option<String>,
 2902        window: &mut Window,
 2903        cx: &mut Context<Self>,
 2904    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2905        if self.project.read(cx).is_via_collab()
 2906            || self.project.read(cx).is_via_remote_server()
 2907            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2908        {
 2909            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2910            let rx = prompt(self, lister, suggested_name, window, cx);
 2911            self.on_prompt_for_new_path = Some(prompt);
 2912            return rx;
 2913        }
 2914
 2915        let (tx, rx) = oneshot::channel();
 2916        cx.spawn_in(window, async move |workspace, cx| {
 2917            let abs_path = workspace.update(cx, |workspace, cx| {
 2918                let relative_to = workspace
 2919                    .most_recent_active_path(cx)
 2920                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2921                    .or_else(|| {
 2922                        let project = workspace.project.read(cx);
 2923                        project.visible_worktrees(cx).find_map(|worktree| {
 2924                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2925                        })
 2926                    })
 2927                    .or_else(std::env::home_dir)
 2928                    .unwrap_or_else(|| PathBuf::from(""));
 2929                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2930            })?;
 2931            let abs_path = match abs_path.await? {
 2932                Ok(path) => path,
 2933                Err(err) => {
 2934                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2935                        workspace.show_portal_error(err.to_string(), cx);
 2936
 2937                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2938                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2939                        workspace.on_prompt_for_new_path = Some(prompt);
 2940                        rx
 2941                    })?;
 2942                    if let Ok(path) = rx.await {
 2943                        tx.send(path).ok();
 2944                    }
 2945                    return anyhow::Ok(());
 2946                }
 2947            };
 2948
 2949            tx.send(abs_path.map(|path| vec![path])).ok();
 2950            anyhow::Ok(())
 2951        })
 2952        .detach();
 2953
 2954        rx
 2955    }
 2956
 2957    pub fn titlebar_item(&self) -> Option<AnyView> {
 2958        self.titlebar_item.clone()
 2959    }
 2960
 2961    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2962    ///
 2963    /// If the given workspace has a local project, then it will be passed
 2964    /// to the callback. Otherwise, a new empty window will be created.
 2965    pub fn with_local_workspace<T, F>(
 2966        &mut self,
 2967        window: &mut Window,
 2968        cx: &mut Context<Self>,
 2969        callback: F,
 2970    ) -> Task<Result<T>>
 2971    where
 2972        T: 'static,
 2973        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2974    {
 2975        if self.project.read(cx).is_local() {
 2976            Task::ready(Ok(callback(self, window, cx)))
 2977        } else {
 2978            let env = self.project.read(cx).cli_environment(cx);
 2979            let task = Self::new_local(
 2980                Vec::new(),
 2981                self.app_state.clone(),
 2982                None,
 2983                env,
 2984                None,
 2985                OpenMode::Activate,
 2986                cx,
 2987            );
 2988            cx.spawn_in(window, async move |_vh, cx| {
 2989                let OpenResult {
 2990                    window: multi_workspace_window,
 2991                    ..
 2992                } = task.await?;
 2993                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2994                    let workspace = multi_workspace.workspace().clone();
 2995                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2996                })
 2997            })
 2998        }
 2999    }
 3000
 3001    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 3002    ///
 3003    /// If the given workspace has a local project, then it will be passed
 3004    /// to the callback. Otherwise, a new empty window will be created.
 3005    pub fn with_local_or_wsl_workspace<T, F>(
 3006        &mut self,
 3007        window: &mut Window,
 3008        cx: &mut Context<Self>,
 3009        callback: F,
 3010    ) -> Task<Result<T>>
 3011    where
 3012        T: 'static,
 3013        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 3014    {
 3015        let project = self.project.read(cx);
 3016        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 3017            Task::ready(Ok(callback(self, window, cx)))
 3018        } else {
 3019            let env = self.project.read(cx).cli_environment(cx);
 3020            let task = Self::new_local(
 3021                Vec::new(),
 3022                self.app_state.clone(),
 3023                None,
 3024                env,
 3025                None,
 3026                OpenMode::Activate,
 3027                cx,
 3028            );
 3029            cx.spawn_in(window, async move |_vh, cx| {
 3030                let OpenResult {
 3031                    window: multi_workspace_window,
 3032                    ..
 3033                } = task.await?;
 3034                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 3035                    let workspace = multi_workspace.workspace().clone();
 3036                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 3037                })
 3038            })
 3039        }
 3040    }
 3041
 3042    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3043        self.project.read(cx).worktrees(cx)
 3044    }
 3045
 3046    pub fn visible_worktrees<'a>(
 3047        &self,
 3048        cx: &'a App,
 3049    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3050        self.project.read(cx).visible_worktrees(cx)
 3051    }
 3052
 3053    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 3054        let futures = self
 3055            .worktrees(cx)
 3056            .filter_map(|worktree| worktree.read(cx).as_local())
 3057            .map(|worktree| worktree.scan_complete())
 3058            .collect::<Vec<_>>();
 3059        async move {
 3060            for future in futures {
 3061                future.await;
 3062            }
 3063        }
 3064    }
 3065
 3066    pub fn close_global(cx: &mut App) {
 3067        cx.defer(|cx| {
 3068            cx.windows().iter().find(|window| {
 3069                window
 3070                    .update(cx, |_, window, _| {
 3071                        if window.is_window_active() {
 3072                            //This can only get called when the window's project connection has been lost
 3073                            //so we don't need to prompt the user for anything and instead just close the window
 3074                            window.remove_window();
 3075                            true
 3076                        } else {
 3077                            false
 3078                        }
 3079                    })
 3080                    .unwrap_or(false)
 3081            });
 3082        });
 3083    }
 3084
 3085    pub fn move_focused_panel_to_next_position(
 3086        &mut self,
 3087        _: &MoveFocusedPanelToNextPosition,
 3088        window: &mut Window,
 3089        cx: &mut Context<Self>,
 3090    ) {
 3091        let docks = self.all_docks();
 3092        let active_dock = docks
 3093            .into_iter()
 3094            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 3095
 3096        if let Some(dock) = active_dock {
 3097            dock.update(cx, |dock, cx| {
 3098                let active_panel = dock
 3099                    .active_panel()
 3100                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 3101
 3102                if let Some(panel) = active_panel {
 3103                    panel.move_to_next_position(window, cx);
 3104                }
 3105            })
 3106        }
 3107    }
 3108
 3109    pub fn prepare_to_close(
 3110        &mut self,
 3111        close_intent: CloseIntent,
 3112        window: &mut Window,
 3113        cx: &mut Context<Self>,
 3114    ) -> Task<Result<bool>> {
 3115        let active_call = self.active_global_call();
 3116
 3117        cx.spawn_in(window, async move |this, cx| {
 3118            this.update(cx, |this, _| {
 3119                if close_intent == CloseIntent::CloseWindow {
 3120                    this.removing = true;
 3121                }
 3122            })?;
 3123
 3124            let workspace_count = cx.update(|_window, cx| {
 3125                cx.windows()
 3126                    .iter()
 3127                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 3128                    .count()
 3129            })?;
 3130
 3131            #[cfg(target_os = "macos")]
 3132            let save_last_workspace = false;
 3133
 3134            // On Linux and Windows, closing the last window should restore the last workspace.
 3135            #[cfg(not(target_os = "macos"))]
 3136            let save_last_workspace = {
 3137                let remaining_workspaces = cx.update(|_window, cx| {
 3138                    cx.windows()
 3139                        .iter()
 3140                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 3141                        .filter_map(|multi_workspace| {
 3142                            multi_workspace
 3143                                .update(cx, |multi_workspace, _, cx| {
 3144                                    multi_workspace.workspace().read(cx).removing
 3145                                })
 3146                                .ok()
 3147                        })
 3148                        .filter(|removing| !removing)
 3149                        .count()
 3150                })?;
 3151
 3152                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 3153            };
 3154
 3155            if let Some(active_call) = active_call
 3156                && workspace_count == 1
 3157                && cx
 3158                    .update(|_window, cx| active_call.0.is_in_room(cx))
 3159                    .unwrap_or(false)
 3160            {
 3161                if close_intent == CloseIntent::CloseWindow {
 3162                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3163                    let answer = cx.update(|window, cx| {
 3164                        window.prompt(
 3165                            PromptLevel::Warning,
 3166                            "Do you want to leave the current call?",
 3167                            None,
 3168                            &["Close window and hang up", "Cancel"],
 3169                            cx,
 3170                        )
 3171                    })?;
 3172
 3173                    if answer.await.log_err() == Some(1) {
 3174                        return anyhow::Ok(false);
 3175                    } else {
 3176                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 3177                            task.await.log_err();
 3178                        }
 3179                    }
 3180                }
 3181                if close_intent == CloseIntent::ReplaceWindow {
 3182                    _ = cx.update(|_window, cx| {
 3183                        let multi_workspace = cx
 3184                            .windows()
 3185                            .iter()
 3186                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 3187                            .next()
 3188                            .unwrap();
 3189                        let project = multi_workspace
 3190                            .read(cx)?
 3191                            .workspace()
 3192                            .read(cx)
 3193                            .project
 3194                            .clone();
 3195                        if project.read(cx).is_shared() {
 3196                            active_call.0.unshare_project(project, cx)?;
 3197                        }
 3198                        Ok::<_, anyhow::Error>(())
 3199                    });
 3200                }
 3201            }
 3202
 3203            let save_result = this
 3204                .update_in(cx, |this, window, cx| {
 3205                    this.save_all_internal(SaveIntent::Close, window, cx)
 3206                })?
 3207                .await;
 3208
 3209            // If we're not quitting, but closing, we remove the workspace from
 3210            // the current session.
 3211            if close_intent != CloseIntent::Quit
 3212                && !save_last_workspace
 3213                && save_result.as_ref().is_ok_and(|&res| res)
 3214            {
 3215                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 3216                    .await;
 3217            }
 3218
 3219            save_result
 3220        })
 3221    }
 3222
 3223    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 3224        self.save_all_internal(
 3225            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 3226            window,
 3227            cx,
 3228        )
 3229        .detach_and_log_err(cx);
 3230    }
 3231
 3232    fn send_keystrokes(
 3233        &mut self,
 3234        action: &SendKeystrokes,
 3235        window: &mut Window,
 3236        cx: &mut Context<Self>,
 3237    ) {
 3238        let keystrokes: Vec<Keystroke> = action
 3239            .0
 3240            .split(' ')
 3241            .flat_map(|k| Keystroke::parse(k).log_err())
 3242            .map(|k| {
 3243                cx.keyboard_mapper()
 3244                    .map_key_equivalent(k, false)
 3245                    .inner()
 3246                    .clone()
 3247            })
 3248            .collect();
 3249        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 3250    }
 3251
 3252    pub fn send_keystrokes_impl(
 3253        &mut self,
 3254        keystrokes: Vec<Keystroke>,
 3255        window: &mut Window,
 3256        cx: &mut Context<Self>,
 3257    ) -> Shared<Task<()>> {
 3258        let mut state = self.dispatching_keystrokes.borrow_mut();
 3259        if !state.dispatched.insert(keystrokes.clone()) {
 3260            cx.propagate();
 3261            return state.task.clone().unwrap();
 3262        }
 3263
 3264        state.queue.extend(keystrokes);
 3265
 3266        let keystrokes = self.dispatching_keystrokes.clone();
 3267        if state.task.is_none() {
 3268            state.task = Some(
 3269                window
 3270                    .spawn(cx, async move |cx| {
 3271                        // limit to 100 keystrokes to avoid infinite recursion.
 3272                        for _ in 0..100 {
 3273                            let keystroke = {
 3274                                let mut state = keystrokes.borrow_mut();
 3275                                let Some(keystroke) = state.queue.pop_front() else {
 3276                                    state.dispatched.clear();
 3277                                    state.task.take();
 3278                                    return;
 3279                                };
 3280                                keystroke
 3281                            };
 3282                            cx.update(|window, cx| {
 3283                                let focused = window.focused(cx);
 3284                                window.dispatch_keystroke(keystroke.clone(), cx);
 3285                                if window.focused(cx) != focused {
 3286                                    // dispatch_keystroke may cause the focus to change.
 3287                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3288                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 3289                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 3290                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3291                                    // )
 3292                                    window.draw(cx).clear();
 3293                                }
 3294                            })
 3295                            .ok();
 3296
 3297                            // Yield between synthetic keystrokes so deferred focus and
 3298                            // other effects can settle before dispatching the next key.
 3299                            yield_now().await;
 3300                        }
 3301
 3302                        *keystrokes.borrow_mut() = Default::default();
 3303                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3304                    })
 3305                    .shared(),
 3306            );
 3307        }
 3308        state.task.clone().unwrap()
 3309    }
 3310
 3311    /// Prompts the user to save or discard each dirty item, returning
 3312    /// `true` if they confirmed (saved/discarded everything) or `false`
 3313    /// if they cancelled. Used before removing worktree roots during
 3314    /// thread archival.
 3315    pub fn prompt_to_save_or_discard_dirty_items(
 3316        &mut self,
 3317        window: &mut Window,
 3318        cx: &mut Context<Self>,
 3319    ) -> Task<Result<bool>> {
 3320        self.save_all_internal(SaveIntent::Close, window, cx)
 3321    }
 3322
 3323    fn save_all_internal(
 3324        &mut self,
 3325        mut save_intent: SaveIntent,
 3326        window: &mut Window,
 3327        cx: &mut Context<Self>,
 3328    ) -> Task<Result<bool>> {
 3329        if self.project.read(cx).is_disconnected(cx) {
 3330            return Task::ready(Ok(true));
 3331        }
 3332        let dirty_items = self
 3333            .panes
 3334            .iter()
 3335            .flat_map(|pane| {
 3336                pane.read(cx).items().filter_map(|item| {
 3337                    if item.is_dirty(cx) {
 3338                        item.tab_content_text(0, cx);
 3339                        Some((pane.downgrade(), item.boxed_clone()))
 3340                    } else {
 3341                        None
 3342                    }
 3343                })
 3344            })
 3345            .collect::<Vec<_>>();
 3346
 3347        let project = self.project.clone();
 3348        cx.spawn_in(window, async move |workspace, cx| {
 3349            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3350                let (serialize_tasks, remaining_dirty_items) =
 3351                    workspace.update_in(cx, |workspace, window, cx| {
 3352                        let mut remaining_dirty_items = Vec::new();
 3353                        let mut serialize_tasks = Vec::new();
 3354                        for (pane, item) in dirty_items {
 3355                            if let Some(task) = item
 3356                                .to_serializable_item_handle(cx)
 3357                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3358                            {
 3359                                serialize_tasks.push(task);
 3360                            } else {
 3361                                remaining_dirty_items.push((pane, item));
 3362                            }
 3363                        }
 3364                        (serialize_tasks, remaining_dirty_items)
 3365                    })?;
 3366
 3367                futures::future::try_join_all(serialize_tasks).await?;
 3368
 3369                if !remaining_dirty_items.is_empty() {
 3370                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3371                }
 3372
 3373                if remaining_dirty_items.len() > 1 {
 3374                    let answer = workspace.update_in(cx, |_, window, cx| {
 3375                        cx.emit(Event::Activate);
 3376                        let detail = Pane::file_names_for_prompt(
 3377                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3378                            cx,
 3379                        );
 3380                        window.prompt(
 3381                            PromptLevel::Warning,
 3382                            "Do you want to save all changes in the following files?",
 3383                            Some(&detail),
 3384                            &["Save all", "Discard all", "Cancel"],
 3385                            cx,
 3386                        )
 3387                    })?;
 3388                    match answer.await.log_err() {
 3389                        Some(0) => save_intent = SaveIntent::SaveAll,
 3390                        Some(1) => save_intent = SaveIntent::Skip,
 3391                        Some(2) => return Ok(false),
 3392                        _ => {}
 3393                    }
 3394                }
 3395
 3396                remaining_dirty_items
 3397            } else {
 3398                dirty_items
 3399            };
 3400
 3401            for (pane, item) in dirty_items {
 3402                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3403                    (
 3404                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3405                        item.project_entry_ids(cx),
 3406                    )
 3407                })?;
 3408                if (singleton || !project_entry_ids.is_empty())
 3409                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3410                {
 3411                    return Ok(false);
 3412                }
 3413            }
 3414            Ok(true)
 3415        })
 3416    }
 3417
 3418    pub fn open_workspace_for_paths(
 3419        &mut self,
 3420        // replace_current_window: bool,
 3421        mut open_mode: OpenMode,
 3422        paths: Vec<PathBuf>,
 3423        window: &mut Window,
 3424        cx: &mut Context<Self>,
 3425    ) -> Task<Result<Entity<Workspace>>> {
 3426        let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
 3427        let is_remote = self.project.read(cx).is_via_collab();
 3428        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3429        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3430
 3431        let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
 3432        if workspace_is_empty {
 3433            open_mode = OpenMode::Activate;
 3434        }
 3435
 3436        let app_state = self.app_state.clone();
 3437
 3438        cx.spawn(async move |_, cx| {
 3439            let OpenResult { workspace, .. } = cx
 3440                .update(|cx| {
 3441                    open_paths(
 3442                        &paths,
 3443                        app_state,
 3444                        OpenOptions {
 3445                            requesting_window,
 3446                            open_mode,
 3447                            ..Default::default()
 3448                        },
 3449                        cx,
 3450                    )
 3451                })
 3452                .await?;
 3453            Ok(workspace)
 3454        })
 3455    }
 3456
 3457    #[allow(clippy::type_complexity)]
 3458    pub fn open_paths(
 3459        &mut self,
 3460        mut abs_paths: Vec<PathBuf>,
 3461        options: OpenOptions,
 3462        pane: Option<WeakEntity<Pane>>,
 3463        window: &mut Window,
 3464        cx: &mut Context<Self>,
 3465    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3466        let fs = self.app_state.fs.clone();
 3467
 3468        let caller_ordered_abs_paths = abs_paths.clone();
 3469
 3470        // Sort the paths to ensure we add worktrees for parents before their children.
 3471        abs_paths.sort_unstable();
 3472        cx.spawn_in(window, async move |this, cx| {
 3473            let mut tasks = Vec::with_capacity(abs_paths.len());
 3474
 3475            for abs_path in &abs_paths {
 3476                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3477                    OpenVisible::All => Some(true),
 3478                    OpenVisible::None => Some(false),
 3479                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3480                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3481                        Some(None) => Some(true),
 3482                        None => None,
 3483                    },
 3484                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3485                        Some(Some(metadata)) => Some(metadata.is_dir),
 3486                        Some(None) => Some(false),
 3487                        None => None,
 3488                    },
 3489                };
 3490                let project_path = match visible {
 3491                    Some(visible) => match this
 3492                        .update(cx, |this, cx| {
 3493                            Workspace::project_path_for_path(
 3494                                this.project.clone(),
 3495                                abs_path,
 3496                                visible,
 3497                                cx,
 3498                            )
 3499                        })
 3500                        .log_err()
 3501                    {
 3502                        Some(project_path) => project_path.await.log_err(),
 3503                        None => None,
 3504                    },
 3505                    None => None,
 3506                };
 3507
 3508                let this = this.clone();
 3509                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3510                let fs = fs.clone();
 3511                let pane = pane.clone();
 3512                let task = cx.spawn(async move |cx| {
 3513                    let (_worktree, project_path) = project_path?;
 3514                    if fs.is_dir(&abs_path).await {
 3515                        // Opening a directory should not race to update the active entry.
 3516                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3517                        None
 3518                    } else {
 3519                        Some(
 3520                            this.update_in(cx, |this, window, cx| {
 3521                                this.open_path(
 3522                                    project_path,
 3523                                    pane,
 3524                                    options.focus.unwrap_or(true),
 3525                                    window,
 3526                                    cx,
 3527                                )
 3528                            })
 3529                            .ok()?
 3530                            .await,
 3531                        )
 3532                    }
 3533                });
 3534                tasks.push(task);
 3535            }
 3536
 3537            let results = futures::future::join_all(tasks).await;
 3538
 3539            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3540            let mut winner: Option<(PathBuf, bool)> = None;
 3541            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3542                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3543                    if !metadata.is_dir {
 3544                        winner = Some((abs_path, false));
 3545                        break;
 3546                    }
 3547                    if winner.is_none() {
 3548                        winner = Some((abs_path, true));
 3549                    }
 3550                } else if winner.is_none() {
 3551                    winner = Some((abs_path, false));
 3552                }
 3553            }
 3554
 3555            // Compute the winner entry id on the foreground thread and emit once, after all
 3556            // paths finish opening. This avoids races between concurrently-opening paths
 3557            // (directories in particular) and makes the resulting project panel selection
 3558            // deterministic.
 3559            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3560                'emit_winner: {
 3561                    let winner_abs_path: Arc<Path> =
 3562                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3563
 3564                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3565                        OpenVisible::All => true,
 3566                        OpenVisible::None => false,
 3567                        OpenVisible::OnlyFiles => !winner_is_dir,
 3568                        OpenVisible::OnlyDirectories => winner_is_dir,
 3569                    };
 3570
 3571                    let Some(worktree_task) = this
 3572                        .update(cx, |workspace, cx| {
 3573                            workspace.project.update(cx, |project, cx| {
 3574                                project.find_or_create_worktree(
 3575                                    winner_abs_path.as_ref(),
 3576                                    visible,
 3577                                    cx,
 3578                                )
 3579                            })
 3580                        })
 3581                        .ok()
 3582                    else {
 3583                        break 'emit_winner;
 3584                    };
 3585
 3586                    let Ok((worktree, _)) = worktree_task.await else {
 3587                        break 'emit_winner;
 3588                    };
 3589
 3590                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3591                        let worktree = worktree.read(cx);
 3592                        let worktree_abs_path = worktree.abs_path();
 3593                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3594                            worktree.root_entry()
 3595                        } else {
 3596                            winner_abs_path
 3597                                .strip_prefix(worktree_abs_path.as_ref())
 3598                                .ok()
 3599                                .and_then(|relative_path| {
 3600                                    let relative_path =
 3601                                        RelPath::new(relative_path, PathStyle::local())
 3602                                            .log_err()?;
 3603                                    worktree.entry_for_path(&relative_path)
 3604                                })
 3605                        }?;
 3606                        Some(entry.id)
 3607                    }) else {
 3608                        break 'emit_winner;
 3609                    };
 3610
 3611                    this.update(cx, |workspace, cx| {
 3612                        workspace.project.update(cx, |_, cx| {
 3613                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3614                        });
 3615                    })
 3616                    .ok();
 3617                }
 3618            }
 3619
 3620            results
 3621        })
 3622    }
 3623
 3624    pub fn open_resolved_path(
 3625        &mut self,
 3626        path: ResolvedPath,
 3627        window: &mut Window,
 3628        cx: &mut Context<Self>,
 3629    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3630        match path {
 3631            ResolvedPath::ProjectPath { project_path, .. } => {
 3632                self.open_path(project_path, None, true, window, cx)
 3633            }
 3634            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3635                PathBuf::from(path),
 3636                OpenOptions {
 3637                    visible: Some(OpenVisible::None),
 3638                    ..Default::default()
 3639                },
 3640                window,
 3641                cx,
 3642            ),
 3643        }
 3644    }
 3645
 3646    pub fn absolute_path_of_worktree(
 3647        &self,
 3648        worktree_id: WorktreeId,
 3649        cx: &mut Context<Self>,
 3650    ) -> Option<PathBuf> {
 3651        self.project
 3652            .read(cx)
 3653            .worktree_for_id(worktree_id, cx)
 3654            // TODO: use `abs_path` or `root_dir`
 3655            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3656    }
 3657
 3658    pub fn add_folder_to_project(
 3659        &mut self,
 3660        _: &AddFolderToProject,
 3661        window: &mut Window,
 3662        cx: &mut Context<Self>,
 3663    ) {
 3664        let project = self.project.read(cx);
 3665        if project.is_via_collab() {
 3666            self.show_error(
 3667                &anyhow!("You cannot add folders to someone else's project"),
 3668                cx,
 3669            );
 3670            return;
 3671        }
 3672        let paths = self.prompt_for_open_path(
 3673            PathPromptOptions {
 3674                files: false,
 3675                directories: true,
 3676                multiple: true,
 3677                prompt: None,
 3678            },
 3679            DirectoryLister::Project(self.project.clone()),
 3680            window,
 3681            cx,
 3682        );
 3683        cx.spawn_in(window, async move |this, cx| {
 3684            if let Some(paths) = paths.await.log_err().flatten() {
 3685                let results = this
 3686                    .update_in(cx, |this, window, cx| {
 3687                        this.open_paths(
 3688                            paths,
 3689                            OpenOptions {
 3690                                visible: Some(OpenVisible::All),
 3691                                ..Default::default()
 3692                            },
 3693                            None,
 3694                            window,
 3695                            cx,
 3696                        )
 3697                    })?
 3698                    .await;
 3699                for result in results.into_iter().flatten() {
 3700                    result.log_err();
 3701                }
 3702            }
 3703            anyhow::Ok(())
 3704        })
 3705        .detach_and_log_err(cx);
 3706    }
 3707
 3708    pub fn project_path_for_path(
 3709        project: Entity<Project>,
 3710        abs_path: &Path,
 3711        visible: bool,
 3712        cx: &mut App,
 3713    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3714        let entry = project.update(cx, |project, cx| {
 3715            project.find_or_create_worktree(abs_path, visible, cx)
 3716        });
 3717        cx.spawn(async move |cx| {
 3718            let (worktree, path) = entry.await?;
 3719            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3720            Ok((worktree, ProjectPath { worktree_id, path }))
 3721        })
 3722    }
 3723
 3724    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3725        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3726    }
 3727
 3728    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3729        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3730    }
 3731
 3732    pub fn items_of_type<'a, T: Item>(
 3733        &'a self,
 3734        cx: &'a App,
 3735    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3736        self.panes
 3737            .iter()
 3738            .flat_map(|pane| pane.read(cx).items_of_type())
 3739    }
 3740
 3741    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3742        self.active_pane().read(cx).active_item()
 3743    }
 3744
 3745    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3746        let item = self.active_item(cx)?;
 3747        item.to_any_view().downcast::<I>().ok()
 3748    }
 3749
 3750    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3751        self.active_item(cx).and_then(|item| item.project_path(cx))
 3752    }
 3753
 3754    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3755        self.recent_navigation_history_iter(cx)
 3756            .filter_map(|(path, abs_path)| {
 3757                let worktree = self
 3758                    .project
 3759                    .read(cx)
 3760                    .worktree_for_id(path.worktree_id, cx)?;
 3761                if worktree.read(cx).is_visible() {
 3762                    abs_path
 3763                } else {
 3764                    None
 3765                }
 3766            })
 3767            .next()
 3768    }
 3769
 3770    pub fn save_active_item(
 3771        &mut self,
 3772        save_intent: SaveIntent,
 3773        window: &mut Window,
 3774        cx: &mut App,
 3775    ) -> Task<Result<()>> {
 3776        let project = self.project.clone();
 3777        let pane = self.active_pane();
 3778        let item = pane.read(cx).active_item();
 3779        let pane = pane.downgrade();
 3780
 3781        window.spawn(cx, async move |cx| {
 3782            if let Some(item) = item {
 3783                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3784                    .await
 3785                    .map(|_| ())
 3786            } else {
 3787                Ok(())
 3788            }
 3789        })
 3790    }
 3791
 3792    pub fn close_inactive_items_and_panes(
 3793        &mut self,
 3794        action: &CloseInactiveTabsAndPanes,
 3795        window: &mut Window,
 3796        cx: &mut Context<Self>,
 3797    ) {
 3798        if let Some(task) = self.close_all_internal(
 3799            true,
 3800            action.save_intent.unwrap_or(SaveIntent::Close),
 3801            window,
 3802            cx,
 3803        ) {
 3804            task.detach_and_log_err(cx)
 3805        }
 3806    }
 3807
 3808    pub fn close_all_items_and_panes(
 3809        &mut self,
 3810        action: &CloseAllItemsAndPanes,
 3811        window: &mut Window,
 3812        cx: &mut Context<Self>,
 3813    ) {
 3814        if let Some(task) = self.close_all_internal(
 3815            false,
 3816            action.save_intent.unwrap_or(SaveIntent::Close),
 3817            window,
 3818            cx,
 3819        ) {
 3820            task.detach_and_log_err(cx)
 3821        }
 3822    }
 3823
 3824    /// Closes the active item across all panes.
 3825    pub fn close_item_in_all_panes(
 3826        &mut self,
 3827        action: &CloseItemInAllPanes,
 3828        window: &mut Window,
 3829        cx: &mut Context<Self>,
 3830    ) {
 3831        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3832            return;
 3833        };
 3834
 3835        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3836        let close_pinned = action.close_pinned;
 3837
 3838        if let Some(project_path) = active_item.project_path(cx) {
 3839            self.close_items_with_project_path(
 3840                &project_path,
 3841                save_intent,
 3842                close_pinned,
 3843                window,
 3844                cx,
 3845            );
 3846        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3847            let item_id = active_item.item_id();
 3848            self.active_pane().update(cx, |pane, cx| {
 3849                pane.close_item_by_id(item_id, save_intent, window, cx)
 3850                    .detach_and_log_err(cx);
 3851            });
 3852        }
 3853    }
 3854
 3855    /// Closes all items with the given project path across all panes.
 3856    pub fn close_items_with_project_path(
 3857        &mut self,
 3858        project_path: &ProjectPath,
 3859        save_intent: SaveIntent,
 3860        close_pinned: bool,
 3861        window: &mut Window,
 3862        cx: &mut Context<Self>,
 3863    ) {
 3864        let panes = self.panes().to_vec();
 3865        for pane in panes {
 3866            pane.update(cx, |pane, cx| {
 3867                pane.close_items_for_project_path(
 3868                    project_path,
 3869                    save_intent,
 3870                    close_pinned,
 3871                    window,
 3872                    cx,
 3873                )
 3874                .detach_and_log_err(cx);
 3875            });
 3876        }
 3877    }
 3878
 3879    fn close_all_internal(
 3880        &mut self,
 3881        retain_active_pane: bool,
 3882        save_intent: SaveIntent,
 3883        window: &mut Window,
 3884        cx: &mut Context<Self>,
 3885    ) -> Option<Task<Result<()>>> {
 3886        let current_pane = self.active_pane();
 3887
 3888        let mut tasks = Vec::new();
 3889
 3890        if retain_active_pane {
 3891            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3892                pane.close_other_items(
 3893                    &CloseOtherItems {
 3894                        save_intent: None,
 3895                        close_pinned: false,
 3896                    },
 3897                    None,
 3898                    window,
 3899                    cx,
 3900                )
 3901            });
 3902
 3903            tasks.push(current_pane_close);
 3904        }
 3905
 3906        for pane in self.panes() {
 3907            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3908                continue;
 3909            }
 3910
 3911            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3912                pane.close_all_items(
 3913                    &CloseAllItems {
 3914                        save_intent: Some(save_intent),
 3915                        close_pinned: false,
 3916                    },
 3917                    window,
 3918                    cx,
 3919                )
 3920            });
 3921
 3922            tasks.push(close_pane_items)
 3923        }
 3924
 3925        if tasks.is_empty() {
 3926            None
 3927        } else {
 3928            Some(cx.spawn_in(window, async move |_, _| {
 3929                for task in tasks {
 3930                    task.await?
 3931                }
 3932                Ok(())
 3933            }))
 3934        }
 3935    }
 3936
 3937    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3938        self.dock_at_position(position).read(cx).is_open()
 3939    }
 3940
 3941    pub fn toggle_dock(
 3942        &mut self,
 3943        dock_side: DockPosition,
 3944        window: &mut Window,
 3945        cx: &mut Context<Self>,
 3946    ) {
 3947        let mut focus_center = false;
 3948        let mut reveal_dock = false;
 3949
 3950        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3951        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3952
 3953        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3954            telemetry::event!(
 3955                "Panel Button Clicked",
 3956                name = panel.persistent_name(),
 3957                toggle_state = !was_visible
 3958            );
 3959        }
 3960        if was_visible {
 3961            self.save_open_dock_positions(cx);
 3962        }
 3963
 3964        let dock = self.dock_at_position(dock_side);
 3965        dock.update(cx, |dock, cx| {
 3966            dock.set_open(!was_visible, window, cx);
 3967
 3968            if dock.active_panel().is_none() {
 3969                let Some(panel_ix) = dock
 3970                    .first_enabled_panel_idx(cx)
 3971                    .log_with_level(log::Level::Info)
 3972                else {
 3973                    return;
 3974                };
 3975                dock.activate_panel(panel_ix, window, cx);
 3976            }
 3977
 3978            if let Some(active_panel) = dock.active_panel() {
 3979                if was_visible {
 3980                    if active_panel
 3981                        .panel_focus_handle(cx)
 3982                        .contains_focused(window, cx)
 3983                    {
 3984                        focus_center = true;
 3985                    }
 3986                } else {
 3987                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3988                    window.focus(focus_handle, cx);
 3989                    reveal_dock = true;
 3990                }
 3991            }
 3992        });
 3993
 3994        if reveal_dock {
 3995            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3996        }
 3997
 3998        if focus_center {
 3999            self.active_pane
 4000                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4001        }
 4002
 4003        cx.notify();
 4004        self.serialize_workspace(window, cx);
 4005    }
 4006
 4007    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 4008        self.all_docks().into_iter().find(|&dock| {
 4009            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 4010        })
 4011    }
 4012
 4013    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 4014        if let Some(dock) = self.active_dock(window, cx).cloned() {
 4015            self.save_open_dock_positions(cx);
 4016            dock.update(cx, |dock, cx| {
 4017                dock.set_open(false, window, cx);
 4018            });
 4019            return true;
 4020        }
 4021        false
 4022    }
 4023
 4024    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4025        self.save_open_dock_positions(cx);
 4026        for dock in self.all_docks() {
 4027            dock.update(cx, |dock, cx| {
 4028                dock.set_open(false, window, cx);
 4029            });
 4030        }
 4031
 4032        cx.focus_self(window);
 4033        cx.notify();
 4034        self.serialize_workspace(window, cx);
 4035    }
 4036
 4037    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 4038        self.all_docks()
 4039            .into_iter()
 4040            .filter_map(|dock| {
 4041                let dock_ref = dock.read(cx);
 4042                if dock_ref.is_open() {
 4043                    Some(dock_ref.position())
 4044                } else {
 4045                    None
 4046                }
 4047            })
 4048            .collect()
 4049    }
 4050
 4051    /// Saves the positions of currently open docks.
 4052    ///
 4053    /// Updates `last_open_dock_positions` with positions of all currently open
 4054    /// docks, to later be restored by the 'Toggle All Docks' action.
 4055    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 4056        let open_dock_positions = self.get_open_dock_positions(cx);
 4057        if !open_dock_positions.is_empty() {
 4058            self.last_open_dock_positions = open_dock_positions;
 4059        }
 4060    }
 4061
 4062    /// Toggles all docks between open and closed states.
 4063    ///
 4064    /// If any docks are open, closes all and remembers their positions. If all
 4065    /// docks are closed, restores the last remembered dock configuration.
 4066    fn toggle_all_docks(
 4067        &mut self,
 4068        _: &ToggleAllDocks,
 4069        window: &mut Window,
 4070        cx: &mut Context<Self>,
 4071    ) {
 4072        let open_dock_positions = self.get_open_dock_positions(cx);
 4073
 4074        if !open_dock_positions.is_empty() {
 4075            self.close_all_docks(window, cx);
 4076        } else if !self.last_open_dock_positions.is_empty() {
 4077            self.restore_last_open_docks(window, cx);
 4078        }
 4079    }
 4080
 4081    /// Reopens docks from the most recently remembered configuration.
 4082    ///
 4083    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 4084    /// and clears the stored positions.
 4085    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4086        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 4087
 4088        for position in positions_to_open {
 4089            let dock = self.dock_at_position(position);
 4090            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 4091        }
 4092
 4093        cx.focus_self(window);
 4094        cx.notify();
 4095        self.serialize_workspace(window, cx);
 4096    }
 4097
 4098    /// Transfer focus to the panel of the given type.
 4099    pub fn focus_panel<T: Panel>(
 4100        &mut self,
 4101        window: &mut Window,
 4102        cx: &mut Context<Self>,
 4103    ) -> Option<Entity<T>> {
 4104        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 4105        panel.to_any().downcast().ok()
 4106    }
 4107
 4108    /// Focus the panel of the given type if it isn't already focused. If it is
 4109    /// already focused, then transfer focus back to the workspace center.
 4110    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 4111    /// panel when transferring focus back to the center.
 4112    pub fn toggle_panel_focus<T: Panel>(
 4113        &mut self,
 4114        window: &mut Window,
 4115        cx: &mut Context<Self>,
 4116    ) -> bool {
 4117        let mut did_focus_panel = false;
 4118        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 4119            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 4120            did_focus_panel
 4121        });
 4122
 4123        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 4124            self.close_panel::<T>(window, cx);
 4125        }
 4126
 4127        telemetry::event!(
 4128            "Panel Button Clicked",
 4129            name = T::persistent_name(),
 4130            toggle_state = did_focus_panel
 4131        );
 4132
 4133        did_focus_panel
 4134    }
 4135
 4136    pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4137        if let Some(item) = self.active_item(cx) {
 4138            item.item_focus_handle(cx).focus(window, cx);
 4139        } else {
 4140            log::error!("Could not find a focus target when switching focus to the center panes",);
 4141        }
 4142    }
 4143
 4144    pub fn activate_panel_for_proto_id(
 4145        &mut self,
 4146        panel_id: PanelId,
 4147        window: &mut Window,
 4148        cx: &mut Context<Self>,
 4149    ) -> Option<Arc<dyn PanelHandle>> {
 4150        let mut panel = None;
 4151        for dock in self.all_docks() {
 4152            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 4153                panel = dock.update(cx, |dock, cx| {
 4154                    dock.activate_panel(panel_index, window, cx);
 4155                    dock.set_open(true, window, cx);
 4156                    dock.active_panel().cloned()
 4157                });
 4158                break;
 4159            }
 4160        }
 4161
 4162        if panel.is_some() {
 4163            cx.notify();
 4164            self.serialize_workspace(window, cx);
 4165        }
 4166
 4167        panel
 4168    }
 4169
 4170    /// Focus or unfocus the given panel type, depending on the given callback.
 4171    fn focus_or_unfocus_panel<T: Panel>(
 4172        &mut self,
 4173        window: &mut Window,
 4174        cx: &mut Context<Self>,
 4175        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 4176    ) -> Option<Arc<dyn PanelHandle>> {
 4177        let mut result_panel = None;
 4178        let mut serialize = false;
 4179        for dock in self.all_docks() {
 4180            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4181                let mut focus_center = false;
 4182                let panel = dock.update(cx, |dock, cx| {
 4183                    dock.activate_panel(panel_index, window, cx);
 4184
 4185                    let panel = dock.active_panel().cloned();
 4186                    if let Some(panel) = panel.as_ref() {
 4187                        if should_focus(&**panel, window, cx) {
 4188                            dock.set_open(true, window, cx);
 4189                            panel.panel_focus_handle(cx).focus(window, cx);
 4190                        } else {
 4191                            focus_center = true;
 4192                        }
 4193                    }
 4194                    panel
 4195                });
 4196
 4197                if focus_center {
 4198                    self.active_pane
 4199                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4200                }
 4201
 4202                result_panel = panel;
 4203                serialize = true;
 4204                break;
 4205            }
 4206        }
 4207
 4208        if serialize {
 4209            self.serialize_workspace(window, cx);
 4210        }
 4211
 4212        cx.notify();
 4213        result_panel
 4214    }
 4215
 4216    /// Open the panel of the given type
 4217    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4218        for dock in self.all_docks() {
 4219            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4220                dock.update(cx, |dock, cx| {
 4221                    dock.activate_panel(panel_index, window, cx);
 4222                    dock.set_open(true, window, cx);
 4223                });
 4224            }
 4225        }
 4226    }
 4227
 4228    /// Open the panel of the given type, dismissing any zoomed items that
 4229    /// would obscure it (e.g. a zoomed terminal).
 4230    pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4231        let dock_position = self.all_docks().iter().find_map(|dock| {
 4232            let dock = dock.read(cx);
 4233            dock.panel_index_for_type::<T>().map(|_| dock.position())
 4234        });
 4235        self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
 4236        self.open_panel::<T>(window, cx);
 4237    }
 4238
 4239    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 4240        for dock in self.all_docks().iter() {
 4241            dock.update(cx, |dock, cx| {
 4242                if dock.panel::<T>().is_some() {
 4243                    dock.set_open(false, window, cx)
 4244                }
 4245            })
 4246        }
 4247    }
 4248
 4249    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 4250        self.all_docks()
 4251            .iter()
 4252            .find_map(|dock| dock.read(cx).panel::<T>())
 4253    }
 4254
 4255    fn dismiss_zoomed_items_to_reveal(
 4256        &mut self,
 4257        dock_to_reveal: Option<DockPosition>,
 4258        window: &mut Window,
 4259        cx: &mut Context<Self>,
 4260    ) {
 4261        // If a center pane is zoomed, unzoom it.
 4262        for pane in &self.panes {
 4263            if pane != &self.active_pane || dock_to_reveal.is_some() {
 4264                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4265            }
 4266        }
 4267
 4268        // If another dock is zoomed, hide it.
 4269        let mut focus_center = false;
 4270        for dock in self.all_docks() {
 4271            dock.update(cx, |dock, cx| {
 4272                if Some(dock.position()) != dock_to_reveal
 4273                    && let Some(panel) = dock.active_panel()
 4274                    && panel.is_zoomed(window, cx)
 4275                {
 4276                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 4277                    dock.set_open(false, window, cx);
 4278                }
 4279            });
 4280        }
 4281
 4282        if focus_center {
 4283            self.active_pane
 4284                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4285        }
 4286
 4287        if self.zoomed_position != dock_to_reveal {
 4288            self.zoomed = None;
 4289            self.zoomed_position = None;
 4290            cx.emit(Event::ZoomChanged);
 4291        }
 4292
 4293        cx.notify();
 4294    }
 4295
 4296    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4297        let pane = cx.new(|cx| {
 4298            let mut pane = Pane::new(
 4299                self.weak_handle(),
 4300                self.project.clone(),
 4301                self.pane_history_timestamp.clone(),
 4302                None,
 4303                NewFile.boxed_clone(),
 4304                true,
 4305                window,
 4306                cx,
 4307            );
 4308            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4309            pane
 4310        });
 4311        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4312            .detach();
 4313        self.panes.push(pane.clone());
 4314
 4315        window.focus(&pane.focus_handle(cx), cx);
 4316
 4317        cx.emit(Event::PaneAdded(pane.clone()));
 4318        pane
 4319    }
 4320
 4321    pub fn add_item_to_center(
 4322        &mut self,
 4323        item: Box<dyn ItemHandle>,
 4324        window: &mut Window,
 4325        cx: &mut Context<Self>,
 4326    ) -> bool {
 4327        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4328            if let Some(center_pane) = center_pane.upgrade() {
 4329                center_pane.update(cx, |pane, cx| {
 4330                    pane.add_item(item, true, true, None, window, cx)
 4331                });
 4332                true
 4333            } else {
 4334                false
 4335            }
 4336        } else {
 4337            false
 4338        }
 4339    }
 4340
 4341    pub fn add_item_to_active_pane(
 4342        &mut self,
 4343        item: Box<dyn ItemHandle>,
 4344        destination_index: Option<usize>,
 4345        focus_item: bool,
 4346        window: &mut Window,
 4347        cx: &mut App,
 4348    ) {
 4349        self.add_item(
 4350            self.active_pane.clone(),
 4351            item,
 4352            destination_index,
 4353            false,
 4354            focus_item,
 4355            window,
 4356            cx,
 4357        )
 4358    }
 4359
 4360    pub fn add_item(
 4361        &mut self,
 4362        pane: Entity<Pane>,
 4363        item: Box<dyn ItemHandle>,
 4364        destination_index: Option<usize>,
 4365        activate_pane: bool,
 4366        focus_item: bool,
 4367        window: &mut Window,
 4368        cx: &mut App,
 4369    ) {
 4370        pane.update(cx, |pane, cx| {
 4371            pane.add_item(
 4372                item,
 4373                activate_pane,
 4374                focus_item,
 4375                destination_index,
 4376                window,
 4377                cx,
 4378            )
 4379        });
 4380    }
 4381
 4382    pub fn split_item(
 4383        &mut self,
 4384        split_direction: SplitDirection,
 4385        item: Box<dyn ItemHandle>,
 4386        window: &mut Window,
 4387        cx: &mut Context<Self>,
 4388    ) {
 4389        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4390        self.add_item(new_pane, item, None, true, true, window, cx);
 4391    }
 4392
 4393    pub fn open_abs_path(
 4394        &mut self,
 4395        abs_path: PathBuf,
 4396        options: OpenOptions,
 4397        window: &mut Window,
 4398        cx: &mut Context<Self>,
 4399    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4400        cx.spawn_in(window, async move |workspace, cx| {
 4401            let open_paths_task_result = workspace
 4402                .update_in(cx, |workspace, window, cx| {
 4403                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4404                })
 4405                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4406                .await;
 4407            anyhow::ensure!(
 4408                open_paths_task_result.len() == 1,
 4409                "open abs path {abs_path:?} task returned incorrect number of results"
 4410            );
 4411            match open_paths_task_result
 4412                .into_iter()
 4413                .next()
 4414                .expect("ensured single task result")
 4415            {
 4416                Some(open_result) => {
 4417                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4418                }
 4419                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4420            }
 4421        })
 4422    }
 4423
 4424    pub fn split_abs_path(
 4425        &mut self,
 4426        abs_path: PathBuf,
 4427        visible: bool,
 4428        window: &mut Window,
 4429        cx: &mut Context<Self>,
 4430    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4431        let project_path_task =
 4432            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4433        cx.spawn_in(window, async move |this, cx| {
 4434            let (_, path) = project_path_task.await?;
 4435            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4436                .await
 4437        })
 4438    }
 4439
 4440    pub fn open_path(
 4441        &mut self,
 4442        path: impl Into<ProjectPath>,
 4443        pane: Option<WeakEntity<Pane>>,
 4444        focus_item: bool,
 4445        window: &mut Window,
 4446        cx: &mut App,
 4447    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4448        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4449    }
 4450
 4451    pub fn open_path_preview(
 4452        &mut self,
 4453        path: impl Into<ProjectPath>,
 4454        pane: Option<WeakEntity<Pane>>,
 4455        focus_item: bool,
 4456        allow_preview: bool,
 4457        activate: bool,
 4458        window: &mut Window,
 4459        cx: &mut App,
 4460    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4461        let pane = pane.unwrap_or_else(|| {
 4462            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4463                self.panes
 4464                    .first()
 4465                    .expect("There must be an active pane")
 4466                    .downgrade()
 4467            })
 4468        });
 4469
 4470        let project_path = path.into();
 4471        let task = self.load_path(project_path.clone(), window, cx);
 4472        window.spawn(cx, async move |cx| {
 4473            let (project_entry_id, build_item) = task.await?;
 4474
 4475            pane.update_in(cx, |pane, window, cx| {
 4476                pane.open_item(
 4477                    project_entry_id,
 4478                    project_path,
 4479                    focus_item,
 4480                    allow_preview,
 4481                    activate,
 4482                    None,
 4483                    window,
 4484                    cx,
 4485                    build_item,
 4486                )
 4487            })
 4488        })
 4489    }
 4490
 4491    pub fn split_path(
 4492        &mut self,
 4493        path: impl Into<ProjectPath>,
 4494        window: &mut Window,
 4495        cx: &mut Context<Self>,
 4496    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4497        self.split_path_preview(path, false, None, window, cx)
 4498    }
 4499
 4500    pub fn split_path_preview(
 4501        &mut self,
 4502        path: impl Into<ProjectPath>,
 4503        allow_preview: bool,
 4504        split_direction: Option<SplitDirection>,
 4505        window: &mut Window,
 4506        cx: &mut Context<Self>,
 4507    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4508        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4509            self.panes
 4510                .first()
 4511                .expect("There must be an active pane")
 4512                .downgrade()
 4513        });
 4514
 4515        if let Member::Pane(center_pane) = &self.center.root
 4516            && center_pane.read(cx).items_len() == 0
 4517        {
 4518            return self.open_path(path, Some(pane), true, window, cx);
 4519        }
 4520
 4521        let project_path = path.into();
 4522        let task = self.load_path(project_path.clone(), window, cx);
 4523        cx.spawn_in(window, async move |this, cx| {
 4524            let (project_entry_id, build_item) = task.await?;
 4525            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4526                let pane = pane.upgrade()?;
 4527                let new_pane = this.split_pane(
 4528                    pane,
 4529                    split_direction.unwrap_or(SplitDirection::Right),
 4530                    window,
 4531                    cx,
 4532                );
 4533                new_pane.update(cx, |new_pane, cx| {
 4534                    Some(new_pane.open_item(
 4535                        project_entry_id,
 4536                        project_path,
 4537                        true,
 4538                        allow_preview,
 4539                        true,
 4540                        None,
 4541                        window,
 4542                        cx,
 4543                        build_item,
 4544                    ))
 4545                })
 4546            })
 4547            .map(|option| option.context("pane was dropped"))?
 4548        })
 4549    }
 4550
 4551    fn load_path(
 4552        &mut self,
 4553        path: ProjectPath,
 4554        window: &mut Window,
 4555        cx: &mut App,
 4556    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4557        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4558        registry.open_path(self.project(), &path, window, cx)
 4559    }
 4560
 4561    pub fn find_project_item<T>(
 4562        &self,
 4563        pane: &Entity<Pane>,
 4564        project_item: &Entity<T::Item>,
 4565        cx: &App,
 4566    ) -> Option<Entity<T>>
 4567    where
 4568        T: ProjectItem,
 4569    {
 4570        use project::ProjectItem as _;
 4571        let project_item = project_item.read(cx);
 4572        let entry_id = project_item.entry_id(cx);
 4573        let project_path = project_item.project_path(cx);
 4574
 4575        let mut item = None;
 4576        if let Some(entry_id) = entry_id {
 4577            item = pane.read(cx).item_for_entry(entry_id, cx);
 4578        }
 4579        if item.is_none()
 4580            && let Some(project_path) = project_path
 4581        {
 4582            item = pane.read(cx).item_for_path(project_path, cx);
 4583        }
 4584
 4585        item.and_then(|item| item.downcast::<T>())
 4586    }
 4587
 4588    pub fn is_project_item_open<T>(
 4589        &self,
 4590        pane: &Entity<Pane>,
 4591        project_item: &Entity<T::Item>,
 4592        cx: &App,
 4593    ) -> bool
 4594    where
 4595        T: ProjectItem,
 4596    {
 4597        self.find_project_item::<T>(pane, project_item, cx)
 4598            .is_some()
 4599    }
 4600
 4601    pub fn open_project_item<T>(
 4602        &mut self,
 4603        pane: Entity<Pane>,
 4604        project_item: Entity<T::Item>,
 4605        activate_pane: bool,
 4606        focus_item: bool,
 4607        keep_old_preview: bool,
 4608        allow_new_preview: bool,
 4609        window: &mut Window,
 4610        cx: &mut Context<Self>,
 4611    ) -> Entity<T>
 4612    where
 4613        T: ProjectItem,
 4614    {
 4615        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4616
 4617        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4618            if !keep_old_preview
 4619                && let Some(old_id) = old_item_id
 4620                && old_id != item.item_id()
 4621            {
 4622                // switching to a different item, so unpreview old active item
 4623                pane.update(cx, |pane, _| {
 4624                    pane.unpreview_item_if_preview(old_id);
 4625                });
 4626            }
 4627
 4628            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4629            if !allow_new_preview {
 4630                pane.update(cx, |pane, _| {
 4631                    pane.unpreview_item_if_preview(item.item_id());
 4632                });
 4633            }
 4634            return item;
 4635        }
 4636
 4637        let item = pane.update(cx, |pane, cx| {
 4638            cx.new(|cx| {
 4639                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4640            })
 4641        });
 4642        let mut destination_index = None;
 4643        pane.update(cx, |pane, cx| {
 4644            if !keep_old_preview && let Some(old_id) = old_item_id {
 4645                pane.unpreview_item_if_preview(old_id);
 4646            }
 4647            if allow_new_preview {
 4648                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4649            }
 4650        });
 4651
 4652        self.add_item(
 4653            pane,
 4654            Box::new(item.clone()),
 4655            destination_index,
 4656            activate_pane,
 4657            focus_item,
 4658            window,
 4659            cx,
 4660        );
 4661        item
 4662    }
 4663
 4664    pub fn open_shared_screen(
 4665        &mut self,
 4666        peer_id: PeerId,
 4667        window: &mut Window,
 4668        cx: &mut Context<Self>,
 4669    ) {
 4670        if let Some(shared_screen) =
 4671            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4672        {
 4673            self.active_pane.update(cx, |pane, cx| {
 4674                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4675            });
 4676        }
 4677    }
 4678
 4679    pub fn activate_item(
 4680        &mut self,
 4681        item: &dyn ItemHandle,
 4682        activate_pane: bool,
 4683        focus_item: bool,
 4684        window: &mut Window,
 4685        cx: &mut App,
 4686    ) -> bool {
 4687        let result = self.panes.iter().find_map(|pane| {
 4688            pane.read(cx)
 4689                .index_for_item(item)
 4690                .map(|ix| (pane.clone(), ix))
 4691        });
 4692        if let Some((pane, ix)) = result {
 4693            pane.update(cx, |pane, cx| {
 4694                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4695            });
 4696            true
 4697        } else {
 4698            false
 4699        }
 4700    }
 4701
 4702    fn activate_pane_at_index(
 4703        &mut self,
 4704        action: &ActivatePane,
 4705        window: &mut Window,
 4706        cx: &mut Context<Self>,
 4707    ) {
 4708        let panes = self.center.panes();
 4709        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4710            window.focus(&pane.focus_handle(cx), cx);
 4711        } else {
 4712            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4713                .detach();
 4714        }
 4715    }
 4716
 4717    fn move_item_to_pane_at_index(
 4718        &mut self,
 4719        action: &MoveItemToPane,
 4720        window: &mut Window,
 4721        cx: &mut Context<Self>,
 4722    ) {
 4723        let panes = self.center.panes();
 4724        let destination = match panes.get(action.destination) {
 4725            Some(&destination) => destination.clone(),
 4726            None => {
 4727                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4728                    return;
 4729                }
 4730                let direction = SplitDirection::Right;
 4731                let split_off_pane = self
 4732                    .find_pane_in_direction(direction, cx)
 4733                    .unwrap_or_else(|| self.active_pane.clone());
 4734                let new_pane = self.add_pane(window, cx);
 4735                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4736                new_pane
 4737            }
 4738        };
 4739
 4740        if action.clone {
 4741            if self
 4742                .active_pane
 4743                .read(cx)
 4744                .active_item()
 4745                .is_some_and(|item| item.can_split(cx))
 4746            {
 4747                clone_active_item(
 4748                    self.database_id(),
 4749                    &self.active_pane,
 4750                    &destination,
 4751                    action.focus,
 4752                    window,
 4753                    cx,
 4754                );
 4755                return;
 4756            }
 4757        }
 4758        move_active_item(
 4759            &self.active_pane,
 4760            &destination,
 4761            action.focus,
 4762            true,
 4763            window,
 4764            cx,
 4765        )
 4766    }
 4767
 4768    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4769        let panes = self.center.panes();
 4770        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4771            let next_ix = (ix + 1) % panes.len();
 4772            let next_pane = panes[next_ix].clone();
 4773            window.focus(&next_pane.focus_handle(cx), cx);
 4774        }
 4775    }
 4776
 4777    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4778        let panes = self.center.panes();
 4779        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4780            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4781            let prev_pane = panes[prev_ix].clone();
 4782            window.focus(&prev_pane.focus_handle(cx), cx);
 4783        }
 4784    }
 4785
 4786    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4787        let last_pane = self.center.last_pane();
 4788        window.focus(&last_pane.focus_handle(cx), cx);
 4789    }
 4790
 4791    pub fn activate_pane_in_direction(
 4792        &mut self,
 4793        direction: SplitDirection,
 4794        window: &mut Window,
 4795        cx: &mut App,
 4796    ) {
 4797        use ActivateInDirectionTarget as Target;
 4798        enum Origin {
 4799            Sidebar,
 4800            LeftDock,
 4801            RightDock,
 4802            BottomDock,
 4803            Center,
 4804        }
 4805
 4806        let origin: Origin = if self
 4807            .sidebar_focus_handle
 4808            .as_ref()
 4809            .is_some_and(|h| h.contains_focused(window, cx))
 4810        {
 4811            Origin::Sidebar
 4812        } else {
 4813            [
 4814                (&self.left_dock, Origin::LeftDock),
 4815                (&self.right_dock, Origin::RightDock),
 4816                (&self.bottom_dock, Origin::BottomDock),
 4817            ]
 4818            .into_iter()
 4819            .find_map(|(dock, origin)| {
 4820                if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4821                    Some(origin)
 4822                } else {
 4823                    None
 4824                }
 4825            })
 4826            .unwrap_or(Origin::Center)
 4827        };
 4828
 4829        let get_last_active_pane = || {
 4830            let pane = self
 4831                .last_active_center_pane
 4832                .clone()
 4833                .unwrap_or_else(|| {
 4834                    self.panes
 4835                        .first()
 4836                        .expect("There must be an active pane")
 4837                        .downgrade()
 4838                })
 4839                .upgrade()?;
 4840            (pane.read(cx).items_len() != 0).then_some(pane)
 4841        };
 4842
 4843        let try_dock =
 4844            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4845
 4846        let sidebar_target = self
 4847            .sidebar_focus_handle
 4848            .as_ref()
 4849            .map(|h| Target::Sidebar(h.clone()));
 4850
 4851        let sidebar_on_right = self
 4852            .multi_workspace
 4853            .as_ref()
 4854            .and_then(|mw| mw.upgrade())
 4855            .map_or(false, |mw| {
 4856                mw.read(cx).sidebar_side(cx) == SidebarSide::Right
 4857            });
 4858
 4859        let away_from_sidebar = if sidebar_on_right {
 4860            SplitDirection::Left
 4861        } else {
 4862            SplitDirection::Right
 4863        };
 4864
 4865        let (near_dock, far_dock) = if sidebar_on_right {
 4866            (&self.right_dock, &self.left_dock)
 4867        } else {
 4868            (&self.left_dock, &self.right_dock)
 4869        };
 4870
 4871        let target = match (origin, direction) {
 4872            (Origin::Sidebar, dir) if dir == away_from_sidebar => try_dock(near_dock)
 4873                .or_else(|| get_last_active_pane().map(Target::Pane))
 4874                .or_else(|| try_dock(&self.bottom_dock))
 4875                .or_else(|| try_dock(far_dock)),
 4876
 4877            (Origin::Sidebar, _) => None,
 4878
 4879            // We're in the center, so we first try to go to a different pane,
 4880            // otherwise try to go to a dock.
 4881            (Origin::Center, direction) => {
 4882                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4883                    Some(Target::Pane(pane))
 4884                } else {
 4885                    match direction {
 4886                        SplitDirection::Up => None,
 4887                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4888                        SplitDirection::Left => {
 4889                            let dock_target = try_dock(&self.left_dock);
 4890                            if sidebar_on_right {
 4891                                dock_target
 4892                            } else {
 4893                                dock_target.or(sidebar_target)
 4894                            }
 4895                        }
 4896                        SplitDirection::Right => {
 4897                            let dock_target = try_dock(&self.right_dock);
 4898                            if sidebar_on_right {
 4899                                dock_target.or(sidebar_target)
 4900                            } else {
 4901                                dock_target
 4902                            }
 4903                        }
 4904                    }
 4905                }
 4906            }
 4907
 4908            (Origin::LeftDock, SplitDirection::Right) => {
 4909                if let Some(last_active_pane) = get_last_active_pane() {
 4910                    Some(Target::Pane(last_active_pane))
 4911                } else {
 4912                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4913                }
 4914            }
 4915
 4916            (Origin::LeftDock, SplitDirection::Left) => {
 4917                if sidebar_on_right {
 4918                    None
 4919                } else {
 4920                    sidebar_target
 4921                }
 4922            }
 4923
 4924            (Origin::LeftDock, SplitDirection::Down)
 4925            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4926
 4927            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4928            (Origin::BottomDock, SplitDirection::Left) => {
 4929                let dock_target = try_dock(&self.left_dock);
 4930                if sidebar_on_right {
 4931                    dock_target
 4932                } else {
 4933                    dock_target.or(sidebar_target)
 4934                }
 4935            }
 4936            (Origin::BottomDock, SplitDirection::Right) => {
 4937                let dock_target = try_dock(&self.right_dock);
 4938                if sidebar_on_right {
 4939                    dock_target.or(sidebar_target)
 4940                } else {
 4941                    dock_target
 4942                }
 4943            }
 4944
 4945            (Origin::RightDock, SplitDirection::Left) => {
 4946                if let Some(last_active_pane) = get_last_active_pane() {
 4947                    Some(Target::Pane(last_active_pane))
 4948                } else {
 4949                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 4950                }
 4951            }
 4952
 4953            (Origin::RightDock, SplitDirection::Right) => {
 4954                if sidebar_on_right {
 4955                    sidebar_target
 4956                } else {
 4957                    None
 4958                }
 4959            }
 4960
 4961            _ => None,
 4962        };
 4963
 4964        match target {
 4965            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4966                let pane = pane.read(cx);
 4967                if let Some(item) = pane.active_item() {
 4968                    item.item_focus_handle(cx).focus(window, cx);
 4969                } else {
 4970                    log::error!(
 4971                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4972                    );
 4973                }
 4974            }
 4975            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4976                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4977                window.defer(cx, move |window, cx| {
 4978                    let dock = dock.read(cx);
 4979                    if let Some(panel) = dock.active_panel() {
 4980                        panel.panel_focus_handle(cx).focus(window, cx);
 4981                    } else {
 4982                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4983                    }
 4984                })
 4985            }
 4986            Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
 4987                focus_handle.focus(window, cx);
 4988            }
 4989            None => {}
 4990        }
 4991    }
 4992
 4993    pub fn move_item_to_pane_in_direction(
 4994        &mut self,
 4995        action: &MoveItemToPaneInDirection,
 4996        window: &mut Window,
 4997        cx: &mut Context<Self>,
 4998    ) {
 4999        let destination = match self.find_pane_in_direction(action.direction, cx) {
 5000            Some(destination) => destination,
 5001            None => {
 5002                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 5003                    return;
 5004                }
 5005                let new_pane = self.add_pane(window, cx);
 5006                self.center
 5007                    .split(&self.active_pane, &new_pane, action.direction, cx);
 5008                new_pane
 5009            }
 5010        };
 5011
 5012        if action.clone {
 5013            if self
 5014                .active_pane
 5015                .read(cx)
 5016                .active_item()
 5017                .is_some_and(|item| item.can_split(cx))
 5018            {
 5019                clone_active_item(
 5020                    self.database_id(),
 5021                    &self.active_pane,
 5022                    &destination,
 5023                    action.focus,
 5024                    window,
 5025                    cx,
 5026                );
 5027                return;
 5028            }
 5029        }
 5030        move_active_item(
 5031            &self.active_pane,
 5032            &destination,
 5033            action.focus,
 5034            true,
 5035            window,
 5036            cx,
 5037        );
 5038    }
 5039
 5040    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 5041        self.center.bounding_box_for_pane(pane)
 5042    }
 5043
 5044    pub fn find_pane_in_direction(
 5045        &mut self,
 5046        direction: SplitDirection,
 5047        cx: &App,
 5048    ) -> Option<Entity<Pane>> {
 5049        self.center
 5050            .find_pane_in_direction(&self.active_pane, direction, cx)
 5051            .cloned()
 5052    }
 5053
 5054    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 5055        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 5056            self.center.swap(&self.active_pane, &to, cx);
 5057            cx.notify();
 5058        }
 5059    }
 5060
 5061    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 5062        if self
 5063            .center
 5064            .move_to_border(&self.active_pane, direction, cx)
 5065            .unwrap()
 5066        {
 5067            cx.notify();
 5068        }
 5069    }
 5070
 5071    pub fn resize_pane(
 5072        &mut self,
 5073        axis: gpui::Axis,
 5074        amount: Pixels,
 5075        window: &mut Window,
 5076        cx: &mut Context<Self>,
 5077    ) {
 5078        let docks = self.all_docks();
 5079        let active_dock = docks
 5080            .into_iter()
 5081            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 5082
 5083        if let Some(dock_entity) = active_dock {
 5084            let dock = dock_entity.read(cx);
 5085            let Some(panel_size) = self.dock_size(&dock, window, cx) else {
 5086                return;
 5087            };
 5088            match dock.position() {
 5089                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 5090                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 5091                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 5092            }
 5093        } else {
 5094            self.center
 5095                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 5096        }
 5097        cx.notify();
 5098    }
 5099
 5100    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 5101        self.center.reset_pane_sizes(cx);
 5102        cx.notify();
 5103    }
 5104
 5105    fn handle_pane_focused(
 5106        &mut self,
 5107        pane: Entity<Pane>,
 5108        window: &mut Window,
 5109        cx: &mut Context<Self>,
 5110    ) {
 5111        // This is explicitly hoisted out of the following check for pane identity as
 5112        // terminal panel panes are not registered as a center panes.
 5113        self.status_bar.update(cx, |status_bar, cx| {
 5114            status_bar.set_active_pane(&pane, window, cx);
 5115        });
 5116        if self.active_pane != pane {
 5117            self.set_active_pane(&pane, window, cx);
 5118        }
 5119
 5120        if self.last_active_center_pane.is_none() {
 5121            self.last_active_center_pane = Some(pane.downgrade());
 5122        }
 5123
 5124        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 5125        // This prevents the dock from closing when focus events fire during window activation.
 5126        // We also preserve any dock whose active panel itself has focus — this covers
 5127        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 5128        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 5129            let dock_read = dock.read(cx);
 5130            if let Some(panel) = dock_read.active_panel() {
 5131                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 5132                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 5133                {
 5134                    return Some(dock_read.position());
 5135                }
 5136            }
 5137            None
 5138        });
 5139
 5140        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 5141        if pane.read(cx).is_zoomed() {
 5142            self.zoomed = Some(pane.downgrade().into());
 5143        } else {
 5144            self.zoomed = None;
 5145        }
 5146        self.zoomed_position = None;
 5147        cx.emit(Event::ZoomChanged);
 5148        self.update_active_view_for_followers(window, cx);
 5149        pane.update(cx, |pane, _| {
 5150            pane.track_alternate_file_items();
 5151        });
 5152
 5153        cx.notify();
 5154    }
 5155
 5156    fn set_active_pane(
 5157        &mut self,
 5158        pane: &Entity<Pane>,
 5159        window: &mut Window,
 5160        cx: &mut Context<Self>,
 5161    ) {
 5162        self.active_pane = pane.clone();
 5163        self.active_item_path_changed(true, window, cx);
 5164        self.last_active_center_pane = Some(pane.downgrade());
 5165    }
 5166
 5167    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5168        self.update_active_view_for_followers(window, cx);
 5169    }
 5170
 5171    fn handle_pane_event(
 5172        &mut self,
 5173        pane: &Entity<Pane>,
 5174        event: &pane::Event,
 5175        window: &mut Window,
 5176        cx: &mut Context<Self>,
 5177    ) {
 5178        let mut serialize_workspace = true;
 5179        match event {
 5180            pane::Event::AddItem { item } => {
 5181                item.added_to_pane(self, pane.clone(), window, cx);
 5182                cx.emit(Event::ItemAdded {
 5183                    item: item.boxed_clone(),
 5184                });
 5185            }
 5186            pane::Event::Split { direction, mode } => {
 5187                match mode {
 5188                    SplitMode::ClonePane => {
 5189                        self.split_and_clone(pane.clone(), *direction, window, cx)
 5190                            .detach();
 5191                    }
 5192                    SplitMode::EmptyPane => {
 5193                        self.split_pane(pane.clone(), *direction, window, cx);
 5194                    }
 5195                    SplitMode::MovePane => {
 5196                        self.split_and_move(pane.clone(), *direction, window, cx);
 5197                    }
 5198                };
 5199            }
 5200            pane::Event::JoinIntoNext => {
 5201                self.join_pane_into_next(pane.clone(), window, cx);
 5202            }
 5203            pane::Event::JoinAll => {
 5204                self.join_all_panes(window, cx);
 5205            }
 5206            pane::Event::Remove { focus_on_pane } => {
 5207                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 5208            }
 5209            pane::Event::ActivateItem {
 5210                local,
 5211                focus_changed,
 5212            } => {
 5213                window.invalidate_character_coordinates();
 5214
 5215                pane.update(cx, |pane, _| {
 5216                    pane.track_alternate_file_items();
 5217                });
 5218                if *local {
 5219                    self.unfollow_in_pane(pane, window, cx);
 5220                }
 5221                serialize_workspace = *focus_changed || pane != self.active_pane();
 5222                if pane == self.active_pane() {
 5223                    self.active_item_path_changed(*focus_changed, window, cx);
 5224                    self.update_active_view_for_followers(window, cx);
 5225                } else if *local {
 5226                    self.set_active_pane(pane, window, cx);
 5227                }
 5228            }
 5229            pane::Event::UserSavedItem { item, save_intent } => {
 5230                cx.emit(Event::UserSavedItem {
 5231                    pane: pane.downgrade(),
 5232                    item: item.boxed_clone(),
 5233                    save_intent: *save_intent,
 5234                });
 5235                serialize_workspace = false;
 5236            }
 5237            pane::Event::ChangeItemTitle => {
 5238                if *pane == self.active_pane {
 5239                    self.active_item_path_changed(false, window, cx);
 5240                }
 5241                serialize_workspace = false;
 5242            }
 5243            pane::Event::RemovedItem { item } => {
 5244                cx.emit(Event::ActiveItemChanged);
 5245                self.update_window_edited(window, cx);
 5246                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 5247                    && entry.get().entity_id() == pane.entity_id()
 5248                {
 5249                    entry.remove();
 5250                }
 5251                cx.emit(Event::ItemRemoved {
 5252                    item_id: item.item_id(),
 5253                });
 5254            }
 5255            pane::Event::Focus => {
 5256                window.invalidate_character_coordinates();
 5257                self.handle_pane_focused(pane.clone(), window, cx);
 5258            }
 5259            pane::Event::ZoomIn => {
 5260                if *pane == self.active_pane {
 5261                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 5262                    if pane.read(cx).has_focus(window, cx) {
 5263                        self.zoomed = Some(pane.downgrade().into());
 5264                        self.zoomed_position = None;
 5265                        cx.emit(Event::ZoomChanged);
 5266                    }
 5267                    cx.notify();
 5268                }
 5269            }
 5270            pane::Event::ZoomOut => {
 5271                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 5272                if self.zoomed_position.is_none() {
 5273                    self.zoomed = None;
 5274                    cx.emit(Event::ZoomChanged);
 5275                }
 5276                cx.notify();
 5277            }
 5278            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 5279        }
 5280
 5281        if serialize_workspace {
 5282            self.serialize_workspace(window, cx);
 5283        }
 5284    }
 5285
 5286    pub fn unfollow_in_pane(
 5287        &mut self,
 5288        pane: &Entity<Pane>,
 5289        window: &mut Window,
 5290        cx: &mut Context<Workspace>,
 5291    ) -> Option<CollaboratorId> {
 5292        let leader_id = self.leader_for_pane(pane)?;
 5293        self.unfollow(leader_id, window, cx);
 5294        Some(leader_id)
 5295    }
 5296
 5297    pub fn split_pane(
 5298        &mut self,
 5299        pane_to_split: Entity<Pane>,
 5300        split_direction: SplitDirection,
 5301        window: &mut Window,
 5302        cx: &mut Context<Self>,
 5303    ) -> Entity<Pane> {
 5304        let new_pane = self.add_pane(window, cx);
 5305        self.center
 5306            .split(&pane_to_split, &new_pane, split_direction, cx);
 5307        cx.notify();
 5308        new_pane
 5309    }
 5310
 5311    pub fn split_and_move(
 5312        &mut self,
 5313        pane: Entity<Pane>,
 5314        direction: SplitDirection,
 5315        window: &mut Window,
 5316        cx: &mut Context<Self>,
 5317    ) {
 5318        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 5319            return;
 5320        };
 5321        let new_pane = self.add_pane(window, cx);
 5322        new_pane.update(cx, |pane, cx| {
 5323            pane.add_item(item, true, true, None, window, cx)
 5324        });
 5325        self.center.split(&pane, &new_pane, direction, cx);
 5326        cx.notify();
 5327    }
 5328
 5329    pub fn split_and_clone(
 5330        &mut self,
 5331        pane: Entity<Pane>,
 5332        direction: SplitDirection,
 5333        window: &mut Window,
 5334        cx: &mut Context<Self>,
 5335    ) -> Task<Option<Entity<Pane>>> {
 5336        let Some(item) = pane.read(cx).active_item() else {
 5337            return Task::ready(None);
 5338        };
 5339        if !item.can_split(cx) {
 5340            return Task::ready(None);
 5341        }
 5342        let task = item.clone_on_split(self.database_id(), window, cx);
 5343        cx.spawn_in(window, async move |this, cx| {
 5344            if let Some(clone) = task.await {
 5345                this.update_in(cx, |this, window, cx| {
 5346                    let new_pane = this.add_pane(window, cx);
 5347                    let nav_history = pane.read(cx).fork_nav_history();
 5348                    new_pane.update(cx, |pane, cx| {
 5349                        pane.set_nav_history(nav_history, cx);
 5350                        pane.add_item(clone, true, true, None, window, cx)
 5351                    });
 5352                    this.center.split(&pane, &new_pane, direction, cx);
 5353                    cx.notify();
 5354                    new_pane
 5355                })
 5356                .ok()
 5357            } else {
 5358                None
 5359            }
 5360        })
 5361    }
 5362
 5363    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5364        let active_item = self.active_pane.read(cx).active_item();
 5365        for pane in &self.panes {
 5366            join_pane_into_active(&self.active_pane, pane, window, cx);
 5367        }
 5368        if let Some(active_item) = active_item {
 5369            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5370        }
 5371        cx.notify();
 5372    }
 5373
 5374    pub fn join_pane_into_next(
 5375        &mut self,
 5376        pane: Entity<Pane>,
 5377        window: &mut Window,
 5378        cx: &mut Context<Self>,
 5379    ) {
 5380        let next_pane = self
 5381            .find_pane_in_direction(SplitDirection::Right, cx)
 5382            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5383            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5384            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5385        let Some(next_pane) = next_pane else {
 5386            return;
 5387        };
 5388        move_all_items(&pane, &next_pane, window, cx);
 5389        cx.notify();
 5390    }
 5391
 5392    fn remove_pane(
 5393        &mut self,
 5394        pane: Entity<Pane>,
 5395        focus_on: Option<Entity<Pane>>,
 5396        window: &mut Window,
 5397        cx: &mut Context<Self>,
 5398    ) {
 5399        if self.center.remove(&pane, cx).unwrap() {
 5400            self.force_remove_pane(&pane, &focus_on, window, cx);
 5401            self.unfollow_in_pane(&pane, window, cx);
 5402            self.last_leaders_by_pane.remove(&pane.downgrade());
 5403            for removed_item in pane.read(cx).items() {
 5404                self.panes_by_item.remove(&removed_item.item_id());
 5405            }
 5406
 5407            cx.notify();
 5408        } else {
 5409            self.active_item_path_changed(true, window, cx);
 5410        }
 5411        cx.emit(Event::PaneRemoved);
 5412    }
 5413
 5414    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5415        &mut self.panes
 5416    }
 5417
 5418    pub fn panes(&self) -> &[Entity<Pane>] {
 5419        &self.panes
 5420    }
 5421
 5422    pub fn active_pane(&self) -> &Entity<Pane> {
 5423        &self.active_pane
 5424    }
 5425
 5426    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5427        for dock in self.all_docks() {
 5428            if dock.focus_handle(cx).contains_focused(window, cx)
 5429                && let Some(pane) = dock
 5430                    .read(cx)
 5431                    .active_panel()
 5432                    .and_then(|panel| panel.pane(cx))
 5433            {
 5434                return pane;
 5435            }
 5436        }
 5437        self.active_pane().clone()
 5438    }
 5439
 5440    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5441        self.find_pane_in_direction(SplitDirection::Right, cx)
 5442            .unwrap_or_else(|| {
 5443                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5444            })
 5445    }
 5446
 5447    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5448        self.pane_for_item_id(handle.item_id())
 5449    }
 5450
 5451    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5452        let weak_pane = self.panes_by_item.get(&item_id)?;
 5453        weak_pane.upgrade()
 5454    }
 5455
 5456    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5457        self.panes
 5458            .iter()
 5459            .find(|pane| pane.entity_id() == entity_id)
 5460            .cloned()
 5461    }
 5462
 5463    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5464        self.follower_states.retain(|leader_id, state| {
 5465            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5466                for item in state.items_by_leader_view_id.values() {
 5467                    item.view.set_leader_id(None, window, cx);
 5468                }
 5469                false
 5470            } else {
 5471                true
 5472            }
 5473        });
 5474        cx.notify();
 5475    }
 5476
 5477    pub fn start_following(
 5478        &mut self,
 5479        leader_id: impl Into<CollaboratorId>,
 5480        window: &mut Window,
 5481        cx: &mut Context<Self>,
 5482    ) -> Option<Task<Result<()>>> {
 5483        let leader_id = leader_id.into();
 5484        let pane = self.active_pane().clone();
 5485
 5486        self.last_leaders_by_pane
 5487            .insert(pane.downgrade(), leader_id);
 5488        self.unfollow(leader_id, window, cx);
 5489        self.unfollow_in_pane(&pane, window, cx);
 5490        self.follower_states.insert(
 5491            leader_id,
 5492            FollowerState {
 5493                center_pane: pane.clone(),
 5494                dock_pane: None,
 5495                active_view_id: None,
 5496                items_by_leader_view_id: Default::default(),
 5497            },
 5498        );
 5499        cx.notify();
 5500
 5501        match leader_id {
 5502            CollaboratorId::PeerId(leader_peer_id) => {
 5503                let room_id = self.active_call()?.room_id(cx)?;
 5504                let project_id = self.project.read(cx).remote_id();
 5505                let request = self.app_state.client.request(proto::Follow {
 5506                    room_id,
 5507                    project_id,
 5508                    leader_id: Some(leader_peer_id),
 5509                });
 5510
 5511                Some(cx.spawn_in(window, async move |this, cx| {
 5512                    let response = request.await?;
 5513                    this.update(cx, |this, _| {
 5514                        let state = this
 5515                            .follower_states
 5516                            .get_mut(&leader_id)
 5517                            .context("following interrupted")?;
 5518                        state.active_view_id = response
 5519                            .active_view
 5520                            .as_ref()
 5521                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5522                        anyhow::Ok(())
 5523                    })??;
 5524                    if let Some(view) = response.active_view {
 5525                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5526                    }
 5527                    this.update_in(cx, |this, window, cx| {
 5528                        this.leader_updated(leader_id, window, cx)
 5529                    })?;
 5530                    Ok(())
 5531                }))
 5532            }
 5533            CollaboratorId::Agent => {
 5534                self.leader_updated(leader_id, window, cx)?;
 5535                Some(Task::ready(Ok(())))
 5536            }
 5537        }
 5538    }
 5539
 5540    pub fn follow_next_collaborator(
 5541        &mut self,
 5542        _: &FollowNextCollaborator,
 5543        window: &mut Window,
 5544        cx: &mut Context<Self>,
 5545    ) {
 5546        let collaborators = self.project.read(cx).collaborators();
 5547        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5548            let mut collaborators = collaborators.keys().copied();
 5549            for peer_id in collaborators.by_ref() {
 5550                if CollaboratorId::PeerId(peer_id) == leader_id {
 5551                    break;
 5552                }
 5553            }
 5554            collaborators.next().map(CollaboratorId::PeerId)
 5555        } else if let Some(last_leader_id) =
 5556            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5557        {
 5558            match last_leader_id {
 5559                CollaboratorId::PeerId(peer_id) => {
 5560                    if collaborators.contains_key(peer_id) {
 5561                        Some(*last_leader_id)
 5562                    } else {
 5563                        None
 5564                    }
 5565                }
 5566                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5567            }
 5568        } else {
 5569            None
 5570        };
 5571
 5572        let pane = self.active_pane.clone();
 5573        let Some(leader_id) = next_leader_id.or_else(|| {
 5574            Some(CollaboratorId::PeerId(
 5575                collaborators.keys().copied().next()?,
 5576            ))
 5577        }) else {
 5578            return;
 5579        };
 5580        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5581            return;
 5582        }
 5583        if let Some(task) = self.start_following(leader_id, window, cx) {
 5584            task.detach_and_log_err(cx)
 5585        }
 5586    }
 5587
 5588    pub fn follow(
 5589        &mut self,
 5590        leader_id: impl Into<CollaboratorId>,
 5591        window: &mut Window,
 5592        cx: &mut Context<Self>,
 5593    ) {
 5594        let leader_id = leader_id.into();
 5595
 5596        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5597            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5598                return;
 5599            };
 5600            let Some(remote_participant) =
 5601                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5602            else {
 5603                return;
 5604            };
 5605
 5606            let project = self.project.read(cx);
 5607
 5608            let other_project_id = match remote_participant.location {
 5609                ParticipantLocation::External => None,
 5610                ParticipantLocation::UnsharedProject => None,
 5611                ParticipantLocation::SharedProject { project_id } => {
 5612                    if Some(project_id) == project.remote_id() {
 5613                        None
 5614                    } else {
 5615                        Some(project_id)
 5616                    }
 5617                }
 5618            };
 5619
 5620            // if they are active in another project, follow there.
 5621            if let Some(project_id) = other_project_id {
 5622                let app_state = self.app_state.clone();
 5623                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5624                    .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
 5625                        Some(format!("{error:#}"))
 5626                    });
 5627            }
 5628        }
 5629
 5630        // if you're already following, find the right pane and focus it.
 5631        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5632            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5633
 5634            return;
 5635        }
 5636
 5637        // Otherwise, follow.
 5638        if let Some(task) = self.start_following(leader_id, window, cx) {
 5639            task.detach_and_log_err(cx)
 5640        }
 5641    }
 5642
 5643    pub fn unfollow(
 5644        &mut self,
 5645        leader_id: impl Into<CollaboratorId>,
 5646        window: &mut Window,
 5647        cx: &mut Context<Self>,
 5648    ) -> Option<()> {
 5649        cx.notify();
 5650
 5651        let leader_id = leader_id.into();
 5652        let state = self.follower_states.remove(&leader_id)?;
 5653        for (_, item) in state.items_by_leader_view_id {
 5654            item.view.set_leader_id(None, window, cx);
 5655        }
 5656
 5657        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5658            let project_id = self.project.read(cx).remote_id();
 5659            let room_id = self.active_call()?.room_id(cx)?;
 5660            self.app_state
 5661                .client
 5662                .send(proto::Unfollow {
 5663                    room_id,
 5664                    project_id,
 5665                    leader_id: Some(leader_peer_id),
 5666                })
 5667                .log_err();
 5668        }
 5669
 5670        Some(())
 5671    }
 5672
 5673    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5674        self.follower_states.contains_key(&id.into())
 5675    }
 5676
 5677    fn active_item_path_changed(
 5678        &mut self,
 5679        focus_changed: bool,
 5680        window: &mut Window,
 5681        cx: &mut Context<Self>,
 5682    ) {
 5683        cx.emit(Event::ActiveItemChanged);
 5684        let active_entry = self.active_project_path(cx);
 5685        self.project.update(cx, |project, cx| {
 5686            project.set_active_path(active_entry.clone(), cx)
 5687        });
 5688
 5689        if focus_changed && let Some(project_path) = &active_entry {
 5690            let git_store_entity = self.project.read(cx).git_store().clone();
 5691            git_store_entity.update(cx, |git_store, cx| {
 5692                git_store.set_active_repo_for_path(project_path, cx);
 5693            });
 5694        }
 5695
 5696        self.update_window_title(window, cx);
 5697    }
 5698
 5699    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5700        let project = self.project().read(cx);
 5701        let mut title = String::new();
 5702
 5703        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5704            let name = {
 5705                let settings_location = SettingsLocation {
 5706                    worktree_id: worktree.read(cx).id(),
 5707                    path: RelPath::empty(),
 5708                };
 5709
 5710                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5711                match &settings.project_name {
 5712                    Some(name) => name.as_str(),
 5713                    None => worktree.read(cx).root_name_str(),
 5714                }
 5715            };
 5716            if i > 0 {
 5717                title.push_str(", ");
 5718            }
 5719            title.push_str(name);
 5720        }
 5721
 5722        if title.is_empty() {
 5723            title = "empty project".to_string();
 5724        }
 5725
 5726        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5727            let filename = path.path.file_name().or_else(|| {
 5728                Some(
 5729                    project
 5730                        .worktree_for_id(path.worktree_id, cx)?
 5731                        .read(cx)
 5732                        .root_name_str(),
 5733                )
 5734            });
 5735
 5736            if let Some(filename) = filename {
 5737                title.push_str("");
 5738                title.push_str(filename.as_ref());
 5739            }
 5740        }
 5741
 5742        if project.is_via_collab() {
 5743            title.push_str("");
 5744        } else if project.is_shared() {
 5745            title.push_str("");
 5746        }
 5747
 5748        if let Some(last_title) = self.last_window_title.as_ref()
 5749            && &title == last_title
 5750        {
 5751            return;
 5752        }
 5753        window.set_window_title(&title);
 5754        SystemWindowTabController::update_tab_title(
 5755            cx,
 5756            window.window_handle().window_id(),
 5757            SharedString::from(&title),
 5758        );
 5759        self.last_window_title = Some(title);
 5760    }
 5761
 5762    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5763        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5764        if is_edited != self.window_edited {
 5765            self.window_edited = is_edited;
 5766            window.set_window_edited(self.window_edited)
 5767        }
 5768    }
 5769
 5770    fn update_item_dirty_state(
 5771        &mut self,
 5772        item: &dyn ItemHandle,
 5773        window: &mut Window,
 5774        cx: &mut App,
 5775    ) {
 5776        let is_dirty = item.is_dirty(cx);
 5777        let item_id = item.item_id();
 5778        let was_dirty = self.dirty_items.contains_key(&item_id);
 5779        if is_dirty == was_dirty {
 5780            return;
 5781        }
 5782        if was_dirty {
 5783            self.dirty_items.remove(&item_id);
 5784            self.update_window_edited(window, cx);
 5785            return;
 5786        }
 5787
 5788        let workspace = self.weak_handle();
 5789        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5790            return;
 5791        };
 5792        let on_release_callback = Box::new(move |cx: &mut App| {
 5793            window_handle
 5794                .update(cx, |_, window, cx| {
 5795                    workspace
 5796                        .update(cx, |workspace, cx| {
 5797                            workspace.dirty_items.remove(&item_id);
 5798                            workspace.update_window_edited(window, cx)
 5799                        })
 5800                        .ok();
 5801                })
 5802                .ok();
 5803        });
 5804
 5805        let s = item.on_release(cx, on_release_callback);
 5806        self.dirty_items.insert(item_id, s);
 5807        self.update_window_edited(window, cx);
 5808    }
 5809
 5810    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5811        if self.notifications.is_empty() {
 5812            None
 5813        } else {
 5814            Some(
 5815                div()
 5816                    .absolute()
 5817                    .right_3()
 5818                    .bottom_3()
 5819                    .w_112()
 5820                    .h_full()
 5821                    .flex()
 5822                    .flex_col()
 5823                    .justify_end()
 5824                    .gap_2()
 5825                    .children(
 5826                        self.notifications
 5827                            .iter()
 5828                            .map(|(_, notification)| notification.clone().into_any()),
 5829                    ),
 5830            )
 5831        }
 5832    }
 5833
 5834    // RPC handlers
 5835
 5836    fn active_view_for_follower(
 5837        &self,
 5838        follower_project_id: Option<u64>,
 5839        window: &mut Window,
 5840        cx: &mut Context<Self>,
 5841    ) -> Option<proto::View> {
 5842        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5843        let item = item?;
 5844        let leader_id = self
 5845            .pane_for(&*item)
 5846            .and_then(|pane| self.leader_for_pane(&pane));
 5847        let leader_peer_id = match leader_id {
 5848            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5849            Some(CollaboratorId::Agent) | None => None,
 5850        };
 5851
 5852        let item_handle = item.to_followable_item_handle(cx)?;
 5853        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5854        let variant = item_handle.to_state_proto(window, cx)?;
 5855
 5856        if item_handle.is_project_item(window, cx)
 5857            && (follower_project_id.is_none()
 5858                || follower_project_id != self.project.read(cx).remote_id())
 5859        {
 5860            return None;
 5861        }
 5862
 5863        Some(proto::View {
 5864            id: id.to_proto(),
 5865            leader_id: leader_peer_id,
 5866            variant: Some(variant),
 5867            panel_id: panel_id.map(|id| id as i32),
 5868        })
 5869    }
 5870
 5871    fn handle_follow(
 5872        &mut self,
 5873        follower_project_id: Option<u64>,
 5874        window: &mut Window,
 5875        cx: &mut Context<Self>,
 5876    ) -> proto::FollowResponse {
 5877        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5878
 5879        cx.notify();
 5880        proto::FollowResponse {
 5881            views: active_view.iter().cloned().collect(),
 5882            active_view,
 5883        }
 5884    }
 5885
 5886    fn handle_update_followers(
 5887        &mut self,
 5888        leader_id: PeerId,
 5889        message: proto::UpdateFollowers,
 5890        _window: &mut Window,
 5891        _cx: &mut Context<Self>,
 5892    ) {
 5893        self.leader_updates_tx
 5894            .unbounded_send((leader_id, message))
 5895            .ok();
 5896    }
 5897
 5898    async fn process_leader_update(
 5899        this: &WeakEntity<Self>,
 5900        leader_id: PeerId,
 5901        update: proto::UpdateFollowers,
 5902        cx: &mut AsyncWindowContext,
 5903    ) -> Result<()> {
 5904        match update.variant.context("invalid update")? {
 5905            proto::update_followers::Variant::CreateView(view) => {
 5906                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5907                let should_add_view = this.update(cx, |this, _| {
 5908                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5909                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5910                    } else {
 5911                        anyhow::Ok(false)
 5912                    }
 5913                })??;
 5914
 5915                if should_add_view {
 5916                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5917                }
 5918            }
 5919            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5920                let should_add_view = this.update(cx, |this, _| {
 5921                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5922                        state.active_view_id = update_active_view
 5923                            .view
 5924                            .as_ref()
 5925                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5926
 5927                        if state.active_view_id.is_some_and(|view_id| {
 5928                            !state.items_by_leader_view_id.contains_key(&view_id)
 5929                        }) {
 5930                            anyhow::Ok(true)
 5931                        } else {
 5932                            anyhow::Ok(false)
 5933                        }
 5934                    } else {
 5935                        anyhow::Ok(false)
 5936                    }
 5937                })??;
 5938
 5939                if should_add_view && let Some(view) = update_active_view.view {
 5940                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5941                }
 5942            }
 5943            proto::update_followers::Variant::UpdateView(update_view) => {
 5944                let variant = update_view.variant.context("missing update view variant")?;
 5945                let id = update_view.id.context("missing update view id")?;
 5946                let mut tasks = Vec::new();
 5947                this.update_in(cx, |this, window, cx| {
 5948                    let project = this.project.clone();
 5949                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5950                        let view_id = ViewId::from_proto(id.clone())?;
 5951                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5952                            tasks.push(item.view.apply_update_proto(
 5953                                &project,
 5954                                variant.clone(),
 5955                                window,
 5956                                cx,
 5957                            ));
 5958                        }
 5959                    }
 5960                    anyhow::Ok(())
 5961                })??;
 5962                try_join_all(tasks).await.log_err();
 5963            }
 5964        }
 5965        this.update_in(cx, |this, window, cx| {
 5966            this.leader_updated(leader_id, window, cx)
 5967        })?;
 5968        Ok(())
 5969    }
 5970
 5971    async fn add_view_from_leader(
 5972        this: WeakEntity<Self>,
 5973        leader_id: PeerId,
 5974        view: &proto::View,
 5975        cx: &mut AsyncWindowContext,
 5976    ) -> Result<()> {
 5977        let this = this.upgrade().context("workspace dropped")?;
 5978
 5979        let Some(id) = view.id.clone() else {
 5980            anyhow::bail!("no id for view");
 5981        };
 5982        let id = ViewId::from_proto(id)?;
 5983        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5984
 5985        let pane = this.update(cx, |this, _cx| {
 5986            let state = this
 5987                .follower_states
 5988                .get(&leader_id.into())
 5989                .context("stopped following")?;
 5990            anyhow::Ok(state.pane().clone())
 5991        })?;
 5992        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5993            let client = this.read(cx).client().clone();
 5994            pane.items().find_map(|item| {
 5995                let item = item.to_followable_item_handle(cx)?;
 5996                if item.remote_id(&client, window, cx) == Some(id) {
 5997                    Some(item)
 5998                } else {
 5999                    None
 6000                }
 6001            })
 6002        })?;
 6003        let item = if let Some(existing_item) = existing_item {
 6004            existing_item
 6005        } else {
 6006            let variant = view.variant.clone();
 6007            anyhow::ensure!(variant.is_some(), "missing view variant");
 6008
 6009            let task = cx.update(|window, cx| {
 6010                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 6011            })?;
 6012
 6013            let Some(task) = task else {
 6014                anyhow::bail!(
 6015                    "failed to construct view from leader (maybe from a different version of zed?)"
 6016                );
 6017            };
 6018
 6019            let mut new_item = task.await?;
 6020            pane.update_in(cx, |pane, window, cx| {
 6021                let mut item_to_remove = None;
 6022                for (ix, item) in pane.items().enumerate() {
 6023                    if let Some(item) = item.to_followable_item_handle(cx) {
 6024                        match new_item.dedup(item.as_ref(), window, cx) {
 6025                            Some(item::Dedup::KeepExisting) => {
 6026                                new_item =
 6027                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 6028                                break;
 6029                            }
 6030                            Some(item::Dedup::ReplaceExisting) => {
 6031                                item_to_remove = Some((ix, item.item_id()));
 6032                                break;
 6033                            }
 6034                            None => {}
 6035                        }
 6036                    }
 6037                }
 6038
 6039                if let Some((ix, id)) = item_to_remove {
 6040                    pane.remove_item(id, false, false, window, cx);
 6041                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 6042                }
 6043            })?;
 6044
 6045            new_item
 6046        };
 6047
 6048        this.update_in(cx, |this, window, cx| {
 6049            let state = this.follower_states.get_mut(&leader_id.into())?;
 6050            item.set_leader_id(Some(leader_id.into()), window, cx);
 6051            state.items_by_leader_view_id.insert(
 6052                id,
 6053                FollowerView {
 6054                    view: item,
 6055                    location: panel_id,
 6056                },
 6057            );
 6058
 6059            Some(())
 6060        })
 6061        .context("no follower state")?;
 6062
 6063        Ok(())
 6064    }
 6065
 6066    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6067        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 6068            return;
 6069        };
 6070
 6071        if let Some(agent_location) = self.project.read(cx).agent_location() {
 6072            let buffer_entity_id = agent_location.buffer.entity_id();
 6073            let view_id = ViewId {
 6074                creator: CollaboratorId::Agent,
 6075                id: buffer_entity_id.as_u64(),
 6076            };
 6077            follower_state.active_view_id = Some(view_id);
 6078
 6079            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 6080                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 6081                hash_map::Entry::Vacant(entry) => {
 6082                    let existing_view =
 6083                        follower_state
 6084                            .center_pane
 6085                            .read(cx)
 6086                            .items()
 6087                            .find_map(|item| {
 6088                                let item = item.to_followable_item_handle(cx)?;
 6089                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 6090                                    && item.project_item_model_ids(cx).as_slice()
 6091                                        == [buffer_entity_id]
 6092                                {
 6093                                    Some(item)
 6094                                } else {
 6095                                    None
 6096                                }
 6097                            });
 6098                    let view = existing_view.or_else(|| {
 6099                        agent_location.buffer.upgrade().and_then(|buffer| {
 6100                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 6101                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 6102                            })?
 6103                            .to_followable_item_handle(cx)
 6104                        })
 6105                    });
 6106
 6107                    view.map(|view| {
 6108                        entry.insert(FollowerView {
 6109                            view,
 6110                            location: None,
 6111                        })
 6112                    })
 6113                }
 6114            };
 6115
 6116            if let Some(item) = item {
 6117                item.view
 6118                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 6119                item.view
 6120                    .update_agent_location(agent_location.position, window, cx);
 6121            }
 6122        } else {
 6123            follower_state.active_view_id = None;
 6124        }
 6125
 6126        self.leader_updated(CollaboratorId::Agent, window, cx);
 6127    }
 6128
 6129    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 6130        let mut is_project_item = true;
 6131        let mut update = proto::UpdateActiveView::default();
 6132        if window.is_window_active() {
 6133            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 6134
 6135            if let Some(item) = active_item
 6136                && item.item_focus_handle(cx).contains_focused(window, cx)
 6137            {
 6138                let leader_id = self
 6139                    .pane_for(&*item)
 6140                    .and_then(|pane| self.leader_for_pane(&pane));
 6141                let leader_peer_id = match leader_id {
 6142                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 6143                    Some(CollaboratorId::Agent) | None => None,
 6144                };
 6145
 6146                if let Some(item) = item.to_followable_item_handle(cx) {
 6147                    let id = item
 6148                        .remote_id(&self.app_state.client, window, cx)
 6149                        .map(|id| id.to_proto());
 6150
 6151                    if let Some(id) = id
 6152                        && let Some(variant) = item.to_state_proto(window, cx)
 6153                    {
 6154                        let view = Some(proto::View {
 6155                            id,
 6156                            leader_id: leader_peer_id,
 6157                            variant: Some(variant),
 6158                            panel_id: panel_id.map(|id| id as i32),
 6159                        });
 6160
 6161                        is_project_item = item.is_project_item(window, cx);
 6162                        update = proto::UpdateActiveView { view };
 6163                    };
 6164                }
 6165            }
 6166        }
 6167
 6168        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 6169        if active_view_id != self.last_active_view_id.as_ref() {
 6170            self.last_active_view_id = active_view_id.cloned();
 6171            self.update_followers(
 6172                is_project_item,
 6173                proto::update_followers::Variant::UpdateActiveView(update),
 6174                window,
 6175                cx,
 6176            );
 6177        }
 6178    }
 6179
 6180    fn active_item_for_followers(
 6181        &self,
 6182        window: &mut Window,
 6183        cx: &mut App,
 6184    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 6185        let mut active_item = None;
 6186        let mut panel_id = None;
 6187        for dock in self.all_docks() {
 6188            if dock.focus_handle(cx).contains_focused(window, cx)
 6189                && let Some(panel) = dock.read(cx).active_panel()
 6190                && let Some(pane) = panel.pane(cx)
 6191                && let Some(item) = pane.read(cx).active_item()
 6192            {
 6193                active_item = Some(item);
 6194                panel_id = panel.remote_id();
 6195                break;
 6196            }
 6197        }
 6198
 6199        if active_item.is_none() {
 6200            active_item = self.active_pane().read(cx).active_item();
 6201        }
 6202        (active_item, panel_id)
 6203    }
 6204
 6205    fn update_followers(
 6206        &self,
 6207        project_only: bool,
 6208        update: proto::update_followers::Variant,
 6209        _: &mut Window,
 6210        cx: &mut App,
 6211    ) -> Option<()> {
 6212        // If this update only applies to for followers in the current project,
 6213        // then skip it unless this project is shared. If it applies to all
 6214        // followers, regardless of project, then set `project_id` to none,
 6215        // indicating that it goes to all followers.
 6216        let project_id = if project_only {
 6217            Some(self.project.read(cx).remote_id()?)
 6218        } else {
 6219            None
 6220        };
 6221        self.app_state().workspace_store.update(cx, |store, cx| {
 6222            store.update_followers(project_id, update, cx)
 6223        })
 6224    }
 6225
 6226    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 6227        self.follower_states.iter().find_map(|(leader_id, state)| {
 6228            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 6229                Some(*leader_id)
 6230            } else {
 6231                None
 6232            }
 6233        })
 6234    }
 6235
 6236    fn leader_updated(
 6237        &mut self,
 6238        leader_id: impl Into<CollaboratorId>,
 6239        window: &mut Window,
 6240        cx: &mut Context<Self>,
 6241    ) -> Option<Box<dyn ItemHandle>> {
 6242        cx.notify();
 6243
 6244        let leader_id = leader_id.into();
 6245        let (panel_id, item) = match leader_id {
 6246            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 6247            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 6248        };
 6249
 6250        let state = self.follower_states.get(&leader_id)?;
 6251        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 6252        let pane;
 6253        if let Some(panel_id) = panel_id {
 6254            pane = self
 6255                .activate_panel_for_proto_id(panel_id, window, cx)?
 6256                .pane(cx)?;
 6257            let state = self.follower_states.get_mut(&leader_id)?;
 6258            state.dock_pane = Some(pane.clone());
 6259        } else {
 6260            pane = state.center_pane.clone();
 6261            let state = self.follower_states.get_mut(&leader_id)?;
 6262            if let Some(dock_pane) = state.dock_pane.take() {
 6263                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 6264            }
 6265        }
 6266
 6267        pane.update(cx, |pane, cx| {
 6268            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 6269            if let Some(index) = pane.index_for_item(item.as_ref()) {
 6270                pane.activate_item(index, false, false, window, cx);
 6271            } else {
 6272                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 6273            }
 6274
 6275            if focus_active_item {
 6276                pane.focus_active_item(window, cx)
 6277            }
 6278        });
 6279
 6280        Some(item)
 6281    }
 6282
 6283    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 6284        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 6285        let active_view_id = state.active_view_id?;
 6286        Some(
 6287            state
 6288                .items_by_leader_view_id
 6289                .get(&active_view_id)?
 6290                .view
 6291                .boxed_clone(),
 6292        )
 6293    }
 6294
 6295    fn active_item_for_peer(
 6296        &self,
 6297        peer_id: PeerId,
 6298        window: &mut Window,
 6299        cx: &mut Context<Self>,
 6300    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 6301        let call = self.active_call()?;
 6302        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 6303        let leader_in_this_app;
 6304        let leader_in_this_project;
 6305        match participant.location {
 6306            ParticipantLocation::SharedProject { project_id } => {
 6307                leader_in_this_app = true;
 6308                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 6309            }
 6310            ParticipantLocation::UnsharedProject => {
 6311                leader_in_this_app = true;
 6312                leader_in_this_project = false;
 6313            }
 6314            ParticipantLocation::External => {
 6315                leader_in_this_app = false;
 6316                leader_in_this_project = false;
 6317            }
 6318        };
 6319        let state = self.follower_states.get(&peer_id.into())?;
 6320        let mut item_to_activate = None;
 6321        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 6322            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 6323                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 6324            {
 6325                item_to_activate = Some((item.location, item.view.boxed_clone()));
 6326            }
 6327        } else if let Some(shared_screen) =
 6328            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 6329        {
 6330            item_to_activate = Some((None, Box::new(shared_screen)));
 6331        }
 6332        item_to_activate
 6333    }
 6334
 6335    fn shared_screen_for_peer(
 6336        &self,
 6337        peer_id: PeerId,
 6338        pane: &Entity<Pane>,
 6339        window: &mut Window,
 6340        cx: &mut App,
 6341    ) -> Option<Entity<SharedScreen>> {
 6342        self.active_call()?
 6343            .create_shared_screen(peer_id, pane, window, cx)
 6344    }
 6345
 6346    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6347        if window.is_window_active() {
 6348            self.update_active_view_for_followers(window, cx);
 6349
 6350            if let Some(database_id) = self.database_id {
 6351                let db = WorkspaceDb::global(cx);
 6352                cx.background_spawn(async move { db.update_timestamp(database_id).await })
 6353                    .detach();
 6354            }
 6355        } else {
 6356            for pane in &self.panes {
 6357                pane.update(cx, |pane, cx| {
 6358                    if let Some(item) = pane.active_item() {
 6359                        item.workspace_deactivated(window, cx);
 6360                    }
 6361                    for item in pane.items() {
 6362                        if matches!(
 6363                            item.workspace_settings(cx).autosave,
 6364                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6365                        ) {
 6366                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6367                                .detach_and_log_err(cx);
 6368                        }
 6369                    }
 6370                });
 6371            }
 6372        }
 6373    }
 6374
 6375    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6376        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6377    }
 6378
 6379    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6380        self.active_call.as_ref().map(|(call, _)| call.clone())
 6381    }
 6382
 6383    fn on_active_call_event(
 6384        &mut self,
 6385        event: &ActiveCallEvent,
 6386        window: &mut Window,
 6387        cx: &mut Context<Self>,
 6388    ) {
 6389        match event {
 6390            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6391            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6392                self.leader_updated(participant_id, window, cx);
 6393            }
 6394        }
 6395    }
 6396
 6397    pub fn database_id(&self) -> Option<WorkspaceId> {
 6398        self.database_id
 6399    }
 6400
 6401    #[cfg(any(test, feature = "test-support"))]
 6402    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6403        self.database_id = Some(id);
 6404    }
 6405
 6406    pub fn session_id(&self) -> Option<String> {
 6407        self.session_id.clone()
 6408    }
 6409
 6410    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6411        let Some(display) = window.display(cx) else {
 6412            return Task::ready(());
 6413        };
 6414        let Ok(display_uuid) = display.uuid() else {
 6415            return Task::ready(());
 6416        };
 6417
 6418        let window_bounds = window.inner_window_bounds();
 6419        let database_id = self.database_id;
 6420        let has_paths = !self.root_paths(cx).is_empty();
 6421        let db = WorkspaceDb::global(cx);
 6422        let kvp = db::kvp::KeyValueStore::global(cx);
 6423
 6424        cx.background_executor().spawn(async move {
 6425            if !has_paths {
 6426                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6427                    .await
 6428                    .log_err();
 6429            }
 6430            if let Some(database_id) = database_id {
 6431                db.set_window_open_status(
 6432                    database_id,
 6433                    SerializedWindowBounds(window_bounds),
 6434                    display_uuid,
 6435                )
 6436                .await
 6437                .log_err();
 6438            } else {
 6439                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6440                    .await
 6441                    .log_err();
 6442            }
 6443        })
 6444    }
 6445
 6446    /// Bypass the 200ms serialization throttle and write workspace state to
 6447    /// the DB immediately. Returns a task the caller can await to ensure the
 6448    /// write completes. Used by the quit handler so the most recent state
 6449    /// isn't lost to a pending throttle timer when the process exits.
 6450    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6451        self._schedule_serialize_workspace.take();
 6452        self._serialize_workspace_task.take();
 6453        self.bounds_save_task_queued.take();
 6454
 6455        let bounds_task = self.save_window_bounds(window, cx);
 6456        let serialize_task = self.serialize_workspace_internal(window, cx);
 6457        cx.spawn(async move |_| {
 6458            bounds_task.await;
 6459            serialize_task.await;
 6460        })
 6461    }
 6462
 6463    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6464        let project = self.project().read(cx);
 6465        project
 6466            .visible_worktrees(cx)
 6467            .map(|worktree| worktree.read(cx).abs_path())
 6468            .collect::<Vec<_>>()
 6469    }
 6470
 6471    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6472        match member {
 6473            Member::Axis(PaneAxis { members, .. }) => {
 6474                for child in members.iter() {
 6475                    self.remove_panes(child.clone(), window, cx)
 6476                }
 6477            }
 6478            Member::Pane(pane) => {
 6479                self.force_remove_pane(&pane, &None, window, cx);
 6480            }
 6481        }
 6482    }
 6483
 6484    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6485        self.session_id.take();
 6486        self.serialize_workspace_internal(window, cx)
 6487    }
 6488
 6489    fn force_remove_pane(
 6490        &mut self,
 6491        pane: &Entity<Pane>,
 6492        focus_on: &Option<Entity<Pane>>,
 6493        window: &mut Window,
 6494        cx: &mut Context<Workspace>,
 6495    ) {
 6496        self.panes.retain(|p| p != pane);
 6497        if let Some(focus_on) = focus_on {
 6498            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6499        } else if self.active_pane() == pane {
 6500            self.panes
 6501                .last()
 6502                .unwrap()
 6503                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6504        }
 6505        if self.last_active_center_pane == Some(pane.downgrade()) {
 6506            self.last_active_center_pane = None;
 6507        }
 6508        cx.notify();
 6509    }
 6510
 6511    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6512        if self._schedule_serialize_workspace.is_none() {
 6513            self._schedule_serialize_workspace =
 6514                Some(cx.spawn_in(window, async move |this, cx| {
 6515                    cx.background_executor()
 6516                        .timer(SERIALIZATION_THROTTLE_TIME)
 6517                        .await;
 6518                    this.update_in(cx, |this, window, cx| {
 6519                        this._serialize_workspace_task =
 6520                            Some(this.serialize_workspace_internal(window, cx));
 6521                        this._schedule_serialize_workspace.take();
 6522                    })
 6523                    .log_err();
 6524                }));
 6525        }
 6526    }
 6527
 6528    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6529        let Some(database_id) = self.database_id() else {
 6530            return Task::ready(());
 6531        };
 6532
 6533        fn serialize_pane_handle(
 6534            pane_handle: &Entity<Pane>,
 6535            window: &mut Window,
 6536            cx: &mut App,
 6537        ) -> SerializedPane {
 6538            let (items, active, pinned_count) = {
 6539                let pane = pane_handle.read(cx);
 6540                let active_item_id = pane.active_item().map(|item| item.item_id());
 6541                (
 6542                    pane.items()
 6543                        .filter_map(|handle| {
 6544                            let handle = handle.to_serializable_item_handle(cx)?;
 6545
 6546                            Some(SerializedItem {
 6547                                kind: Arc::from(handle.serialized_item_kind()),
 6548                                item_id: handle.item_id().as_u64(),
 6549                                active: Some(handle.item_id()) == active_item_id,
 6550                                preview: pane.is_active_preview_item(handle.item_id()),
 6551                            })
 6552                        })
 6553                        .collect::<Vec<_>>(),
 6554                    pane.has_focus(window, cx),
 6555                    pane.pinned_count(),
 6556                )
 6557            };
 6558
 6559            SerializedPane::new(items, active, pinned_count)
 6560        }
 6561
 6562        fn build_serialized_pane_group(
 6563            pane_group: &Member,
 6564            window: &mut Window,
 6565            cx: &mut App,
 6566        ) -> SerializedPaneGroup {
 6567            match pane_group {
 6568                Member::Axis(PaneAxis {
 6569                    axis,
 6570                    members,
 6571                    flexes,
 6572                    bounding_boxes: _,
 6573                }) => SerializedPaneGroup::Group {
 6574                    axis: SerializedAxis(*axis),
 6575                    children: members
 6576                        .iter()
 6577                        .map(|member| build_serialized_pane_group(member, window, cx))
 6578                        .collect::<Vec<_>>(),
 6579                    flexes: Some(flexes.lock().clone()),
 6580                },
 6581                Member::Pane(pane_handle) => {
 6582                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6583                }
 6584            }
 6585        }
 6586
 6587        fn build_serialized_docks(
 6588            this: &Workspace,
 6589            window: &mut Window,
 6590            cx: &mut App,
 6591        ) -> DockStructure {
 6592            this.capture_dock_state(window, cx)
 6593        }
 6594
 6595        match self.workspace_location(cx) {
 6596            WorkspaceLocation::Location(location, paths) => {
 6597                let breakpoints = self.project.update(cx, |project, cx| {
 6598                    project
 6599                        .breakpoint_store()
 6600                        .read(cx)
 6601                        .all_source_breakpoints(cx)
 6602                });
 6603                let user_toolchains = self
 6604                    .project
 6605                    .read(cx)
 6606                    .user_toolchains(cx)
 6607                    .unwrap_or_default();
 6608
 6609                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6610                let docks = build_serialized_docks(self, window, cx);
 6611                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6612
 6613                let serialized_workspace = SerializedWorkspace {
 6614                    id: database_id,
 6615                    location,
 6616                    paths,
 6617                    center_group,
 6618                    window_bounds,
 6619                    display: Default::default(),
 6620                    docks,
 6621                    centered_layout: self.centered_layout,
 6622                    session_id: self.session_id.clone(),
 6623                    breakpoints,
 6624                    window_id: Some(window.window_handle().window_id().as_u64()),
 6625                    user_toolchains,
 6626                };
 6627
 6628                let db = WorkspaceDb::global(cx);
 6629                window.spawn(cx, async move |_| {
 6630                    db.save_workspace(serialized_workspace).await;
 6631                })
 6632            }
 6633            WorkspaceLocation::DetachFromSession => {
 6634                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6635                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6636                // Save dock state for empty local workspaces
 6637                let docks = build_serialized_docks(self, window, cx);
 6638                let db = WorkspaceDb::global(cx);
 6639                let kvp = db::kvp::KeyValueStore::global(cx);
 6640                window.spawn(cx, async move |_| {
 6641                    db.set_window_open_status(
 6642                        database_id,
 6643                        window_bounds,
 6644                        display.unwrap_or_default(),
 6645                    )
 6646                    .await
 6647                    .log_err();
 6648                    db.set_session_id(database_id, None).await.log_err();
 6649                    persistence::write_default_dock_state(&kvp, docks)
 6650                        .await
 6651                        .log_err();
 6652                })
 6653            }
 6654            WorkspaceLocation::None => {
 6655                // Save dock state for empty non-local workspaces
 6656                let docks = build_serialized_docks(self, window, cx);
 6657                let kvp = db::kvp::KeyValueStore::global(cx);
 6658                window.spawn(cx, async move |_| {
 6659                    persistence::write_default_dock_state(&kvp, docks)
 6660                        .await
 6661                        .log_err();
 6662                })
 6663            }
 6664        }
 6665    }
 6666
 6667    fn has_any_items_open(&self, cx: &App) -> bool {
 6668        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6669    }
 6670
 6671    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6672        let paths = PathList::new(&self.root_paths(cx));
 6673        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6674            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6675        } else if self.project.read(cx).is_local() {
 6676            if !paths.is_empty() || self.has_any_items_open(cx) {
 6677                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6678            } else {
 6679                WorkspaceLocation::DetachFromSession
 6680            }
 6681        } else {
 6682            WorkspaceLocation::None
 6683        }
 6684    }
 6685
 6686    fn update_history(&self, cx: &mut App) {
 6687        let Some(id) = self.database_id() else {
 6688            return;
 6689        };
 6690        if !self.project.read(cx).is_local() {
 6691            return;
 6692        }
 6693        if let Some(manager) = HistoryManager::global(cx) {
 6694            let paths = PathList::new(&self.root_paths(cx));
 6695            manager.update(cx, |this, cx| {
 6696                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6697            });
 6698        }
 6699    }
 6700
 6701    async fn serialize_items(
 6702        this: &WeakEntity<Self>,
 6703        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6704        cx: &mut AsyncWindowContext,
 6705    ) -> Result<()> {
 6706        const CHUNK_SIZE: usize = 200;
 6707
 6708        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6709
 6710        while let Some(items_received) = serializable_items.next().await {
 6711            let unique_items =
 6712                items_received
 6713                    .into_iter()
 6714                    .fold(HashMap::default(), |mut acc, item| {
 6715                        acc.entry(item.item_id()).or_insert(item);
 6716                        acc
 6717                    });
 6718
 6719            // We use into_iter() here so that the references to the items are moved into
 6720            // the tasks and not kept alive while we're sleeping.
 6721            for (_, item) in unique_items.into_iter() {
 6722                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6723                    item.serialize(workspace, false, window, cx)
 6724                }) {
 6725                    cx.background_spawn(async move { task.await.log_err() })
 6726                        .detach();
 6727                }
 6728            }
 6729
 6730            cx.background_executor()
 6731                .timer(SERIALIZATION_THROTTLE_TIME)
 6732                .await;
 6733        }
 6734
 6735        Ok(())
 6736    }
 6737
 6738    pub(crate) fn enqueue_item_serialization(
 6739        &mut self,
 6740        item: Box<dyn SerializableItemHandle>,
 6741    ) -> Result<()> {
 6742        self.serializable_items_tx
 6743            .unbounded_send(item)
 6744            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6745    }
 6746
 6747    pub(crate) fn load_workspace(
 6748        serialized_workspace: SerializedWorkspace,
 6749        paths_to_open: Vec<Option<ProjectPath>>,
 6750        window: &mut Window,
 6751        cx: &mut Context<Workspace>,
 6752    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6753        cx.spawn_in(window, async move |workspace, cx| {
 6754            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6755
 6756            let mut center_group = None;
 6757            let mut center_items = None;
 6758
 6759            // Traverse the splits tree and add to things
 6760            if let Some((group, active_pane, items)) = serialized_workspace
 6761                .center_group
 6762                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6763                .await
 6764            {
 6765                center_items = Some(items);
 6766                center_group = Some((group, active_pane))
 6767            }
 6768
 6769            let mut items_by_project_path = HashMap::default();
 6770            let mut item_ids_by_kind = HashMap::default();
 6771            let mut all_deserialized_items = Vec::default();
 6772            cx.update(|_, cx| {
 6773                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6774                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6775                        item_ids_by_kind
 6776                            .entry(serializable_item_handle.serialized_item_kind())
 6777                            .or_insert(Vec::new())
 6778                            .push(item.item_id().as_u64() as ItemId);
 6779                    }
 6780
 6781                    if let Some(project_path) = item.project_path(cx) {
 6782                        items_by_project_path.insert(project_path, item.clone());
 6783                    }
 6784                    all_deserialized_items.push(item);
 6785                }
 6786            })?;
 6787
 6788            let opened_items = paths_to_open
 6789                .into_iter()
 6790                .map(|path_to_open| {
 6791                    path_to_open
 6792                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6793                })
 6794                .collect::<Vec<_>>();
 6795
 6796            // Remove old panes from workspace panes list
 6797            workspace.update_in(cx, |workspace, window, cx| {
 6798                if let Some((center_group, active_pane)) = center_group {
 6799                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6800
 6801                    // Swap workspace center group
 6802                    workspace.center = PaneGroup::with_root(center_group);
 6803                    workspace.center.set_is_center(true);
 6804                    workspace.center.mark_positions(cx);
 6805
 6806                    if let Some(active_pane) = active_pane {
 6807                        workspace.set_active_pane(&active_pane, window, cx);
 6808                        cx.focus_self(window);
 6809                    } else {
 6810                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6811                    }
 6812                }
 6813
 6814                let docks = serialized_workspace.docks;
 6815
 6816                for (dock, serialized_dock) in [
 6817                    (&mut workspace.right_dock, docks.right),
 6818                    (&mut workspace.left_dock, docks.left),
 6819                    (&mut workspace.bottom_dock, docks.bottom),
 6820                ]
 6821                .iter_mut()
 6822                {
 6823                    dock.update(cx, |dock, cx| {
 6824                        dock.serialized_dock = Some(serialized_dock.clone());
 6825                        dock.restore_state(window, cx);
 6826                    });
 6827                }
 6828
 6829                cx.notify();
 6830            })?;
 6831
 6832            let _ = project
 6833                .update(cx, |project, cx| {
 6834                    project
 6835                        .breakpoint_store()
 6836                        .update(cx, |breakpoint_store, cx| {
 6837                            breakpoint_store
 6838                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6839                        })
 6840                })
 6841                .await;
 6842
 6843            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6844            // after loading the items, we might have different items and in order to avoid
 6845            // the database filling up, we delete items that haven't been loaded now.
 6846            //
 6847            // The items that have been loaded, have been saved after they've been added to the workspace.
 6848            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6849                item_ids_by_kind
 6850                    .into_iter()
 6851                    .map(|(item_kind, loaded_items)| {
 6852                        SerializableItemRegistry::cleanup(
 6853                            item_kind,
 6854                            serialized_workspace.id,
 6855                            loaded_items,
 6856                            window,
 6857                            cx,
 6858                        )
 6859                        .log_err()
 6860                    })
 6861                    .collect::<Vec<_>>()
 6862            })?;
 6863
 6864            futures::future::join_all(clean_up_tasks).await;
 6865
 6866            workspace
 6867                .update_in(cx, |workspace, window, cx| {
 6868                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6869                    workspace.serialize_workspace_internal(window, cx).detach();
 6870
 6871                    // Ensure that we mark the window as edited if we did load dirty items
 6872                    workspace.update_window_edited(window, cx);
 6873                })
 6874                .ok();
 6875
 6876            Ok(opened_items)
 6877        })
 6878    }
 6879
 6880    pub fn key_context(&self, cx: &App) -> KeyContext {
 6881        let mut context = KeyContext::new_with_defaults();
 6882        context.add("Workspace");
 6883        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6884        if let Some(status) = self
 6885            .debugger_provider
 6886            .as_ref()
 6887            .and_then(|provider| provider.active_thread_state(cx))
 6888        {
 6889            match status {
 6890                ThreadStatus::Running | ThreadStatus::Stepping => {
 6891                    context.add("debugger_running");
 6892                }
 6893                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6894                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6895            }
 6896        }
 6897
 6898        if self.left_dock.read(cx).is_open() {
 6899            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6900                context.set("left_dock", active_panel.panel_key());
 6901            }
 6902        }
 6903
 6904        if self.right_dock.read(cx).is_open() {
 6905            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6906                context.set("right_dock", active_panel.panel_key());
 6907            }
 6908        }
 6909
 6910        if self.bottom_dock.read(cx).is_open() {
 6911            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6912                context.set("bottom_dock", active_panel.panel_key());
 6913            }
 6914        }
 6915
 6916        context
 6917    }
 6918
 6919    /// Multiworkspace uses this to add workspace action handling to itself
 6920    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6921        self.add_workspace_actions_listeners(div, window, cx)
 6922            .on_action(cx.listener(
 6923                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6924                    for action in &action_sequence.0 {
 6925                        window.dispatch_action(action.boxed_clone(), cx);
 6926                    }
 6927                },
 6928            ))
 6929            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6930            .on_action(cx.listener(Self::close_all_items_and_panes))
 6931            .on_action(cx.listener(Self::close_item_in_all_panes))
 6932            .on_action(cx.listener(Self::save_all))
 6933            .on_action(cx.listener(Self::send_keystrokes))
 6934            .on_action(cx.listener(Self::add_folder_to_project))
 6935            .on_action(cx.listener(Self::follow_next_collaborator))
 6936            .on_action(cx.listener(Self::activate_pane_at_index))
 6937            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6938            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6939            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6940            .on_action(cx.listener(Self::toggle_theme_mode))
 6941            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6942                let pane = workspace.active_pane().clone();
 6943                workspace.unfollow_in_pane(&pane, window, cx);
 6944            }))
 6945            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6946                workspace
 6947                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6948                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6949            }))
 6950            .on_action(cx.listener(|workspace, _: &FormatAndSave, window, cx| {
 6951                workspace
 6952                    .save_active_item(SaveIntent::FormatAndSave, window, cx)
 6953                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6954            }))
 6955            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6956                workspace
 6957                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6958                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6959            }))
 6960            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6961                workspace
 6962                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6963                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6964            }))
 6965            .on_action(
 6966                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6967                    workspace.activate_previous_pane(window, cx)
 6968                }),
 6969            )
 6970            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6971                workspace.activate_next_pane(window, cx)
 6972            }))
 6973            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6974                workspace.activate_last_pane(window, cx)
 6975            }))
 6976            .on_action(
 6977                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6978                    workspace.activate_next_window(cx)
 6979                }),
 6980            )
 6981            .on_action(
 6982                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6983                    workspace.activate_previous_window(cx)
 6984                }),
 6985            )
 6986            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6987                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6988            }))
 6989            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6990                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6991            }))
 6992            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6993                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6994            }))
 6995            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6996                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6997            }))
 6998            .on_action(cx.listener(
 6999                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 7000                    workspace.move_item_to_pane_in_direction(action, window, cx)
 7001                },
 7002            ))
 7003            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 7004                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 7005            }))
 7006            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 7007                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 7008            }))
 7009            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 7010                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 7011            }))
 7012            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 7013                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 7014            }))
 7015            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 7016                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 7017                    SplitDirection::Down,
 7018                    SplitDirection::Up,
 7019                    SplitDirection::Right,
 7020                    SplitDirection::Left,
 7021                ];
 7022                for dir in DIRECTION_PRIORITY {
 7023                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 7024                        workspace.swap_pane_in_direction(dir, cx);
 7025                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 7026                        break;
 7027                    }
 7028                }
 7029            }))
 7030            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 7031                workspace.move_pane_to_border(SplitDirection::Left, cx)
 7032            }))
 7033            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 7034                workspace.move_pane_to_border(SplitDirection::Right, cx)
 7035            }))
 7036            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 7037                workspace.move_pane_to_border(SplitDirection::Up, cx)
 7038            }))
 7039            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 7040                workspace.move_pane_to_border(SplitDirection::Down, cx)
 7041            }))
 7042            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 7043                this.toggle_dock(DockPosition::Left, window, cx);
 7044            }))
 7045            .on_action(cx.listener(
 7046                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 7047                    workspace.toggle_dock(DockPosition::Right, window, cx);
 7048                },
 7049            ))
 7050            .on_action(cx.listener(
 7051                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 7052                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 7053                },
 7054            ))
 7055            .on_action(cx.listener(
 7056                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 7057                    if !workspace.close_active_dock(window, cx) {
 7058                        cx.propagate();
 7059                    }
 7060                },
 7061            ))
 7062            .on_action(
 7063                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 7064                    workspace.close_all_docks(window, cx);
 7065                }),
 7066            )
 7067            .on_action(cx.listener(Self::toggle_all_docks))
 7068            .on_action(cx.listener(
 7069                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 7070                    workspace.clear_all_notifications(cx);
 7071                },
 7072            ))
 7073            .on_action(cx.listener(
 7074                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 7075                    workspace.clear_navigation_history(window, cx);
 7076                },
 7077            ))
 7078            .on_action(cx.listener(
 7079                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 7080                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 7081                        workspace.suppress_notification(&notification_id, cx);
 7082                    }
 7083                },
 7084            ))
 7085            .on_action(cx.listener(
 7086                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 7087                    workspace.show_worktree_trust_security_modal(true, window, cx);
 7088                },
 7089            ))
 7090            .on_action(
 7091                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 7092                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 7093                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 7094                            trusted_worktrees.clear_trusted_paths()
 7095                        });
 7096                        let db = WorkspaceDb::global(cx);
 7097                        cx.spawn(async move |_, cx| {
 7098                            if db.clear_trusted_worktrees().await.log_err().is_some() {
 7099                                cx.update(|cx| reload(cx));
 7100                            }
 7101                        })
 7102                        .detach();
 7103                    }
 7104                }),
 7105            )
 7106            .on_action(cx.listener(
 7107                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 7108                    workspace.reopen_closed_item(window, cx).detach();
 7109                },
 7110            ))
 7111            .on_action(cx.listener(
 7112                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 7113                    for dock in workspace.all_docks() {
 7114                        if dock.focus_handle(cx).contains_focused(window, cx) {
 7115                            let panel = dock.read(cx).active_panel().cloned();
 7116                            if let Some(panel) = panel {
 7117                                dock.update(cx, |dock, cx| {
 7118                                    dock.set_panel_size_state(
 7119                                        panel.as_ref(),
 7120                                        dock::PanelSizeState::default(),
 7121                                        cx,
 7122                                    );
 7123                                });
 7124                            }
 7125                            return;
 7126                        }
 7127                    }
 7128                },
 7129            ))
 7130            .on_action(cx.listener(
 7131                |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
 7132                    for dock in workspace.all_docks() {
 7133                        let panel = dock.read(cx).visible_panel().cloned();
 7134                        if let Some(panel) = panel {
 7135                            dock.update(cx, |dock, cx| {
 7136                                dock.set_panel_size_state(
 7137                                    panel.as_ref(),
 7138                                    dock::PanelSizeState::default(),
 7139                                    cx,
 7140                                );
 7141                            });
 7142                        }
 7143                    }
 7144                },
 7145            ))
 7146            .on_action(cx.listener(
 7147                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 7148                    adjust_active_dock_size_by_px(
 7149                        px_with_ui_font_fallback(act.px, cx),
 7150                        workspace,
 7151                        window,
 7152                        cx,
 7153                    );
 7154                },
 7155            ))
 7156            .on_action(cx.listener(
 7157                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 7158                    adjust_active_dock_size_by_px(
 7159                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7160                        workspace,
 7161                        window,
 7162                        cx,
 7163                    );
 7164                },
 7165            ))
 7166            .on_action(cx.listener(
 7167                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 7168                    adjust_open_docks_size_by_px(
 7169                        px_with_ui_font_fallback(act.px, cx),
 7170                        workspace,
 7171                        window,
 7172                        cx,
 7173                    );
 7174                },
 7175            ))
 7176            .on_action(cx.listener(
 7177                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 7178                    adjust_open_docks_size_by_px(
 7179                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7180                        workspace,
 7181                        window,
 7182                        cx,
 7183                    );
 7184                },
 7185            ))
 7186            .on_action(cx.listener(Workspace::toggle_centered_layout))
 7187            .on_action(cx.listener(
 7188                |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
 7189                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7190                        let dock = active_dock.read(cx);
 7191                        if let Some(active_panel) = dock.active_panel() {
 7192                            if active_panel.pane(cx).is_none() {
 7193                                let mut recent_pane: Option<Entity<Pane>> = None;
 7194                                let mut recent_timestamp = 0;
 7195                                for pane_handle in workspace.panes() {
 7196                                    let pane = pane_handle.read(cx);
 7197                                    for entry in pane.activation_history() {
 7198                                        if entry.timestamp > recent_timestamp {
 7199                                            recent_timestamp = entry.timestamp;
 7200                                            recent_pane = Some(pane_handle.clone());
 7201                                        }
 7202                                    }
 7203                                }
 7204
 7205                                if let Some(pane) = recent_pane {
 7206                                    let wrap_around = action.wrap_around;
 7207                                    pane.update(cx, |pane, cx| {
 7208                                        let current_index = pane.active_item_index();
 7209                                        let items_len = pane.items_len();
 7210                                        if items_len > 0 {
 7211                                            let next_index = if current_index + 1 < items_len {
 7212                                                current_index + 1
 7213                                            } else if wrap_around {
 7214                                                0
 7215                                            } else {
 7216                                                return;
 7217                                            };
 7218                                            pane.activate_item(
 7219                                                next_index, false, false, window, cx,
 7220                                            );
 7221                                        }
 7222                                    });
 7223                                    return;
 7224                                }
 7225                            }
 7226                        }
 7227                    }
 7228                    cx.propagate();
 7229                },
 7230            ))
 7231            .on_action(cx.listener(
 7232                |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
 7233                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7234                        let dock = active_dock.read(cx);
 7235                        if let Some(active_panel) = dock.active_panel() {
 7236                            if active_panel.pane(cx).is_none() {
 7237                                let mut recent_pane: Option<Entity<Pane>> = None;
 7238                                let mut recent_timestamp = 0;
 7239                                for pane_handle in workspace.panes() {
 7240                                    let pane = pane_handle.read(cx);
 7241                                    for entry in pane.activation_history() {
 7242                                        if entry.timestamp > recent_timestamp {
 7243                                            recent_timestamp = entry.timestamp;
 7244                                            recent_pane = Some(pane_handle.clone());
 7245                                        }
 7246                                    }
 7247                                }
 7248
 7249                                if let Some(pane) = recent_pane {
 7250                                    let wrap_around = action.wrap_around;
 7251                                    pane.update(cx, |pane, cx| {
 7252                                        let current_index = pane.active_item_index();
 7253                                        let items_len = pane.items_len();
 7254                                        if items_len > 0 {
 7255                                            let prev_index = if current_index > 0 {
 7256                                                current_index - 1
 7257                                            } else if wrap_around {
 7258                                                items_len.saturating_sub(1)
 7259                                            } else {
 7260                                                return;
 7261                                            };
 7262                                            pane.activate_item(
 7263                                                prev_index, false, false, window, cx,
 7264                                            );
 7265                                        }
 7266                                    });
 7267                                    return;
 7268                                }
 7269                            }
 7270                        }
 7271                    }
 7272                    cx.propagate();
 7273                },
 7274            ))
 7275            .on_action(cx.listener(
 7276                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 7277                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7278                        let dock = active_dock.read(cx);
 7279                        if let Some(active_panel) = dock.active_panel() {
 7280                            if active_panel.pane(cx).is_none() {
 7281                                let active_pane = workspace.active_pane().clone();
 7282                                active_pane.update(cx, |pane, cx| {
 7283                                    pane.close_active_item(action, window, cx)
 7284                                        .detach_and_log_err(cx);
 7285                                });
 7286                                return;
 7287                            }
 7288                        }
 7289                    }
 7290                    cx.propagate();
 7291                },
 7292            ))
 7293            .on_action(
 7294                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 7295                    let pane = workspace.active_pane().clone();
 7296                    if let Some(item) = pane.read(cx).active_item() {
 7297                        item.toggle_read_only(window, cx);
 7298                    }
 7299                }),
 7300            )
 7301            .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
 7302                workspace.focus_center_pane(window, cx);
 7303            }))
 7304            .on_action(cx.listener(Workspace::cancel))
 7305    }
 7306
 7307    #[cfg(any(test, feature = "test-support"))]
 7308    pub fn set_random_database_id(&mut self) {
 7309        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 7310    }
 7311
 7312    #[cfg(any(test, feature = "test-support"))]
 7313    pub(crate) fn test_new(
 7314        project: Entity<Project>,
 7315        window: &mut Window,
 7316        cx: &mut Context<Self>,
 7317    ) -> Self {
 7318        use node_runtime::NodeRuntime;
 7319        use session::Session;
 7320
 7321        let client = project.read(cx).client();
 7322        let user_store = project.read(cx).user_store();
 7323        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 7324        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 7325        window.activate_window();
 7326        let app_state = Arc::new(AppState {
 7327            languages: project.read(cx).languages().clone(),
 7328            workspace_store,
 7329            client,
 7330            user_store,
 7331            fs: project.read(cx).fs().clone(),
 7332            build_window_options: |_, _| Default::default(),
 7333            node_runtime: NodeRuntime::unavailable(),
 7334            session,
 7335        });
 7336        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 7337        workspace
 7338            .active_pane
 7339            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 7340        workspace
 7341    }
 7342
 7343    pub fn register_action<A: Action>(
 7344        &mut self,
 7345        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 7346    ) -> &mut Self {
 7347        let callback = Arc::new(callback);
 7348
 7349        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 7350            let callback = callback.clone();
 7351            div.on_action(cx.listener(move |workspace, event, window, cx| {
 7352                (callback)(workspace, event, window, cx)
 7353            }))
 7354        }));
 7355        self
 7356    }
 7357    pub fn register_action_renderer(
 7358        &mut self,
 7359        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 7360    ) -> &mut Self {
 7361        self.workspace_actions.push(Box::new(callback));
 7362        self
 7363    }
 7364
 7365    fn add_workspace_actions_listeners(
 7366        &self,
 7367        mut div: Div,
 7368        window: &mut Window,
 7369        cx: &mut Context<Self>,
 7370    ) -> Div {
 7371        for action in self.workspace_actions.iter() {
 7372            div = (action)(div, self, window, cx)
 7373        }
 7374        div
 7375    }
 7376
 7377    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 7378        self.modal_layer.read(cx).has_active_modal()
 7379    }
 7380
 7381    pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
 7382        self.modal_layer
 7383            .read(cx)
 7384            .is_active_modal_command_palette(cx)
 7385    }
 7386
 7387    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7388        self.modal_layer.read(cx).active_modal()
 7389    }
 7390
 7391    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7392    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7393    /// If no modal is active, the new modal will be shown.
 7394    ///
 7395    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7396    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7397    /// will not be shown.
 7398    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7399    where
 7400        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7401    {
 7402        self.modal_layer.update(cx, |modal_layer, cx| {
 7403            modal_layer.toggle_modal(window, cx, build)
 7404        })
 7405    }
 7406
 7407    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7408        self.modal_layer
 7409            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7410    }
 7411
 7412    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7413        self.toast_layer
 7414            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7415    }
 7416
 7417    pub fn toggle_centered_layout(
 7418        &mut self,
 7419        _: &ToggleCenteredLayout,
 7420        _: &mut Window,
 7421        cx: &mut Context<Self>,
 7422    ) {
 7423        self.centered_layout = !self.centered_layout;
 7424        if let Some(database_id) = self.database_id() {
 7425            let db = WorkspaceDb::global(cx);
 7426            let centered_layout = self.centered_layout;
 7427            cx.background_spawn(async move {
 7428                db.set_centered_layout(database_id, centered_layout).await
 7429            })
 7430            .detach_and_log_err(cx);
 7431        }
 7432        cx.notify();
 7433    }
 7434
 7435    fn adjust_padding(padding: Option<f32>) -> f32 {
 7436        padding
 7437            .unwrap_or(CenteredPaddingSettings::default().0)
 7438            .clamp(
 7439                CenteredPaddingSettings::MIN_PADDING,
 7440                CenteredPaddingSettings::MAX_PADDING,
 7441            )
 7442    }
 7443
 7444    fn render_dock(
 7445        &self,
 7446        position: DockPosition,
 7447        dock: &Entity<Dock>,
 7448        window: &mut Window,
 7449        cx: &mut App,
 7450    ) -> Option<Div> {
 7451        if self.zoomed_position == Some(position) {
 7452            return None;
 7453        }
 7454
 7455        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7456            let pane = panel.pane(cx)?;
 7457            let follower_states = &self.follower_states;
 7458            leader_border_for_pane(follower_states, &pane, window, cx)
 7459        });
 7460
 7461        let mut container = div()
 7462            .flex()
 7463            .overflow_hidden()
 7464            .flex_none()
 7465            .child(dock.clone())
 7466            .children(leader_border);
 7467
 7468        // Apply sizing only when the dock is open. When closed the dock is still
 7469        // included in the element tree so its focus handle remains mounted — without
 7470        // this, toggle_panel_focus cannot focus the panel when the dock is closed.
 7471        let dock = dock.read(cx);
 7472        if let Some(panel) = dock.visible_panel() {
 7473            let size_state = dock.stored_panel_size_state(panel.as_ref());
 7474            let min_size = panel.min_size(window, cx);
 7475            if position.axis() == Axis::Horizontal {
 7476                let use_flexible = panel.has_flexible_size(window, cx);
 7477                let flex_grow = if use_flexible {
 7478                    size_state
 7479                        .and_then(|state| state.flex)
 7480                        .or_else(|| self.default_dock_flex(position))
 7481                } else {
 7482                    None
 7483                };
 7484                if let Some(grow) = flex_grow {
 7485                    let grow = grow.max(0.001);
 7486                    let style = container.style();
 7487                    style.flex_grow = Some(grow);
 7488                    style.flex_shrink = Some(1.0);
 7489                    style.flex_basis = Some(relative(0.).into());
 7490                } else {
 7491                    let size = size_state
 7492                        .and_then(|state| state.size)
 7493                        .unwrap_or_else(|| panel.default_size(window, cx));
 7494                    container = container.w(size);
 7495                }
 7496                if let Some(min) = min_size {
 7497                    container = container.min_w(min);
 7498                }
 7499            } else {
 7500                let size = size_state
 7501                    .and_then(|state| state.size)
 7502                    .unwrap_or_else(|| panel.default_size(window, cx));
 7503                container = container.h(size);
 7504            }
 7505        }
 7506
 7507        Some(container)
 7508    }
 7509
 7510    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7511        window
 7512            .root::<MultiWorkspace>()
 7513            .flatten()
 7514            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7515    }
 7516
 7517    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7518        self.zoomed.as_ref()
 7519    }
 7520
 7521    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7522        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7523            return;
 7524        };
 7525        let windows = cx.windows();
 7526        let next_window =
 7527            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7528                || {
 7529                    windows
 7530                        .iter()
 7531                        .cycle()
 7532                        .skip_while(|window| window.window_id() != current_window_id)
 7533                        .nth(1)
 7534                },
 7535            );
 7536
 7537        if let Some(window) = next_window {
 7538            window
 7539                .update(cx, |_, window, _| window.activate_window())
 7540                .ok();
 7541        }
 7542    }
 7543
 7544    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7545        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7546            return;
 7547        };
 7548        let windows = cx.windows();
 7549        let prev_window =
 7550            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7551                || {
 7552                    windows
 7553                        .iter()
 7554                        .rev()
 7555                        .cycle()
 7556                        .skip_while(|window| window.window_id() != current_window_id)
 7557                        .nth(1)
 7558                },
 7559            );
 7560
 7561        if let Some(window) = prev_window {
 7562            window
 7563                .update(cx, |_, window, _| window.activate_window())
 7564                .ok();
 7565        }
 7566    }
 7567
 7568    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7569        if cx.stop_active_drag(window) {
 7570        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7571            dismiss_app_notification(&notification_id, cx);
 7572        } else {
 7573            cx.propagate();
 7574        }
 7575    }
 7576
 7577    fn resize_dock(
 7578        &mut self,
 7579        dock_pos: DockPosition,
 7580        new_size: Pixels,
 7581        window: &mut Window,
 7582        cx: &mut Context<Self>,
 7583    ) {
 7584        match dock_pos {
 7585            DockPosition::Left => self.resize_left_dock(new_size, window, cx),
 7586            DockPosition::Right => self.resize_right_dock(new_size, window, cx),
 7587            DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
 7588        }
 7589    }
 7590
 7591    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7592        let workspace_width = self.bounds.size.width;
 7593        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7594
 7595        self.right_dock.read_with(cx, |right_dock, cx| {
 7596            let right_dock_size = right_dock
 7597                .stored_active_panel_size(window, cx)
 7598                .unwrap_or(Pixels::ZERO);
 7599            if right_dock_size + size > workspace_width {
 7600                size = workspace_width - right_dock_size
 7601            }
 7602        });
 7603
 7604        let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
 7605        self.left_dock.update(cx, |left_dock, cx| {
 7606            if WorkspaceSettings::get_global(cx)
 7607                .resize_all_panels_in_dock
 7608                .contains(&DockPosition::Left)
 7609            {
 7610                left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7611            } else {
 7612                left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7613            }
 7614        });
 7615    }
 7616
 7617    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7618        let workspace_width = self.bounds.size.width;
 7619        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7620        self.left_dock.read_with(cx, |left_dock, cx| {
 7621            let left_dock_size = left_dock
 7622                .stored_active_panel_size(window, cx)
 7623                .unwrap_or(Pixels::ZERO);
 7624            if left_dock_size + size > workspace_width {
 7625                size = workspace_width - left_dock_size
 7626            }
 7627        });
 7628        let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
 7629        self.right_dock.update(cx, |right_dock, cx| {
 7630            if WorkspaceSettings::get_global(cx)
 7631                .resize_all_panels_in_dock
 7632                .contains(&DockPosition::Right)
 7633            {
 7634                right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7635            } else {
 7636                right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7637            }
 7638        });
 7639    }
 7640
 7641    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7642        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7643        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7644            if WorkspaceSettings::get_global(cx)
 7645                .resize_all_panels_in_dock
 7646                .contains(&DockPosition::Bottom)
 7647            {
 7648                bottom_dock.resize_all_panels(Some(size), None, window, cx);
 7649            } else {
 7650                bottom_dock.resize_active_panel(Some(size), None, window, cx);
 7651            }
 7652        });
 7653    }
 7654
 7655    fn toggle_edit_predictions_all_files(
 7656        &mut self,
 7657        _: &ToggleEditPrediction,
 7658        _window: &mut Window,
 7659        cx: &mut Context<Self>,
 7660    ) {
 7661        let fs = self.project().read(cx).fs().clone();
 7662        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7663        update_settings_file(fs, cx, move |file, _| {
 7664            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7665        });
 7666    }
 7667
 7668    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7669        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7670        let next_mode = match current_mode {
 7671            Some(theme_settings::ThemeAppearanceMode::Light) => {
 7672                theme_settings::ThemeAppearanceMode::Dark
 7673            }
 7674            Some(theme_settings::ThemeAppearanceMode::Dark) => {
 7675                theme_settings::ThemeAppearanceMode::Light
 7676            }
 7677            Some(theme_settings::ThemeAppearanceMode::System) | None => {
 7678                match cx.theme().appearance() {
 7679                    theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
 7680                    theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
 7681                }
 7682            }
 7683        };
 7684
 7685        let fs = self.project().read(cx).fs().clone();
 7686        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7687            theme_settings::set_mode(settings, next_mode);
 7688        });
 7689    }
 7690
 7691    pub fn show_worktree_trust_security_modal(
 7692        &mut self,
 7693        toggle: bool,
 7694        window: &mut Window,
 7695        cx: &mut Context<Self>,
 7696    ) {
 7697        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7698            if toggle {
 7699                security_modal.update(cx, |security_modal, cx| {
 7700                    security_modal.dismiss(cx);
 7701                })
 7702            } else {
 7703                security_modal.update(cx, |security_modal, cx| {
 7704                    security_modal.refresh_restricted_paths(cx);
 7705                });
 7706            }
 7707        } else {
 7708            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7709                .map(|trusted_worktrees| {
 7710                    trusted_worktrees
 7711                        .read(cx)
 7712                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7713                })
 7714                .unwrap_or(false);
 7715            if has_restricted_worktrees {
 7716                let project = self.project().read(cx);
 7717                let remote_host = project
 7718                    .remote_connection_options(cx)
 7719                    .map(RemoteHostLocation::from);
 7720                let worktree_store = project.worktree_store().downgrade();
 7721                self.toggle_modal(window, cx, |_, cx| {
 7722                    SecurityModal::new(worktree_store, remote_host, cx)
 7723                });
 7724            }
 7725        }
 7726    }
 7727}
 7728
 7729pub trait AnyActiveCall {
 7730    fn entity(&self) -> AnyEntity;
 7731    fn is_in_room(&self, _: &App) -> bool;
 7732    fn room_id(&self, _: &App) -> Option<u64>;
 7733    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7734    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7735    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7736    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7737    fn is_sharing_project(&self, _: &App) -> bool;
 7738    fn has_remote_participants(&self, _: &App) -> bool;
 7739    fn local_participant_is_guest(&self, _: &App) -> bool;
 7740    fn client(&self, _: &App) -> Arc<Client>;
 7741    fn share_on_join(&self, _: &App) -> bool;
 7742    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7743    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7744    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7745    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7746    fn join_project(
 7747        &self,
 7748        _: u64,
 7749        _: Arc<LanguageRegistry>,
 7750        _: Arc<dyn Fs>,
 7751        _: &mut App,
 7752    ) -> Task<Result<Entity<Project>>>;
 7753    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7754    fn subscribe(
 7755        &self,
 7756        _: &mut Window,
 7757        _: &mut Context<Workspace>,
 7758        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7759    ) -> Subscription;
 7760    fn create_shared_screen(
 7761        &self,
 7762        _: PeerId,
 7763        _: &Entity<Pane>,
 7764        _: &mut Window,
 7765        _: &mut App,
 7766    ) -> Option<Entity<SharedScreen>>;
 7767}
 7768
 7769#[derive(Clone)]
 7770pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7771impl Global for GlobalAnyActiveCall {}
 7772
 7773impl GlobalAnyActiveCall {
 7774    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7775        cx.try_global()
 7776    }
 7777
 7778    pub(crate) fn global(cx: &App) -> &Self {
 7779        cx.global()
 7780    }
 7781}
 7782
 7783/// Workspace-local view of a remote participant's location.
 7784#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7785pub enum ParticipantLocation {
 7786    SharedProject { project_id: u64 },
 7787    UnsharedProject,
 7788    External,
 7789}
 7790
 7791impl ParticipantLocation {
 7792    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7793        match location
 7794            .and_then(|l| l.variant)
 7795            .context("participant location was not provided")?
 7796        {
 7797            proto::participant_location::Variant::SharedProject(project) => {
 7798                Ok(Self::SharedProject {
 7799                    project_id: project.id,
 7800                })
 7801            }
 7802            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7803            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7804        }
 7805    }
 7806}
 7807/// Workspace-local view of a remote collaborator's state.
 7808/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7809#[derive(Clone)]
 7810pub struct RemoteCollaborator {
 7811    pub user: Arc<User>,
 7812    pub peer_id: PeerId,
 7813    pub location: ParticipantLocation,
 7814    pub participant_index: ParticipantIndex,
 7815}
 7816
 7817pub enum ActiveCallEvent {
 7818    ParticipantLocationChanged { participant_id: PeerId },
 7819    RemoteVideoTracksChanged { participant_id: PeerId },
 7820}
 7821
 7822fn leader_border_for_pane(
 7823    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7824    pane: &Entity<Pane>,
 7825    _: &Window,
 7826    cx: &App,
 7827) -> Option<Div> {
 7828    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7829        if state.pane() == pane {
 7830            Some((*leader_id, state))
 7831        } else {
 7832            None
 7833        }
 7834    })?;
 7835
 7836    let mut leader_color = match leader_id {
 7837        CollaboratorId::PeerId(leader_peer_id) => {
 7838            let leader = GlobalAnyActiveCall::try_global(cx)?
 7839                .0
 7840                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7841
 7842            cx.theme()
 7843                .players()
 7844                .color_for_participant(leader.participant_index.0)
 7845                .cursor
 7846        }
 7847        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7848    };
 7849    leader_color.fade_out(0.3);
 7850    Some(
 7851        div()
 7852            .absolute()
 7853            .size_full()
 7854            .left_0()
 7855            .top_0()
 7856            .border_2()
 7857            .border_color(leader_color),
 7858    )
 7859}
 7860
 7861fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7862    ZED_WINDOW_POSITION
 7863        .zip(*ZED_WINDOW_SIZE)
 7864        .map(|(position, size)| Bounds {
 7865            origin: position,
 7866            size,
 7867        })
 7868}
 7869
 7870fn open_items(
 7871    serialized_workspace: Option<SerializedWorkspace>,
 7872    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7873    window: &mut Window,
 7874    cx: &mut Context<Workspace>,
 7875) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7876    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7877        Workspace::load_workspace(
 7878            serialized_workspace,
 7879            project_paths_to_open
 7880                .iter()
 7881                .map(|(_, project_path)| project_path)
 7882                .cloned()
 7883                .collect(),
 7884            window,
 7885            cx,
 7886        )
 7887    });
 7888
 7889    cx.spawn_in(window, async move |workspace, cx| {
 7890        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7891
 7892        if let Some(restored_items) = restored_items {
 7893            let restored_items = restored_items.await?;
 7894
 7895            let restored_project_paths = restored_items
 7896                .iter()
 7897                .filter_map(|item| {
 7898                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7899                        .ok()
 7900                        .flatten()
 7901                })
 7902                .collect::<HashSet<_>>();
 7903
 7904            for restored_item in restored_items {
 7905                opened_items.push(restored_item.map(Ok));
 7906            }
 7907
 7908            project_paths_to_open
 7909                .iter_mut()
 7910                .for_each(|(_, project_path)| {
 7911                    if let Some(project_path_to_open) = project_path
 7912                        && restored_project_paths.contains(project_path_to_open)
 7913                    {
 7914                        *project_path = None;
 7915                    }
 7916                });
 7917        } else {
 7918            for _ in 0..project_paths_to_open.len() {
 7919                opened_items.push(None);
 7920            }
 7921        }
 7922        assert!(opened_items.len() == project_paths_to_open.len());
 7923
 7924        let tasks =
 7925            project_paths_to_open
 7926                .into_iter()
 7927                .enumerate()
 7928                .map(|(ix, (abs_path, project_path))| {
 7929                    let workspace = workspace.clone();
 7930                    cx.spawn(async move |cx| {
 7931                        let file_project_path = project_path?;
 7932                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7933                            workspace.project().update(cx, |project, cx| {
 7934                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7935                            })
 7936                        });
 7937
 7938                        // We only want to open file paths here. If one of the items
 7939                        // here is a directory, it was already opened further above
 7940                        // with a `find_or_create_worktree`.
 7941                        if let Ok(task) = abs_path_task
 7942                            && task.await.is_none_or(|p| p.is_file())
 7943                        {
 7944                            return Some((
 7945                                ix,
 7946                                workspace
 7947                                    .update_in(cx, |workspace, window, cx| {
 7948                                        workspace.open_path(
 7949                                            file_project_path,
 7950                                            None,
 7951                                            true,
 7952                                            window,
 7953                                            cx,
 7954                                        )
 7955                                    })
 7956                                    .log_err()?
 7957                                    .await,
 7958                            ));
 7959                        }
 7960                        None
 7961                    })
 7962                });
 7963
 7964        let tasks = tasks.collect::<Vec<_>>();
 7965
 7966        let tasks = futures::future::join_all(tasks);
 7967        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7968            opened_items[ix] = Some(path_open_result);
 7969        }
 7970
 7971        Ok(opened_items)
 7972    })
 7973}
 7974
 7975#[derive(Clone)]
 7976enum ActivateInDirectionTarget {
 7977    Pane(Entity<Pane>),
 7978    Dock(Entity<Dock>),
 7979    Sidebar(FocusHandle),
 7980}
 7981
 7982fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7983    window
 7984        .update(cx, |multi_workspace, _, cx| {
 7985            let workspace = multi_workspace.workspace().clone();
 7986            workspace.update(cx, |workspace, cx| {
 7987                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7988                    struct DatabaseFailedNotification;
 7989
 7990                    workspace.show_notification(
 7991                        NotificationId::unique::<DatabaseFailedNotification>(),
 7992                        cx,
 7993                        |cx| {
 7994                            cx.new(|cx| {
 7995                                MessageNotification::new("Failed to load the database file.", cx)
 7996                                    .primary_message("File an Issue")
 7997                                    .primary_icon(IconName::Plus)
 7998                                    .primary_on_click(|window, cx| {
 7999                                        window.dispatch_action(Box::new(FileBugReport), cx)
 8000                                    })
 8001                            })
 8002                        },
 8003                    );
 8004                }
 8005            });
 8006        })
 8007        .log_err();
 8008}
 8009
 8010fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 8011    if val == 0 {
 8012        ThemeSettings::get_global(cx).ui_font_size(cx)
 8013    } else {
 8014        px(val as f32)
 8015    }
 8016}
 8017
 8018fn adjust_active_dock_size_by_px(
 8019    px: Pixels,
 8020    workspace: &mut Workspace,
 8021    window: &mut Window,
 8022    cx: &mut Context<Workspace>,
 8023) {
 8024    let Some(active_dock) = workspace
 8025        .all_docks()
 8026        .into_iter()
 8027        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 8028    else {
 8029        return;
 8030    };
 8031    let dock = active_dock.read(cx);
 8032    let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
 8033        return;
 8034    };
 8035    workspace.resize_dock(dock.position(), panel_size + px, window, cx);
 8036}
 8037
 8038fn adjust_open_docks_size_by_px(
 8039    px: Pixels,
 8040    workspace: &mut Workspace,
 8041    window: &mut Window,
 8042    cx: &mut Context<Workspace>,
 8043) {
 8044    let docks = workspace
 8045        .all_docks()
 8046        .into_iter()
 8047        .filter_map(|dock_entity| {
 8048            let dock = dock_entity.read(cx);
 8049            if dock.is_open() {
 8050                let dock_pos = dock.position();
 8051                let panel_size = workspace.dock_size(&dock, window, cx)?;
 8052                Some((dock_pos, panel_size + px))
 8053            } else {
 8054                None
 8055            }
 8056        })
 8057        .collect::<Vec<_>>();
 8058
 8059    for (position, new_size) in docks {
 8060        workspace.resize_dock(position, new_size, window, cx);
 8061    }
 8062}
 8063
 8064impl Focusable for Workspace {
 8065    fn focus_handle(&self, cx: &App) -> FocusHandle {
 8066        self.active_pane.focus_handle(cx)
 8067    }
 8068}
 8069
 8070#[derive(Clone)]
 8071struct DraggedDock(DockPosition);
 8072
 8073impl Render for DraggedDock {
 8074    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 8075        gpui::Empty
 8076    }
 8077}
 8078
 8079impl Render for Workspace {
 8080    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 8081        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 8082        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 8083            log::info!("Rendered first frame");
 8084        }
 8085
 8086        let centered_layout = self.centered_layout
 8087            && self.center.panes().len() == 1
 8088            && self.active_item(cx).is_some();
 8089        let render_padding = |size| {
 8090            (size > 0.0).then(|| {
 8091                div()
 8092                    .h_full()
 8093                    .w(relative(size))
 8094                    .bg(cx.theme().colors().editor_background)
 8095                    .border_color(cx.theme().colors().pane_group_border)
 8096            })
 8097        };
 8098        let paddings = if centered_layout {
 8099            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 8100            (
 8101                render_padding(Self::adjust_padding(
 8102                    settings.left_padding.map(|padding| padding.0),
 8103                )),
 8104                render_padding(Self::adjust_padding(
 8105                    settings.right_padding.map(|padding| padding.0),
 8106                )),
 8107            )
 8108        } else {
 8109            (None, None)
 8110        };
 8111        let ui_font = theme_settings::setup_ui_font(window, cx);
 8112
 8113        let theme = cx.theme().clone();
 8114        let colors = theme.colors();
 8115        let notification_entities = self
 8116            .notifications
 8117            .iter()
 8118            .map(|(_, notification)| notification.entity_id())
 8119            .collect::<Vec<_>>();
 8120        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 8121
 8122        div()
 8123            .relative()
 8124            .size_full()
 8125            .flex()
 8126            .flex_col()
 8127            .font(ui_font)
 8128            .gap_0()
 8129                .justify_start()
 8130                .items_start()
 8131                .text_color(colors.text)
 8132                .overflow_hidden()
 8133                .children(self.titlebar_item.clone())
 8134                .on_modifiers_changed(move |_, _, cx| {
 8135                    for &id in &notification_entities {
 8136                        cx.notify(id);
 8137                    }
 8138                })
 8139                .child(
 8140                    div()
 8141                        .size_full()
 8142                        .relative()
 8143                        .flex_1()
 8144                        .flex()
 8145                        .flex_col()
 8146                        .child(
 8147                            div()
 8148                                .id("workspace")
 8149                                .bg(colors.background)
 8150                                .relative()
 8151                                .flex_1()
 8152                                .w_full()
 8153                                .flex()
 8154                                .flex_col()
 8155                                .overflow_hidden()
 8156                                .border_t_1()
 8157                                .border_b_1()
 8158                                .border_color(colors.border)
 8159                                .child({
 8160                                    let this = cx.entity();
 8161                                    canvas(
 8162                                        move |bounds, window, cx| {
 8163                                            this.update(cx, |this, cx| {
 8164                                                let bounds_changed = this.bounds != bounds;
 8165                                                this.bounds = bounds;
 8166
 8167                                                if bounds_changed {
 8168                                                    this.left_dock.update(cx, |dock, cx| {
 8169                                                        dock.clamp_panel_size(
 8170                                                            bounds.size.width,
 8171                                                            window,
 8172                                                            cx,
 8173                                                        )
 8174                                                    });
 8175
 8176                                                    this.right_dock.update(cx, |dock, cx| {
 8177                                                        dock.clamp_panel_size(
 8178                                                            bounds.size.width,
 8179                                                            window,
 8180                                                            cx,
 8181                                                        )
 8182                                                    });
 8183
 8184                                                    this.bottom_dock.update(cx, |dock, cx| {
 8185                                                        dock.clamp_panel_size(
 8186                                                            bounds.size.height,
 8187                                                            window,
 8188                                                            cx,
 8189                                                        )
 8190                                                    });
 8191                                                }
 8192                                            })
 8193                                        },
 8194                                        |_, _, _, _| {},
 8195                                    )
 8196                                    .absolute()
 8197                                    .size_full()
 8198                                })
 8199                                .when(self.zoomed.is_none(), |this| {
 8200                                    this.on_drag_move(cx.listener(
 8201                                        move |workspace,
 8202                                              e: &DragMoveEvent<DraggedDock>,
 8203                                              window,
 8204                                              cx| {
 8205                                            if workspace.previous_dock_drag_coordinates
 8206                                                != Some(e.event.position)
 8207                                            {
 8208                                                workspace.previous_dock_drag_coordinates =
 8209                                                    Some(e.event.position);
 8210
 8211                                                match e.drag(cx).0 {
 8212                                                    DockPosition::Left => {
 8213                                                        workspace.resize_left_dock(
 8214                                                            e.event.position.x
 8215                                                                - workspace.bounds.left(),
 8216                                                            window,
 8217                                                            cx,
 8218                                                        );
 8219                                                    }
 8220                                                    DockPosition::Right => {
 8221                                                        workspace.resize_right_dock(
 8222                                                            workspace.bounds.right()
 8223                                                                - e.event.position.x,
 8224                                                            window,
 8225                                                            cx,
 8226                                                        );
 8227                                                    }
 8228                                                    DockPosition::Bottom => {
 8229                                                        workspace.resize_bottom_dock(
 8230                                                            workspace.bounds.bottom()
 8231                                                                - e.event.position.y,
 8232                                                            window,
 8233                                                            cx,
 8234                                                        );
 8235                                                    }
 8236                                                };
 8237                                                workspace.serialize_workspace(window, cx);
 8238                                            }
 8239                                        },
 8240                                    ))
 8241
 8242                                })
 8243                                .child({
 8244                                    match bottom_dock_layout {
 8245                                        BottomDockLayout::Full => div()
 8246                                            .flex()
 8247                                            .flex_col()
 8248                                            .h_full()
 8249                                            .child(
 8250                                                div()
 8251                                                    .flex()
 8252                                                    .flex_row()
 8253                                                    .flex_1()
 8254                                                    .overflow_hidden()
 8255                                                    .children(self.render_dock(
 8256                                                        DockPosition::Left,
 8257                                                        &self.left_dock,
 8258                                                        window,
 8259                                                        cx,
 8260                                                    ))
 8261
 8262                                                    .child(
 8263                                                        div()
 8264                                                            .flex()
 8265                                                            .flex_col()
 8266                                                            .flex_1()
 8267                                                            .overflow_hidden()
 8268                                                            .child(
 8269                                                                h_flex()
 8270                                                                    .flex_1()
 8271                                                                    .when_some(
 8272                                                                        paddings.0,
 8273                                                                        |this, p| {
 8274                                                                            this.child(
 8275                                                                                p.border_r_1(),
 8276                                                                            )
 8277                                                                        },
 8278                                                                    )
 8279                                                                    .child(self.center.render(
 8280                                                                        self.zoomed.as_ref(),
 8281                                                                        &PaneRenderContext {
 8282                                                                            follower_states:
 8283                                                                                &self.follower_states,
 8284                                                                            active_call: self.active_call(),
 8285                                                                            active_pane: &self.active_pane,
 8286                                                                            app_state: &self.app_state,
 8287                                                                            project: &self.project,
 8288                                                                            workspace: &self.weak_self,
 8289                                                                        },
 8290                                                                        window,
 8291                                                                        cx,
 8292                                                                    ))
 8293                                                                    .when_some(
 8294                                                                        paddings.1,
 8295                                                                        |this, p| {
 8296                                                                            this.child(
 8297                                                                                p.border_l_1(),
 8298                                                                            )
 8299                                                                        },
 8300                                                                    ),
 8301                                                            ),
 8302                                                    )
 8303
 8304                                                    .children(self.render_dock(
 8305                                                        DockPosition::Right,
 8306                                                        &self.right_dock,
 8307                                                        window,
 8308                                                        cx,
 8309                                                    )),
 8310                                            )
 8311                                            .child(div().w_full().children(self.render_dock(
 8312                                                DockPosition::Bottom,
 8313                                                &self.bottom_dock,
 8314                                                window,
 8315                                                cx
 8316                                            ))),
 8317
 8318                                        BottomDockLayout::LeftAligned => div()
 8319                                            .flex()
 8320                                            .flex_row()
 8321                                            .h_full()
 8322                                            .child(
 8323                                                div()
 8324                                                    .flex()
 8325                                                    .flex_col()
 8326                                                    .flex_1()
 8327                                                    .h_full()
 8328                                                    .child(
 8329                                                        div()
 8330                                                            .flex()
 8331                                                            .flex_row()
 8332                                                            .flex_1()
 8333                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 8334
 8335                                                            .child(
 8336                                                                div()
 8337                                                                    .flex()
 8338                                                                    .flex_col()
 8339                                                                    .flex_1()
 8340                                                                    .overflow_hidden()
 8341                                                                    .child(
 8342                                                                        h_flex()
 8343                                                                            .flex_1()
 8344                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8345                                                                            .child(self.center.render(
 8346                                                                                self.zoomed.as_ref(),
 8347                                                                                &PaneRenderContext {
 8348                                                                                    follower_states:
 8349                                                                                        &self.follower_states,
 8350                                                                                    active_call: self.active_call(),
 8351                                                                                    active_pane: &self.active_pane,
 8352                                                                                    app_state: &self.app_state,
 8353                                                                                    project: &self.project,
 8354                                                                                    workspace: &self.weak_self,
 8355                                                                                },
 8356                                                                                window,
 8357                                                                                cx,
 8358                                                                            ))
 8359                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8360                                                                    )
 8361                                                            )
 8362
 8363                                                    )
 8364                                                    .child(
 8365                                                        div()
 8366                                                            .w_full()
 8367                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8368                                                    ),
 8369                                            )
 8370                                            .children(self.render_dock(
 8371                                                DockPosition::Right,
 8372                                                &self.right_dock,
 8373                                                window,
 8374                                                cx,
 8375                                            )),
 8376                                        BottomDockLayout::RightAligned => div()
 8377                                            .flex()
 8378                                            .flex_row()
 8379                                            .h_full()
 8380                                            .children(self.render_dock(
 8381                                                DockPosition::Left,
 8382                                                &self.left_dock,
 8383                                                window,
 8384                                                cx,
 8385                                            ))
 8386
 8387                                            .child(
 8388                                                div()
 8389                                                    .flex()
 8390                                                    .flex_col()
 8391                                                    .flex_1()
 8392                                                    .h_full()
 8393                                                    .child(
 8394                                                        div()
 8395                                                            .flex()
 8396                                                            .flex_row()
 8397                                                            .flex_1()
 8398                                                            .child(
 8399                                                                div()
 8400                                                                    .flex()
 8401                                                                    .flex_col()
 8402                                                                    .flex_1()
 8403                                                                    .overflow_hidden()
 8404                                                                    .child(
 8405                                                                        h_flex()
 8406                                                                            .flex_1()
 8407                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8408                                                                            .child(self.center.render(
 8409                                                                                self.zoomed.as_ref(),
 8410                                                                                &PaneRenderContext {
 8411                                                                                    follower_states:
 8412                                                                                        &self.follower_states,
 8413                                                                                    active_call: self.active_call(),
 8414                                                                                    active_pane: &self.active_pane,
 8415                                                                                    app_state: &self.app_state,
 8416                                                                                    project: &self.project,
 8417                                                                                    workspace: &self.weak_self,
 8418                                                                                },
 8419                                                                                window,
 8420                                                                                cx,
 8421                                                                            ))
 8422                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8423                                                                    )
 8424                                                            )
 8425
 8426                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 8427                                                    )
 8428                                                    .child(
 8429                                                        div()
 8430                                                            .w_full()
 8431                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8432                                                    ),
 8433                                            ),
 8434                                        BottomDockLayout::Contained => div()
 8435                                            .flex()
 8436                                            .flex_row()
 8437                                            .h_full()
 8438                                            .children(self.render_dock(
 8439                                                DockPosition::Left,
 8440                                                &self.left_dock,
 8441                                                window,
 8442                                                cx,
 8443                                            ))
 8444
 8445                                            .child(
 8446                                                div()
 8447                                                    .flex()
 8448                                                    .flex_col()
 8449                                                    .flex_1()
 8450                                                    .overflow_hidden()
 8451                                                    .child(
 8452                                                        h_flex()
 8453                                                            .flex_1()
 8454                                                            .when_some(paddings.0, |this, p| {
 8455                                                                this.child(p.border_r_1())
 8456                                                            })
 8457                                                            .child(self.center.render(
 8458                                                                self.zoomed.as_ref(),
 8459                                                                &PaneRenderContext {
 8460                                                                    follower_states:
 8461                                                                        &self.follower_states,
 8462                                                                    active_call: self.active_call(),
 8463                                                                    active_pane: &self.active_pane,
 8464                                                                    app_state: &self.app_state,
 8465                                                                    project: &self.project,
 8466                                                                    workspace: &self.weak_self,
 8467                                                                },
 8468                                                                window,
 8469                                                                cx,
 8470                                                            ))
 8471                                                            .when_some(paddings.1, |this, p| {
 8472                                                                this.child(p.border_l_1())
 8473                                                            }),
 8474                                                    )
 8475                                                    .children(self.render_dock(
 8476                                                        DockPosition::Bottom,
 8477                                                        &self.bottom_dock,
 8478                                                        window,
 8479                                                        cx,
 8480                                                    )),
 8481                                            )
 8482
 8483                                            .children(self.render_dock(
 8484                                                DockPosition::Right,
 8485                                                &self.right_dock,
 8486                                                window,
 8487                                                cx,
 8488                                            )),
 8489                                    }
 8490                                })
 8491                                .children(self.zoomed.as_ref().and_then(|view| {
 8492                                    let zoomed_view = view.upgrade()?;
 8493                                    let div = div()
 8494                                        .occlude()
 8495                                        .absolute()
 8496                                        .overflow_hidden()
 8497                                        .border_color(colors.border)
 8498                                        .bg(colors.background)
 8499                                        .child(zoomed_view)
 8500                                        .inset_0()
 8501                                        .shadow_lg();
 8502
 8503                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8504                                       return Some(div);
 8505                                    }
 8506
 8507                                    Some(match self.zoomed_position {
 8508                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8509                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8510                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8511                                        None => {
 8512                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8513                                        }
 8514                                    })
 8515                                }))
 8516                                .children(self.render_notifications(window, cx)),
 8517                        )
 8518                        .when(self.status_bar_visible(cx), |parent| {
 8519                            parent.child(self.status_bar.clone())
 8520                        })
 8521                        .child(self.toast_layer.clone()),
 8522                )
 8523    }
 8524}
 8525
 8526impl WorkspaceStore {
 8527    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8528        Self {
 8529            workspaces: Default::default(),
 8530            _subscriptions: vec![
 8531                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8532                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8533            ],
 8534            client,
 8535        }
 8536    }
 8537
 8538    pub fn update_followers(
 8539        &self,
 8540        project_id: Option<u64>,
 8541        update: proto::update_followers::Variant,
 8542        cx: &App,
 8543    ) -> Option<()> {
 8544        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8545        let room_id = active_call.0.room_id(cx)?;
 8546        self.client
 8547            .send(proto::UpdateFollowers {
 8548                room_id,
 8549                project_id,
 8550                variant: Some(update),
 8551            })
 8552            .log_err()
 8553    }
 8554
 8555    pub async fn handle_follow(
 8556        this: Entity<Self>,
 8557        envelope: TypedEnvelope<proto::Follow>,
 8558        mut cx: AsyncApp,
 8559    ) -> Result<proto::FollowResponse> {
 8560        this.update(&mut cx, |this, cx| {
 8561            let follower = Follower {
 8562                project_id: envelope.payload.project_id,
 8563                peer_id: envelope.original_sender_id()?,
 8564            };
 8565
 8566            let mut response = proto::FollowResponse::default();
 8567
 8568            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8569                let Some(workspace) = weak_workspace.upgrade() else {
 8570                    return false;
 8571                };
 8572                window_handle
 8573                    .update(cx, |_, window, cx| {
 8574                        workspace.update(cx, |workspace, cx| {
 8575                            let handler_response =
 8576                                workspace.handle_follow(follower.project_id, window, cx);
 8577                            if let Some(active_view) = handler_response.active_view
 8578                                && workspace.project.read(cx).remote_id() == follower.project_id
 8579                            {
 8580                                response.active_view = Some(active_view)
 8581                            }
 8582                        });
 8583                    })
 8584                    .is_ok()
 8585            });
 8586
 8587            Ok(response)
 8588        })
 8589    }
 8590
 8591    async fn handle_update_followers(
 8592        this: Entity<Self>,
 8593        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8594        mut cx: AsyncApp,
 8595    ) -> Result<()> {
 8596        let leader_id = envelope.original_sender_id()?;
 8597        let update = envelope.payload;
 8598
 8599        this.update(&mut cx, |this, cx| {
 8600            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8601                let Some(workspace) = weak_workspace.upgrade() else {
 8602                    return false;
 8603                };
 8604                window_handle
 8605                    .update(cx, |_, window, cx| {
 8606                        workspace.update(cx, |workspace, cx| {
 8607                            let project_id = workspace.project.read(cx).remote_id();
 8608                            if update.project_id != project_id && update.project_id.is_some() {
 8609                                return;
 8610                            }
 8611                            workspace.handle_update_followers(
 8612                                leader_id,
 8613                                update.clone(),
 8614                                window,
 8615                                cx,
 8616                            );
 8617                        });
 8618                    })
 8619                    .is_ok()
 8620            });
 8621            Ok(())
 8622        })
 8623    }
 8624
 8625    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8626        self.workspaces.iter().map(|(_, weak)| weak)
 8627    }
 8628
 8629    pub fn workspaces_with_windows(
 8630        &self,
 8631    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8632        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8633    }
 8634}
 8635
 8636impl ViewId {
 8637    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8638        Ok(Self {
 8639            creator: message
 8640                .creator
 8641                .map(CollaboratorId::PeerId)
 8642                .context("creator is missing")?,
 8643            id: message.id,
 8644        })
 8645    }
 8646
 8647    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8648        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8649            Some(proto::ViewId {
 8650                creator: Some(peer_id),
 8651                id: self.id,
 8652            })
 8653        } else {
 8654            None
 8655        }
 8656    }
 8657}
 8658
 8659impl FollowerState {
 8660    fn pane(&self) -> &Entity<Pane> {
 8661        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8662    }
 8663}
 8664
 8665pub trait WorkspaceHandle {
 8666    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8667}
 8668
 8669impl WorkspaceHandle for Entity<Workspace> {
 8670    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8671        self.read(cx)
 8672            .worktrees(cx)
 8673            .flat_map(|worktree| {
 8674                let worktree_id = worktree.read(cx).id();
 8675                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8676                    worktree_id,
 8677                    path: f.path.clone(),
 8678                })
 8679            })
 8680            .collect::<Vec<_>>()
 8681    }
 8682}
 8683
 8684pub async fn last_opened_workspace_location(
 8685    db: &WorkspaceDb,
 8686    fs: &dyn fs::Fs,
 8687) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8688    db.last_workspace(fs)
 8689        .await
 8690        .log_err()
 8691        .flatten()
 8692        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8693}
 8694
 8695pub async fn last_session_workspace_locations(
 8696    db: &WorkspaceDb,
 8697    last_session_id: &str,
 8698    last_session_window_stack: Option<Vec<WindowId>>,
 8699    fs: &dyn fs::Fs,
 8700) -> Option<Vec<SessionWorkspace>> {
 8701    db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8702        .await
 8703        .log_err()
 8704}
 8705
 8706pub async fn restore_multiworkspace(
 8707    multi_workspace: SerializedMultiWorkspace,
 8708    app_state: Arc<AppState>,
 8709    cx: &mut AsyncApp,
 8710) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8711    let SerializedMultiWorkspace {
 8712        active_workspace,
 8713        state,
 8714    } = multi_workspace;
 8715
 8716    let workspace_result = if active_workspace.paths.is_empty() {
 8717        cx.update(|cx| {
 8718            open_workspace_by_id(active_workspace.workspace_id, app_state.clone(), None, cx)
 8719        })
 8720        .await
 8721    } else {
 8722        cx.update(|cx| {
 8723            Workspace::new_local(
 8724                active_workspace.paths.paths().to_vec(),
 8725                app_state.clone(),
 8726                None,
 8727                None,
 8728                None,
 8729                OpenMode::Activate,
 8730                cx,
 8731            )
 8732        })
 8733        .await
 8734        .map(|result| result.window)
 8735    };
 8736
 8737    let window_handle = match workspace_result {
 8738        Ok(handle) => handle,
 8739        Err(err) => {
 8740            log::error!("Failed to restore active workspace: {err:#}");
 8741
 8742            let mut fallback_handle = None;
 8743            for key in &state.project_groups {
 8744                let key: ProjectGroupKey = key.clone().into();
 8745                let paths = key.path_list().paths().to_vec();
 8746                match cx
 8747                    .update(|cx| {
 8748                        Workspace::new_local(
 8749                            paths,
 8750                            app_state.clone(),
 8751                            None,
 8752                            None,
 8753                            None,
 8754                            OpenMode::Activate,
 8755                            cx,
 8756                        )
 8757                    })
 8758                    .await
 8759                {
 8760                    Ok(OpenResult { window, .. }) => {
 8761                        fallback_handle = Some(window);
 8762                        break;
 8763                    }
 8764                    Err(fallback_err) => {
 8765                        log::error!("Fallback project group also failed: {fallback_err:#}");
 8766                    }
 8767                }
 8768            }
 8769
 8770            fallback_handle.ok_or(err)?
 8771        }
 8772    };
 8773
 8774    apply_restored_multiworkspace_state(window_handle, &state, app_state.fs.clone(), cx).await;
 8775
 8776    window_handle
 8777        .update(cx, |_, window, _cx| {
 8778            window.activate_window();
 8779        })
 8780        .ok();
 8781
 8782    Ok(window_handle)
 8783}
 8784
 8785pub async fn apply_restored_multiworkspace_state(
 8786    window_handle: WindowHandle<MultiWorkspace>,
 8787    state: &MultiWorkspaceState,
 8788    fs: Arc<dyn fs::Fs>,
 8789    cx: &mut AsyncApp,
 8790) {
 8791    let MultiWorkspaceState {
 8792        sidebar_open,
 8793        project_groups,
 8794        sidebar_state,
 8795        ..
 8796    } = state;
 8797
 8798    if !project_groups.is_empty() {
 8799        // Resolve linked worktree paths to their main repo paths so
 8800        // stale keys from previous sessions get normalized and deduped.
 8801        let mut resolved_groups: Vec<SerializedProjectGroupState> = Vec::new();
 8802        for serialized in project_groups.iter().cloned() {
 8803            let SerializedProjectGroupState {
 8804                key,
 8805                expanded,
 8806                visible_thread_count,
 8807            } = serialized.into_restored_state();
 8808            if key.path_list().paths().is_empty() {
 8809                continue;
 8810            }
 8811            let mut resolved_paths = Vec::new();
 8812            for path in key.path_list().paths() {
 8813                if key.host().is_none()
 8814                    && let Some(common_dir) =
 8815                        project::discover_root_repo_common_dir(path, fs.as_ref()).await
 8816                {
 8817                    let main_path = common_dir.parent().unwrap_or(&common_dir);
 8818                    resolved_paths.push(main_path.to_path_buf());
 8819                } else {
 8820                    resolved_paths.push(path.to_path_buf());
 8821                }
 8822            }
 8823            let resolved = ProjectGroupKey::new(key.host(), PathList::new(&resolved_paths));
 8824            if !resolved_groups.iter().any(|g| g.key == resolved) {
 8825                resolved_groups.push(SerializedProjectGroupState {
 8826                    key: resolved,
 8827                    expanded,
 8828                    visible_thread_count,
 8829                });
 8830            }
 8831        }
 8832
 8833        window_handle
 8834            .update(cx, |multi_workspace, _window, cx| {
 8835                multi_workspace.restore_project_groups(resolved_groups, cx);
 8836            })
 8837            .ok();
 8838    }
 8839
 8840    if *sidebar_open {
 8841        window_handle
 8842            .update(cx, |multi_workspace, _, cx| {
 8843                multi_workspace.open_sidebar(cx);
 8844            })
 8845            .ok();
 8846    }
 8847
 8848    if let Some(sidebar_state) = sidebar_state {
 8849        window_handle
 8850            .update(cx, |multi_workspace, window, cx| {
 8851                if let Some(sidebar) = multi_workspace.sidebar() {
 8852                    sidebar.restore_serialized_state(sidebar_state, window, cx);
 8853                }
 8854                multi_workspace.serialize(cx);
 8855            })
 8856            .ok();
 8857    }
 8858}
 8859
 8860actions!(
 8861    collab,
 8862    [
 8863        /// Opens the channel notes for the current call.
 8864        ///
 8865        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8866        /// channel in the collab panel.
 8867        ///
 8868        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8869        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8870        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8871        OpenChannelNotes,
 8872        /// Mutes your microphone.
 8873        Mute,
 8874        /// Deafens yourself (mute both microphone and speakers).
 8875        Deafen,
 8876        /// Leaves the current call.
 8877        LeaveCall,
 8878        /// Shares the current project with collaborators.
 8879        ShareProject,
 8880        /// Shares your screen with collaborators.
 8881        ScreenShare,
 8882        /// Copies the current room name and session id for debugging purposes.
 8883        CopyRoomId,
 8884    ]
 8885);
 8886
 8887/// Opens the channel notes for a specific channel by its ID.
 8888#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8889#[action(namespace = collab)]
 8890#[serde(deny_unknown_fields)]
 8891pub struct OpenChannelNotesById {
 8892    pub channel_id: u64,
 8893}
 8894
 8895actions!(
 8896    zed,
 8897    [
 8898        /// Opens the Zed log file.
 8899        OpenLog,
 8900        /// Reveals the Zed log file in the system file manager.
 8901        RevealLogInFileManager
 8902    ]
 8903);
 8904
 8905async fn join_channel_internal(
 8906    channel_id: ChannelId,
 8907    app_state: &Arc<AppState>,
 8908    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8909    requesting_workspace: Option<WeakEntity<Workspace>>,
 8910    active_call: &dyn AnyActiveCall,
 8911    cx: &mut AsyncApp,
 8912) -> Result<bool> {
 8913    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8914        if !active_call.is_in_room(cx) {
 8915            return (false, false);
 8916        }
 8917
 8918        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8919        let should_prompt = active_call.is_sharing_project(cx)
 8920            && active_call.has_remote_participants(cx)
 8921            && !already_in_channel;
 8922        (should_prompt, already_in_channel)
 8923    });
 8924
 8925    if already_in_channel {
 8926        let task = cx.update(|cx| {
 8927            if let Some((project, host)) = active_call.most_active_project(cx) {
 8928                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8929            } else {
 8930                None
 8931            }
 8932        });
 8933        if let Some(task) = task {
 8934            task.await?;
 8935        }
 8936        return anyhow::Ok(true);
 8937    }
 8938
 8939    if should_prompt {
 8940        if let Some(multi_workspace) = requesting_window {
 8941            let answer = multi_workspace
 8942                .update(cx, |_, window, cx| {
 8943                    window.prompt(
 8944                        PromptLevel::Warning,
 8945                        "Do you want to switch channels?",
 8946                        Some("Leaving this call will unshare your current project."),
 8947                        &["Yes, Join Channel", "Cancel"],
 8948                        cx,
 8949                    )
 8950                })?
 8951                .await;
 8952
 8953            if answer == Ok(1) {
 8954                return Ok(false);
 8955            }
 8956        } else {
 8957            return Ok(false);
 8958        }
 8959    }
 8960
 8961    let client = cx.update(|cx| active_call.client(cx));
 8962
 8963    let mut client_status = client.status();
 8964
 8965    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8966    'outer: loop {
 8967        let Some(status) = client_status.recv().await else {
 8968            anyhow::bail!("error connecting");
 8969        };
 8970
 8971        match status {
 8972            Status::Connecting
 8973            | Status::Authenticating
 8974            | Status::Authenticated
 8975            | Status::Reconnecting
 8976            | Status::Reauthenticating
 8977            | Status::Reauthenticated => continue,
 8978            Status::Connected { .. } => break 'outer,
 8979            Status::SignedOut | Status::AuthenticationError => {
 8980                return Err(ErrorCode::SignedOut.into());
 8981            }
 8982            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8983            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8984                return Err(ErrorCode::Disconnected.into());
 8985            }
 8986        }
 8987    }
 8988
 8989    let joined = cx
 8990        .update(|cx| active_call.join_channel(channel_id, cx))
 8991        .await?;
 8992
 8993    if !joined {
 8994        return anyhow::Ok(true);
 8995    }
 8996
 8997    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8998
 8999    let task = cx.update(|cx| {
 9000        if let Some((project, host)) = active_call.most_active_project(cx) {
 9001            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 9002        }
 9003
 9004        // If you are the first to join a channel, see if you should share your project.
 9005        if !active_call.has_remote_participants(cx)
 9006            && !active_call.local_participant_is_guest(cx)
 9007            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 9008        {
 9009            let project = workspace.update(cx, |workspace, cx| {
 9010                let project = workspace.project.read(cx);
 9011
 9012                if !active_call.share_on_join(cx) {
 9013                    return None;
 9014                }
 9015
 9016                if (project.is_local() || project.is_via_remote_server())
 9017                    && project.visible_worktrees(cx).any(|tree| {
 9018                        tree.read(cx)
 9019                            .root_entry()
 9020                            .is_some_and(|entry| entry.is_dir())
 9021                    })
 9022                {
 9023                    Some(workspace.project.clone())
 9024                } else {
 9025                    None
 9026                }
 9027            });
 9028            if let Some(project) = project {
 9029                let share_task = active_call.share_project(project, cx);
 9030                return Some(cx.spawn(async move |_cx| -> Result<()> {
 9031                    share_task.await?;
 9032                    Ok(())
 9033                }));
 9034            }
 9035        }
 9036
 9037        None
 9038    });
 9039    if let Some(task) = task {
 9040        task.await?;
 9041        return anyhow::Ok(true);
 9042    }
 9043    anyhow::Ok(false)
 9044}
 9045
 9046pub fn join_channel(
 9047    channel_id: ChannelId,
 9048    app_state: Arc<AppState>,
 9049    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9050    requesting_workspace: Option<WeakEntity<Workspace>>,
 9051    cx: &mut App,
 9052) -> Task<Result<()>> {
 9053    let active_call = GlobalAnyActiveCall::global(cx).clone();
 9054    cx.spawn(async move |cx| {
 9055        let result = join_channel_internal(
 9056            channel_id,
 9057            &app_state,
 9058            requesting_window,
 9059            requesting_workspace,
 9060            &*active_call.0,
 9061            cx,
 9062        )
 9063        .await;
 9064
 9065        // join channel succeeded, and opened a window
 9066        if matches!(result, Ok(true)) {
 9067            return anyhow::Ok(());
 9068        }
 9069
 9070        // find an existing workspace to focus and show call controls
 9071        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 9072        if active_window.is_none() {
 9073            // no open workspaces, make one to show the error in (blergh)
 9074            let OpenResult {
 9075                window: window_handle,
 9076                ..
 9077            } = cx
 9078                .update(|cx| {
 9079                    Workspace::new_local(
 9080                        vec![],
 9081                        app_state.clone(),
 9082                        requesting_window,
 9083                        None,
 9084                        None,
 9085                        OpenMode::Activate,
 9086                        cx,
 9087                    )
 9088                })
 9089                .await?;
 9090
 9091            window_handle
 9092                .update(cx, |_, window, _cx| {
 9093                    window.activate_window();
 9094                })
 9095                .ok();
 9096
 9097            if result.is_ok() {
 9098                cx.update(|cx| {
 9099                    cx.dispatch_action(&OpenChannelNotes);
 9100                });
 9101            }
 9102
 9103            active_window = Some(window_handle);
 9104        }
 9105
 9106        if let Err(err) = result {
 9107            log::error!("failed to join channel: {}", err);
 9108            if let Some(active_window) = active_window {
 9109                active_window
 9110                    .update(cx, |_, window, cx| {
 9111                        let detail: SharedString = match err.error_code() {
 9112                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 9113                            ErrorCode::UpgradeRequired => concat!(
 9114                                "Your are running an unsupported version of Zed. ",
 9115                                "Please update to continue."
 9116                            )
 9117                            .into(),
 9118                            ErrorCode::NoSuchChannel => concat!(
 9119                                "No matching channel was found. ",
 9120                                "Please check the link and try again."
 9121                            )
 9122                            .into(),
 9123                            ErrorCode::Forbidden => concat!(
 9124                                "This channel is private, and you do not have access. ",
 9125                                "Please ask someone to add you and try again."
 9126                            )
 9127                            .into(),
 9128                            ErrorCode::Disconnected => {
 9129                                "Please check your internet connection and try again.".into()
 9130                            }
 9131                            _ => format!("{}\n\nPlease try again.", err).into(),
 9132                        };
 9133                        window.prompt(
 9134                            PromptLevel::Critical,
 9135                            "Failed to join channel",
 9136                            Some(&detail),
 9137                            &["Ok"],
 9138                            cx,
 9139                        )
 9140                    })?
 9141                    .await
 9142                    .ok();
 9143            }
 9144        }
 9145
 9146        // return ok, we showed the error to the user.
 9147        anyhow::Ok(())
 9148    })
 9149}
 9150
 9151pub async fn get_any_active_multi_workspace(
 9152    app_state: Arc<AppState>,
 9153    mut cx: AsyncApp,
 9154) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 9155    // find an existing workspace to focus and show call controls
 9156    let active_window = activate_any_workspace_window(&mut cx);
 9157    if active_window.is_none() {
 9158        cx.update(|cx| {
 9159            Workspace::new_local(
 9160                vec![],
 9161                app_state.clone(),
 9162                None,
 9163                None,
 9164                None,
 9165                OpenMode::Activate,
 9166                cx,
 9167            )
 9168        })
 9169        .await?;
 9170    }
 9171    activate_any_workspace_window(&mut cx).context("could not open zed")
 9172}
 9173
 9174fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 9175    cx.update(|cx| {
 9176        if let Some(workspace_window) = cx
 9177            .active_window()
 9178            .and_then(|window| window.downcast::<MultiWorkspace>())
 9179        {
 9180            return Some(workspace_window);
 9181        }
 9182
 9183        for window in cx.windows() {
 9184            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 9185                workspace_window
 9186                    .update(cx, |_, window, _| window.activate_window())
 9187                    .ok();
 9188                return Some(workspace_window);
 9189            }
 9190        }
 9191        None
 9192    })
 9193}
 9194
 9195pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 9196    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 9197}
 9198
 9199pub fn workspace_windows_for_location(
 9200    serialized_location: &SerializedWorkspaceLocation,
 9201    cx: &App,
 9202) -> Vec<WindowHandle<MultiWorkspace>> {
 9203    cx.windows()
 9204        .into_iter()
 9205        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9206        .filter(|multi_workspace| {
 9207            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 9208                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 9209                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 9210                }
 9211                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 9212                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 9213                    a.distro_name == b.distro_name
 9214                }
 9215                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 9216                    a.container_id == b.container_id
 9217                }
 9218                #[cfg(any(test, feature = "test-support"))]
 9219                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 9220                    a.id == b.id
 9221                }
 9222                _ => false,
 9223            };
 9224
 9225            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 9226                multi_workspace.workspaces().any(|workspace| {
 9227                    match workspace.read(cx).workspace_location(cx) {
 9228                        WorkspaceLocation::Location(location, _) => {
 9229                            match (&location, serialized_location) {
 9230                                (
 9231                                    SerializedWorkspaceLocation::Local,
 9232                                    SerializedWorkspaceLocation::Local,
 9233                                ) => true,
 9234                                (
 9235                                    SerializedWorkspaceLocation::Remote(a),
 9236                                    SerializedWorkspaceLocation::Remote(b),
 9237                                ) => same_host(a, b),
 9238                                _ => false,
 9239                            }
 9240                        }
 9241                        _ => false,
 9242                    }
 9243                })
 9244            })
 9245        })
 9246        .collect()
 9247}
 9248
 9249pub async fn find_existing_workspace(
 9250    abs_paths: &[PathBuf],
 9251    open_options: &OpenOptions,
 9252    location: &SerializedWorkspaceLocation,
 9253    cx: &mut AsyncApp,
 9254) -> (
 9255    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 9256    OpenVisible,
 9257) {
 9258    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 9259    let mut open_visible = OpenVisible::All;
 9260    let mut best_match = None;
 9261
 9262    if open_options.workspace_matching != WorkspaceMatching::None {
 9263        cx.update(|cx| {
 9264            for window in workspace_windows_for_location(location, cx) {
 9265                if let Ok(multi_workspace) = window.read(cx) {
 9266                    for workspace in multi_workspace.workspaces() {
 9267                        let project = workspace.read(cx).project.read(cx);
 9268                        let m = project.visibility_for_paths(
 9269                            abs_paths,
 9270                            open_options.workspace_matching != WorkspaceMatching::MatchSubdirectory,
 9271                            cx,
 9272                        );
 9273                        if m > best_match {
 9274                            existing = Some((window, workspace.clone()));
 9275                            best_match = m;
 9276                        } else if best_match.is_none()
 9277                            && open_options.workspace_matching
 9278                                == WorkspaceMatching::MatchSubdirectory
 9279                        {
 9280                            existing = Some((window, workspace.clone()))
 9281                        }
 9282                    }
 9283                }
 9284            }
 9285        });
 9286
 9287        let all_paths_are_files = existing
 9288            .as_ref()
 9289            .and_then(|(_, target_workspace)| {
 9290                cx.update(|cx| {
 9291                    let workspace = target_workspace.read(cx);
 9292                    let project = workspace.project.read(cx);
 9293                    let path_style = workspace.path_style(cx);
 9294                    Some(!abs_paths.iter().any(|path| {
 9295                        let path = util::paths::SanitizedPath::new(path);
 9296                        project.worktrees(cx).any(|worktree| {
 9297                            let worktree = worktree.read(cx);
 9298                            let abs_path = worktree.abs_path();
 9299                            path_style
 9300                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 9301                                .and_then(|rel| worktree.entry_for_path(&rel))
 9302                                .is_some_and(|e| e.is_dir())
 9303                        })
 9304                    }))
 9305                })
 9306            })
 9307            .unwrap_or(false);
 9308
 9309        if open_options.wait && existing.is_some() && all_paths_are_files {
 9310            cx.update(|cx| {
 9311                let windows = workspace_windows_for_location(location, cx);
 9312                let window = cx
 9313                    .active_window()
 9314                    .and_then(|window| window.downcast::<MultiWorkspace>())
 9315                    .filter(|window| windows.contains(window))
 9316                    .or_else(|| windows.into_iter().next());
 9317                if let Some(window) = window {
 9318                    if let Ok(multi_workspace) = window.read(cx) {
 9319                        let active_workspace = multi_workspace.workspace().clone();
 9320                        existing = Some((window, active_workspace));
 9321                        open_visible = OpenVisible::None;
 9322                    }
 9323                }
 9324            });
 9325        }
 9326    }
 9327    (existing, open_visible)
 9328}
 9329
 9330/// Controls whether to reuse an existing workspace whose worktrees contain the
 9331/// given paths, and how broadly to match.
 9332#[derive(Clone, Debug, Default, PartialEq, Eq)]
 9333pub enum WorkspaceMatching {
 9334    /// Always open a new workspace. No matching against existing worktrees.
 9335    None,
 9336    /// Match paths against existing worktree roots and files within them.
 9337    #[default]
 9338    MatchExact,
 9339    /// Match paths against existing worktrees including subdirectories, and
 9340    /// fall back to any existing window if no worktree matched.
 9341    ///
 9342    /// For example, `zed -a foo/bar` will activate the `bar` workspace if it
 9343    /// exists, otherwise it will open a new window with `foo/bar` as the root.
 9344    MatchSubdirectory,
 9345}
 9346
 9347#[derive(Clone)]
 9348pub struct OpenOptions {
 9349    pub visible: Option<OpenVisible>,
 9350    pub focus: Option<bool>,
 9351    pub workspace_matching: WorkspaceMatching,
 9352    /// Whether to add unmatched directories to the existing window's sidebar
 9353    /// rather than opening a new window. Defaults to true, matching the default
 9354    /// `cli_default_open_behavior` setting.
 9355    pub add_dirs_to_sidebar: bool,
 9356    pub wait: bool,
 9357    pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9358    pub open_mode: OpenMode,
 9359    pub env: Option<HashMap<String, String>>,
 9360    pub open_in_dev_container: bool,
 9361}
 9362
 9363impl Default for OpenOptions {
 9364    fn default() -> Self {
 9365        Self {
 9366            visible: None,
 9367            focus: None,
 9368            workspace_matching: WorkspaceMatching::default(),
 9369            add_dirs_to_sidebar: true,
 9370            wait: false,
 9371            requesting_window: None,
 9372            open_mode: OpenMode::default(),
 9373            env: None,
 9374            open_in_dev_container: false,
 9375        }
 9376    }
 9377}
 9378
 9379impl OpenOptions {
 9380    fn should_reuse_existing_window(&self) -> bool {
 9381        self.workspace_matching != WorkspaceMatching::None && self.open_mode != OpenMode::NewWindow
 9382    }
 9383}
 9384
 9385/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 9386/// or [`Workspace::open_workspace_for_paths`].
 9387pub struct OpenResult {
 9388    pub window: WindowHandle<MultiWorkspace>,
 9389    pub workspace: Entity<Workspace>,
 9390    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 9391}
 9392
 9393/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 9394pub fn open_workspace_by_id(
 9395    workspace_id: WorkspaceId,
 9396    app_state: Arc<AppState>,
 9397    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9398    cx: &mut App,
 9399) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 9400    let project_handle = Project::local(
 9401        app_state.client.clone(),
 9402        app_state.node_runtime.clone(),
 9403        app_state.user_store.clone(),
 9404        app_state.languages.clone(),
 9405        app_state.fs.clone(),
 9406        None,
 9407        project::LocalProjectFlags {
 9408            init_worktree_trust: true,
 9409            ..project::LocalProjectFlags::default()
 9410        },
 9411        cx,
 9412    );
 9413
 9414    let db = WorkspaceDb::global(cx);
 9415    let kvp = db::kvp::KeyValueStore::global(cx);
 9416    cx.spawn(async move |cx| {
 9417        let serialized_workspace = db
 9418            .workspace_for_id(workspace_id)
 9419            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 9420
 9421        let centered_layout = serialized_workspace.centered_layout;
 9422
 9423        let (window, workspace) = if let Some(window) = requesting_window {
 9424            let workspace = window.update(cx, |multi_workspace, window, cx| {
 9425                let workspace = cx.new(|cx| {
 9426                    let mut workspace = Workspace::new(
 9427                        Some(workspace_id),
 9428                        project_handle.clone(),
 9429                        app_state.clone(),
 9430                        window,
 9431                        cx,
 9432                    );
 9433                    workspace.centered_layout = centered_layout;
 9434                    workspace
 9435                });
 9436                multi_workspace.add(workspace.clone(), &*window, cx);
 9437                workspace
 9438            })?;
 9439            (window, workspace)
 9440        } else {
 9441            let window_bounds_override = window_bounds_env_override();
 9442
 9443            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 9444                (Some(WindowBounds::Windowed(bounds)), None)
 9445            } else if let Some(display) = serialized_workspace.display
 9446                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 9447            {
 9448                (Some(bounds.0), Some(display))
 9449            } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
 9450                (Some(bounds), Some(display))
 9451            } else {
 9452                (None, None)
 9453            };
 9454
 9455            let options = cx.update(|cx| {
 9456                let mut options = (app_state.build_window_options)(display, cx);
 9457                options.window_bounds = window_bounds;
 9458                options
 9459            });
 9460
 9461            let window = cx.open_window(options, {
 9462                let app_state = app_state.clone();
 9463                let project_handle = project_handle.clone();
 9464                move |window, cx| {
 9465                    let workspace = cx.new(|cx| {
 9466                        let mut workspace = Workspace::new(
 9467                            Some(workspace_id),
 9468                            project_handle,
 9469                            app_state,
 9470                            window,
 9471                            cx,
 9472                        );
 9473                        workspace.centered_layout = centered_layout;
 9474                        workspace
 9475                    });
 9476                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9477                }
 9478            })?;
 9479
 9480            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 9481                multi_workspace.workspace().clone()
 9482            })?;
 9483
 9484            (window, workspace)
 9485        };
 9486
 9487        notify_if_database_failed(window, cx);
 9488
 9489        // Restore items from the serialized workspace
 9490        window
 9491            .update(cx, |_, window, cx| {
 9492                workspace.update(cx, |_workspace, cx| {
 9493                    open_items(Some(serialized_workspace), vec![], window, cx)
 9494                })
 9495            })?
 9496            .await?;
 9497
 9498        window.update(cx, |_, window, cx| {
 9499            workspace.update(cx, |workspace, cx| {
 9500                workspace.serialize_workspace(window, cx);
 9501            });
 9502        })?;
 9503
 9504        Ok(window)
 9505    })
 9506}
 9507
 9508#[allow(clippy::type_complexity)]
 9509pub fn open_paths(
 9510    abs_paths: &[PathBuf],
 9511    app_state: Arc<AppState>,
 9512    mut open_options: OpenOptions,
 9513    cx: &mut App,
 9514) -> Task<anyhow::Result<OpenResult>> {
 9515    let abs_paths = abs_paths.to_vec();
 9516    #[cfg(target_os = "windows")]
 9517    let wsl_path = abs_paths
 9518        .iter()
 9519        .find_map(|p| util::paths::WslPath::from_path(p));
 9520
 9521    cx.spawn(async move |cx| {
 9522        let (mut existing, mut open_visible) = find_existing_workspace(
 9523            &abs_paths,
 9524            &open_options,
 9525            &SerializedWorkspaceLocation::Local,
 9526            cx,
 9527        )
 9528        .await;
 9529
 9530        // Fallback: if no workspace contains the paths and all paths are files,
 9531        // prefer an existing local workspace window (active window first).
 9532        if open_options.should_reuse_existing_window() && existing.is_none() {
 9533            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 9534            let all_metadatas = futures::future::join_all(all_paths)
 9535                .await
 9536                .into_iter()
 9537                .filter_map(|result| result.ok().flatten());
 9538
 9539            if all_metadatas.into_iter().all(|file| !file.is_dir) {
 9540                cx.update(|cx| {
 9541                    let windows = workspace_windows_for_location(
 9542                        &SerializedWorkspaceLocation::Local,
 9543                        cx,
 9544                    );
 9545                    let window = cx
 9546                        .active_window()
 9547                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9548                        .filter(|window| windows.contains(window))
 9549                        .or_else(|| windows.into_iter().next());
 9550                    if let Some(window) = window {
 9551                        if let Ok(multi_workspace) = window.read(cx) {
 9552                            let active_workspace = multi_workspace.workspace().clone();
 9553                            existing = Some((window, active_workspace));
 9554                            open_visible = OpenVisible::None;
 9555                        }
 9556                    }
 9557                });
 9558            }
 9559        }
 9560
 9561        // Fallback for directories: when no flag is specified and no existing
 9562        // workspace matched, check the user's setting to decide whether to add
 9563        // the directory as a new workspace in the active window's MultiWorkspace
 9564        // or open a new window.
 9565        // Skip when requesting_window is already set: the caller (e.g.
 9566        // open_workspace_for_paths reusing an empty window) already chose the
 9567        // target window, so we must not open the sidebar as a side-effect.
 9568        if open_options.should_reuse_existing_window()
 9569            && existing.is_none()
 9570            && open_options.requesting_window.is_none()
 9571        {
 9572            let use_existing_window = open_options.add_dirs_to_sidebar;
 9573
 9574            if use_existing_window {
 9575                let target_window = cx.update(|cx| {
 9576                    let windows = workspace_windows_for_location(
 9577                        &SerializedWorkspaceLocation::Local,
 9578                        cx,
 9579                    );
 9580                    let window = cx
 9581                        .active_window()
 9582                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9583                        .filter(|window| windows.contains(window))
 9584                        .or_else(|| windows.into_iter().next());
 9585                    window.filter(|window| {
 9586                        window
 9587                            .read(cx)
 9588                            .is_ok_and(|mw| mw.multi_workspace_enabled(cx))
 9589                    })
 9590                });
 9591
 9592                if let Some(window) = target_window {
 9593                    open_options.requesting_window = Some(window);
 9594                    window
 9595                        .update(cx, |multi_workspace, _, cx| {
 9596                            multi_workspace.open_sidebar(cx);
 9597                        })
 9598                        .log_err();
 9599                }
 9600            }
 9601        }
 9602
 9603        let open_in_dev_container = open_options.open_in_dev_container;
 9604
 9605        let result = if let Some((existing, target_workspace)) = existing {
 9606            let open_task = existing
 9607                .update(cx, |multi_workspace, window, cx| {
 9608                    window.activate_window();
 9609                    multi_workspace.activate(target_workspace.clone(), window, cx);
 9610                    target_workspace.update(cx, |workspace, cx| {
 9611                        if open_in_dev_container {
 9612                            workspace.set_open_in_dev_container(true);
 9613                        }
 9614                        workspace.open_paths(
 9615                            abs_paths,
 9616                            OpenOptions {
 9617                                visible: Some(open_visible),
 9618                                ..Default::default()
 9619                            },
 9620                            None,
 9621                            window,
 9622                            cx,
 9623                        )
 9624                    })
 9625                })?
 9626                .await;
 9627
 9628            _ = existing.update(cx, |multi_workspace, _, cx| {
 9629                let workspace = multi_workspace.workspace().clone();
 9630                workspace.update(cx, |workspace, cx| {
 9631                    for item in open_task.iter().flatten() {
 9632                        if let Err(e) = item {
 9633                            workspace.show_error(&e, cx);
 9634                        }
 9635                    }
 9636                });
 9637            });
 9638
 9639            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9640        } else {
 9641            let init = if open_in_dev_container {
 9642                Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>| {
 9643                    workspace.set_open_in_dev_container(true);
 9644                }) as Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>)
 9645            } else {
 9646                None
 9647            };
 9648            let result = cx
 9649                .update(move |cx| {
 9650                    Workspace::new_local(
 9651                        abs_paths,
 9652                        app_state.clone(),
 9653                        open_options.requesting_window,
 9654                        open_options.env,
 9655                        init,
 9656                        open_options.open_mode,
 9657                        cx,
 9658                    )
 9659                })
 9660                .await;
 9661
 9662            if let Ok(ref result) = result {
 9663                result.window
 9664                    .update(cx, |_, window, _cx| {
 9665                        window.activate_window();
 9666                    })
 9667                    .log_err();
 9668            }
 9669
 9670            result
 9671        };
 9672
 9673        #[cfg(target_os = "windows")]
 9674        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9675            && let Ok(ref result) = result
 9676        {
 9677            result.window
 9678                .update(cx, move |multi_workspace, _window, cx| {
 9679                    struct OpenInWsl;
 9680                    let workspace = multi_workspace.workspace().clone();
 9681                    workspace.update(cx, |workspace, cx| {
 9682                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9683                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9684                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9685                            cx.new(move |cx| {
 9686                                MessageNotification::new(msg, cx)
 9687                                    .primary_message("Open in WSL")
 9688                                    .primary_icon(IconName::FolderOpen)
 9689                                    .primary_on_click(move |window, cx| {
 9690                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9691                                                distro: remote::WslConnectionOptions {
 9692                                                        distro_name: distro.clone(),
 9693                                                    user: None,
 9694                                                },
 9695                                                paths: vec![path.clone().into()],
 9696                                            }), cx)
 9697                                    })
 9698                            })
 9699                        });
 9700                    });
 9701                })
 9702                .unwrap();
 9703        };
 9704        result
 9705    })
 9706}
 9707
 9708pub fn open_new(
 9709    open_options: OpenOptions,
 9710    app_state: Arc<AppState>,
 9711    cx: &mut App,
 9712    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9713) -> Task<anyhow::Result<()>> {
 9714    let addition = open_options.open_mode;
 9715    let task = Workspace::new_local(
 9716        Vec::new(),
 9717        app_state,
 9718        open_options.requesting_window,
 9719        open_options.env,
 9720        Some(Box::new(init)),
 9721        addition,
 9722        cx,
 9723    );
 9724    cx.spawn(async move |cx| {
 9725        let OpenResult { window, .. } = task.await?;
 9726        window
 9727            .update(cx, |_, window, _cx| {
 9728                window.activate_window();
 9729            })
 9730            .ok();
 9731        Ok(())
 9732    })
 9733}
 9734
 9735pub fn create_and_open_local_file(
 9736    path: &'static Path,
 9737    window: &mut Window,
 9738    cx: &mut Context<Workspace>,
 9739    default_content: impl 'static + Send + FnOnce() -> Rope,
 9740) -> Task<Result<Box<dyn ItemHandle>>> {
 9741    cx.spawn_in(window, async move |workspace, cx| {
 9742        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9743        if !fs.is_file(path).await {
 9744            fs.create_file(path, Default::default()).await?;
 9745            fs.save(path, &default_content(), Default::default())
 9746                .await?;
 9747        }
 9748
 9749        workspace
 9750            .update_in(cx, |workspace, window, cx| {
 9751                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9752                    let path = workspace
 9753                        .project
 9754                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9755                    cx.spawn_in(window, async move |workspace, cx| {
 9756                        let path = path.await?;
 9757
 9758                        let path = fs.canonicalize(&path).await.unwrap_or(path);
 9759
 9760                        let mut items = workspace
 9761                            .update_in(cx, |workspace, window, cx| {
 9762                                workspace.open_paths(
 9763                                    vec![path.to_path_buf()],
 9764                                    OpenOptions {
 9765                                        visible: Some(OpenVisible::None),
 9766                                        ..Default::default()
 9767                                    },
 9768                                    None,
 9769                                    window,
 9770                                    cx,
 9771                                )
 9772                            })?
 9773                            .await;
 9774                        let item = items.pop().flatten();
 9775                        item.with_context(|| format!("path {path:?} is not a file"))?
 9776                    })
 9777                })
 9778            })?
 9779            .await?
 9780            .await
 9781    })
 9782}
 9783
 9784pub fn open_remote_project_with_new_connection(
 9785    window: WindowHandle<MultiWorkspace>,
 9786    remote_connection: Arc<dyn RemoteConnection>,
 9787    cancel_rx: oneshot::Receiver<()>,
 9788    delegate: Arc<dyn RemoteClientDelegate>,
 9789    app_state: Arc<AppState>,
 9790    paths: Vec<PathBuf>,
 9791    cx: &mut App,
 9792) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9793    cx.spawn(async move |cx| {
 9794        let (workspace_id, serialized_workspace) =
 9795            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9796                .await?;
 9797
 9798        let session = match cx
 9799            .update(|cx| {
 9800                remote::RemoteClient::new(
 9801                    ConnectionIdentifier::Workspace(workspace_id.0),
 9802                    remote_connection,
 9803                    cancel_rx,
 9804                    delegate,
 9805                    cx,
 9806                )
 9807            })
 9808            .await?
 9809        {
 9810            Some(result) => result,
 9811            None => return Ok(Vec::new()),
 9812        };
 9813
 9814        let project = cx.update(|cx| {
 9815            project::Project::remote(
 9816                session,
 9817                app_state.client.clone(),
 9818                app_state.node_runtime.clone(),
 9819                app_state.user_store.clone(),
 9820                app_state.languages.clone(),
 9821                app_state.fs.clone(),
 9822                true,
 9823                cx,
 9824            )
 9825        });
 9826
 9827        open_remote_project_inner(
 9828            project,
 9829            paths,
 9830            workspace_id,
 9831            serialized_workspace,
 9832            app_state,
 9833            window,
 9834            None,
 9835            cx,
 9836        )
 9837        .await
 9838    })
 9839}
 9840
 9841pub fn open_remote_project_with_existing_connection(
 9842    connection_options: RemoteConnectionOptions,
 9843    project: Entity<Project>,
 9844    paths: Vec<PathBuf>,
 9845    app_state: Arc<AppState>,
 9846    window: WindowHandle<MultiWorkspace>,
 9847    provisional_project_group_key: Option<ProjectGroupKey>,
 9848    cx: &mut AsyncApp,
 9849) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9850    cx.spawn(async move |cx| {
 9851        let (workspace_id, serialized_workspace) =
 9852            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9853
 9854        open_remote_project_inner(
 9855            project,
 9856            paths,
 9857            workspace_id,
 9858            serialized_workspace,
 9859            app_state,
 9860            window,
 9861            provisional_project_group_key,
 9862            cx,
 9863        )
 9864        .await
 9865    })
 9866}
 9867
 9868async fn open_remote_project_inner(
 9869    project: Entity<Project>,
 9870    paths: Vec<PathBuf>,
 9871    workspace_id: WorkspaceId,
 9872    serialized_workspace: Option<SerializedWorkspace>,
 9873    app_state: Arc<AppState>,
 9874    window: WindowHandle<MultiWorkspace>,
 9875    provisional_project_group_key: Option<ProjectGroupKey>,
 9876    cx: &mut AsyncApp,
 9877) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9878    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9879    let toolchains = db.toolchains(workspace_id).await?;
 9880    for (toolchain, worktree_path, path) in toolchains {
 9881        project
 9882            .update(cx, |this, cx| {
 9883                let Some(worktree_id) =
 9884                    this.find_worktree(&worktree_path, cx)
 9885                        .and_then(|(worktree, rel_path)| {
 9886                            if rel_path.is_empty() {
 9887                                Some(worktree.read(cx).id())
 9888                            } else {
 9889                                None
 9890                            }
 9891                        })
 9892                else {
 9893                    return Task::ready(None);
 9894                };
 9895
 9896                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9897            })
 9898            .await;
 9899    }
 9900    let mut project_paths_to_open = vec![];
 9901    let mut project_path_errors = vec![];
 9902
 9903    for path in paths {
 9904        let result = cx
 9905            .update(|cx| {
 9906                Workspace::project_path_for_path(project.clone(), path.as_path(), true, cx)
 9907            })
 9908            .await;
 9909        match result {
 9910            Ok((_, project_path)) => {
 9911                project_paths_to_open.push((path, Some(project_path)));
 9912            }
 9913            Err(error) => {
 9914                project_path_errors.push(error);
 9915            }
 9916        };
 9917    }
 9918
 9919    if project_paths_to_open.is_empty() {
 9920        return Err(project_path_errors.pop().context("no paths given")?);
 9921    }
 9922
 9923    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9924        telemetry::event!("SSH Project Opened");
 9925
 9926        let new_workspace = cx.new(|cx| {
 9927            let mut workspace =
 9928                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9929            workspace.update_history(cx);
 9930
 9931            if let Some(ref serialized) = serialized_workspace {
 9932                workspace.centered_layout = serialized.centered_layout;
 9933            }
 9934
 9935            workspace
 9936        });
 9937
 9938        if let Some(project_group_key) = provisional_project_group_key.clone() {
 9939            multi_workspace.retain_workspace(new_workspace.clone(), project_group_key, cx);
 9940        }
 9941        multi_workspace.activate(new_workspace.clone(), window, cx);
 9942        new_workspace
 9943    })?;
 9944
 9945    let items = window
 9946        .update(cx, |_, window, cx| {
 9947            window.activate_window();
 9948            workspace.update(cx, |_workspace, cx| {
 9949                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9950            })
 9951        })?
 9952        .await?;
 9953
 9954    workspace.update(cx, |workspace, cx| {
 9955        for error in project_path_errors {
 9956            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9957                if let Some(path) = error.error_tag("path") {
 9958                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9959                }
 9960            } else {
 9961                workspace.show_error(&error, cx)
 9962            }
 9963        }
 9964    });
 9965
 9966    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9967}
 9968
 9969fn deserialize_remote_project(
 9970    connection_options: RemoteConnectionOptions,
 9971    paths: Vec<PathBuf>,
 9972    cx: &AsyncApp,
 9973) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9974    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9975    cx.background_spawn(async move {
 9976        let remote_connection_id = db
 9977            .get_or_create_remote_connection(connection_options)
 9978            .await?;
 9979
 9980        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
 9981
 9982        let workspace_id = if let Some(workspace_id) =
 9983            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9984        {
 9985            workspace_id
 9986        } else {
 9987            db.next_id().await?
 9988        };
 9989
 9990        Ok((workspace_id, serialized_workspace))
 9991    })
 9992}
 9993
 9994pub fn join_in_room_project(
 9995    project_id: u64,
 9996    follow_user_id: u64,
 9997    app_state: Arc<AppState>,
 9998    cx: &mut App,
 9999) -> Task<Result<()>> {
10000    let windows = cx.windows();
10001    cx.spawn(async move |cx| {
10002        let existing_window_and_workspace: Option<(
10003            WindowHandle<MultiWorkspace>,
10004            Entity<Workspace>,
10005        )> = windows.into_iter().find_map(|window_handle| {
10006            window_handle
10007                .downcast::<MultiWorkspace>()
10008                .and_then(|window_handle| {
10009                    window_handle
10010                        .update(cx, |multi_workspace, _window, cx| {
10011                            multi_workspace
10012                                .workspaces()
10013                                .find(|workspace| {
10014                                    workspace.read(cx).project().read(cx).remote_id()
10015                                        == Some(project_id)
10016                                })
10017                                .map(|workspace| (window_handle, workspace.clone()))
10018                        })
10019                        .unwrap_or(None)
10020                })
10021        });
10022
10023        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
10024            existing_window_and_workspace
10025        {
10026            existing_window
10027                .update(cx, |multi_workspace, window, cx| {
10028                    multi_workspace.activate(target_workspace, window, cx);
10029                })
10030                .ok();
10031            existing_window
10032        } else {
10033            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
10034            let project = cx
10035                .update(|cx| {
10036                    active_call.0.join_project(
10037                        project_id,
10038                        app_state.languages.clone(),
10039                        app_state.fs.clone(),
10040                        cx,
10041                    )
10042                })
10043                .await?;
10044
10045            let window_bounds_override = window_bounds_env_override();
10046            cx.update(|cx| {
10047                let mut options = (app_state.build_window_options)(None, cx);
10048                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
10049                cx.open_window(options, |window, cx| {
10050                    let workspace = cx.new(|cx| {
10051                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
10052                    });
10053                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
10054                })
10055            })?
10056        };
10057
10058        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
10059            cx.activate(true);
10060            window.activate_window();
10061
10062            // We set the active workspace above, so this is the correct workspace.
10063            let workspace = multi_workspace.workspace().clone();
10064            workspace.update(cx, |workspace, cx| {
10065                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
10066                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
10067                    .or_else(|| {
10068                        // If we couldn't follow the given user, follow the host instead.
10069                        let collaborator = workspace
10070                            .project()
10071                            .read(cx)
10072                            .collaborators()
10073                            .values()
10074                            .find(|collaborator| collaborator.is_host)?;
10075                        Some(collaborator.peer_id)
10076                    });
10077
10078                if let Some(follow_peer_id) = follow_peer_id {
10079                    workspace.follow(follow_peer_id, window, cx);
10080                }
10081            });
10082        })?;
10083
10084        anyhow::Ok(())
10085    })
10086}
10087
10088pub fn reload(cx: &mut App) {
10089    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
10090    let mut workspace_windows = cx
10091        .windows()
10092        .into_iter()
10093        .filter_map(|window| window.downcast::<MultiWorkspace>())
10094        .collect::<Vec<_>>();
10095
10096    // If multiple windows have unsaved changes, and need a save prompt,
10097    // prompt in the active window before switching to a different window.
10098    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
10099
10100    let mut prompt = None;
10101    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
10102        prompt = window
10103            .update(cx, |_, window, cx| {
10104                window.prompt(
10105                    PromptLevel::Info,
10106                    "Are you sure you want to restart?",
10107                    None,
10108                    &["Restart", "Cancel"],
10109                    cx,
10110                )
10111            })
10112            .ok();
10113    }
10114
10115    cx.spawn(async move |cx| {
10116        if let Some(prompt) = prompt {
10117            let answer = prompt.await?;
10118            if answer != 0 {
10119                return anyhow::Ok(());
10120            }
10121        }
10122
10123        // If the user cancels any save prompt, then keep the app open.
10124        for window in workspace_windows {
10125            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
10126                let workspace = multi_workspace.workspace().clone();
10127                workspace.update(cx, |workspace, cx| {
10128                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
10129                })
10130            }) && !should_close.await?
10131            {
10132                return anyhow::Ok(());
10133            }
10134        }
10135        cx.update(|cx| cx.restart());
10136        anyhow::Ok(())
10137    })
10138    .detach_and_log_err(cx);
10139}
10140
10141fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
10142    let mut parts = value.split(',');
10143    let x: usize = parts.next()?.parse().ok()?;
10144    let y: usize = parts.next()?.parse().ok()?;
10145    Some(point(px(x as f32), px(y as f32)))
10146}
10147
10148fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
10149    let mut parts = value.split(',');
10150    let width: usize = parts.next()?.parse().ok()?;
10151    let height: usize = parts.next()?.parse().ok()?;
10152    Some(size(px(width as f32), px(height as f32)))
10153}
10154
10155/// Add client-side decorations (rounded corners, shadows, resize handling) when
10156/// appropriate.
10157///
10158/// The `border_radius_tiling` parameter allows overriding which corners get
10159/// rounded, independently of the actual window tiling state. This is used
10160/// specifically for the workspace switcher sidebar: when the sidebar is open,
10161/// we want square corners on the left (so the sidebar appears flush with the
10162/// window edge) but we still need the shadow padding for proper visual
10163/// appearance. Unlike actual window tiling, this only affects border radius -
10164/// not padding or shadows.
10165pub fn client_side_decorations(
10166    element: impl IntoElement,
10167    window: &mut Window,
10168    cx: &mut App,
10169    border_radius_tiling: Tiling,
10170) -> Stateful<Div> {
10171    const BORDER_SIZE: Pixels = px(1.0);
10172    let decorations = window.window_decorations();
10173    let tiling = match decorations {
10174        Decorations::Server => Tiling::default(),
10175        Decorations::Client { tiling } => tiling,
10176    };
10177
10178    match decorations {
10179        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
10180        Decorations::Server => window.set_client_inset(px(0.0)),
10181    }
10182
10183    struct GlobalResizeEdge(ResizeEdge);
10184    impl Global for GlobalResizeEdge {}
10185
10186    div()
10187        .id("window-backdrop")
10188        .bg(transparent_black())
10189        .map(|div| match decorations {
10190            Decorations::Server => div,
10191            Decorations::Client { .. } => div
10192                .when(
10193                    !(tiling.top
10194                        || tiling.right
10195                        || border_radius_tiling.top
10196                        || border_radius_tiling.right),
10197                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10198                )
10199                .when(
10200                    !(tiling.top
10201                        || tiling.left
10202                        || border_radius_tiling.top
10203                        || border_radius_tiling.left),
10204                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10205                )
10206                .when(
10207                    !(tiling.bottom
10208                        || tiling.right
10209                        || border_radius_tiling.bottom
10210                        || border_radius_tiling.right),
10211                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10212                )
10213                .when(
10214                    !(tiling.bottom
10215                        || tiling.left
10216                        || border_radius_tiling.bottom
10217                        || border_radius_tiling.left),
10218                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10219                )
10220                .when(!tiling.top, |div| {
10221                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
10222                })
10223                .when(!tiling.bottom, |div| {
10224                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
10225                })
10226                .when(!tiling.left, |div| {
10227                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10228                })
10229                .when(!tiling.right, |div| {
10230                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10231                })
10232                .on_mouse_move(move |e, window, cx| {
10233                    let size = window.window_bounds().get_bounds().size;
10234                    let pos = e.position;
10235
10236                    let new_edge =
10237                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10238
10239                    let edge = cx.try_global::<GlobalResizeEdge>();
10240                    if new_edge != edge.map(|edge| edge.0) {
10241                        window
10242                            .window_handle()
10243                            .update(cx, |workspace, _, cx| {
10244                                cx.notify(workspace.entity_id());
10245                            })
10246                            .ok();
10247                    }
10248                })
10249                .on_mouse_down(MouseButton::Left, move |e, window, _| {
10250                    let size = window.window_bounds().get_bounds().size;
10251                    let pos = e.position;
10252
10253                    let edge = match resize_edge(
10254                        pos,
10255                        theme::CLIENT_SIDE_DECORATION_SHADOW,
10256                        size,
10257                        tiling,
10258                    ) {
10259                        Some(value) => value,
10260                        None => return,
10261                    };
10262
10263                    window.start_window_resize(edge);
10264                }),
10265        })
10266        .size_full()
10267        .child(
10268            div()
10269                .cursor(CursorStyle::Arrow)
10270                .map(|div| match decorations {
10271                    Decorations::Server => div,
10272                    Decorations::Client { .. } => div
10273                        .border_color(cx.theme().colors().border)
10274                        .when(
10275                            !(tiling.top
10276                                || tiling.right
10277                                || border_radius_tiling.top
10278                                || border_radius_tiling.right),
10279                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10280                        )
10281                        .when(
10282                            !(tiling.top
10283                                || tiling.left
10284                                || border_radius_tiling.top
10285                                || border_radius_tiling.left),
10286                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10287                        )
10288                        .when(
10289                            !(tiling.bottom
10290                                || tiling.right
10291                                || border_radius_tiling.bottom
10292                                || border_radius_tiling.right),
10293                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10294                        )
10295                        .when(
10296                            !(tiling.bottom
10297                                || tiling.left
10298                                || border_radius_tiling.bottom
10299                                || border_radius_tiling.left),
10300                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10301                        )
10302                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10303                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10304                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10305                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10306                        .when(!tiling.is_tiled(), |div| {
10307                            div.shadow(vec![gpui::BoxShadow {
10308                                color: Hsla {
10309                                    h: 0.,
10310                                    s: 0.,
10311                                    l: 0.,
10312                                    a: 0.4,
10313                                },
10314                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10315                                spread_radius: px(0.),
10316                                offset: point(px(0.0), px(0.0)),
10317                            }])
10318                        }),
10319                })
10320                .on_mouse_move(|_e, _, cx| {
10321                    cx.stop_propagation();
10322                })
10323                .size_full()
10324                .child(element),
10325        )
10326        .map(|div| match decorations {
10327            Decorations::Server => div,
10328            Decorations::Client { tiling, .. } => div.child(
10329                canvas(
10330                    |_bounds, window, _| {
10331                        window.insert_hitbox(
10332                            Bounds::new(
10333                                point(px(0.0), px(0.0)),
10334                                window.window_bounds().get_bounds().size,
10335                            ),
10336                            HitboxBehavior::Normal,
10337                        )
10338                    },
10339                    move |_bounds, hitbox, window, cx| {
10340                        let mouse = window.mouse_position();
10341                        let size = window.window_bounds().get_bounds().size;
10342                        let Some(edge) =
10343                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10344                        else {
10345                            return;
10346                        };
10347                        cx.set_global(GlobalResizeEdge(edge));
10348                        window.set_cursor_style(
10349                            match edge {
10350                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10351                                ResizeEdge::Left | ResizeEdge::Right => {
10352                                    CursorStyle::ResizeLeftRight
10353                                }
10354                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10355                                    CursorStyle::ResizeUpLeftDownRight
10356                                }
10357                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10358                                    CursorStyle::ResizeUpRightDownLeft
10359                                }
10360                            },
10361                            &hitbox,
10362                        );
10363                    },
10364                )
10365                .size_full()
10366                .absolute(),
10367            ),
10368        })
10369}
10370
10371fn resize_edge(
10372    pos: Point<Pixels>,
10373    shadow_size: Pixels,
10374    window_size: Size<Pixels>,
10375    tiling: Tiling,
10376) -> Option<ResizeEdge> {
10377    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10378    if bounds.contains(&pos) {
10379        return None;
10380    }
10381
10382    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10383    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10384    if !tiling.top && top_left_bounds.contains(&pos) {
10385        return Some(ResizeEdge::TopLeft);
10386    }
10387
10388    let top_right_bounds = Bounds::new(
10389        Point::new(window_size.width - corner_size.width, px(0.)),
10390        corner_size,
10391    );
10392    if !tiling.top && top_right_bounds.contains(&pos) {
10393        return Some(ResizeEdge::TopRight);
10394    }
10395
10396    let bottom_left_bounds = Bounds::new(
10397        Point::new(px(0.), window_size.height - corner_size.height),
10398        corner_size,
10399    );
10400    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10401        return Some(ResizeEdge::BottomLeft);
10402    }
10403
10404    let bottom_right_bounds = Bounds::new(
10405        Point::new(
10406            window_size.width - corner_size.width,
10407            window_size.height - corner_size.height,
10408        ),
10409        corner_size,
10410    );
10411    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10412        return Some(ResizeEdge::BottomRight);
10413    }
10414
10415    if !tiling.top && pos.y < shadow_size {
10416        Some(ResizeEdge::Top)
10417    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10418        Some(ResizeEdge::Bottom)
10419    } else if !tiling.left && pos.x < shadow_size {
10420        Some(ResizeEdge::Left)
10421    } else if !tiling.right && pos.x > window_size.width - shadow_size {
10422        Some(ResizeEdge::Right)
10423    } else {
10424        None
10425    }
10426}
10427
10428fn join_pane_into_active(
10429    active_pane: &Entity<Pane>,
10430    pane: &Entity<Pane>,
10431    window: &mut Window,
10432    cx: &mut App,
10433) {
10434    if pane == active_pane {
10435    } else if pane.read(cx).items_len() == 0 {
10436        pane.update(cx, |_, cx| {
10437            cx.emit(pane::Event::Remove {
10438                focus_on_pane: None,
10439            });
10440        })
10441    } else {
10442        move_all_items(pane, active_pane, window, cx);
10443    }
10444}
10445
10446fn move_all_items(
10447    from_pane: &Entity<Pane>,
10448    to_pane: &Entity<Pane>,
10449    window: &mut Window,
10450    cx: &mut App,
10451) {
10452    let destination_is_different = from_pane != to_pane;
10453    let mut moved_items = 0;
10454    for (item_ix, item_handle) in from_pane
10455        .read(cx)
10456        .items()
10457        .enumerate()
10458        .map(|(ix, item)| (ix, item.clone()))
10459        .collect::<Vec<_>>()
10460    {
10461        let ix = item_ix - moved_items;
10462        if destination_is_different {
10463            // Close item from previous pane
10464            from_pane.update(cx, |source, cx| {
10465                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10466            });
10467            moved_items += 1;
10468        }
10469
10470        // This automatically removes duplicate items in the pane
10471        to_pane.update(cx, |destination, cx| {
10472            destination.add_item(item_handle, true, true, None, window, cx);
10473            window.focus(&destination.focus_handle(cx), cx)
10474        });
10475    }
10476}
10477
10478pub fn move_item(
10479    source: &Entity<Pane>,
10480    destination: &Entity<Pane>,
10481    item_id_to_move: EntityId,
10482    destination_index: usize,
10483    activate: bool,
10484    window: &mut Window,
10485    cx: &mut App,
10486) {
10487    let Some((item_ix, item_handle)) = source
10488        .read(cx)
10489        .items()
10490        .enumerate()
10491        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10492        .map(|(ix, item)| (ix, item.clone()))
10493    else {
10494        // Tab was closed during drag
10495        return;
10496    };
10497
10498    if source != destination {
10499        // Close item from previous pane
10500        source.update(cx, |source, cx| {
10501            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10502        });
10503    }
10504
10505    // This automatically removes duplicate items in the pane
10506    destination.update(cx, |destination, cx| {
10507        destination.add_item_inner(
10508            item_handle,
10509            activate,
10510            activate,
10511            activate,
10512            Some(destination_index),
10513            window,
10514            cx,
10515        );
10516        if activate {
10517            window.focus(&destination.focus_handle(cx), cx)
10518        }
10519    });
10520}
10521
10522pub fn move_active_item(
10523    source: &Entity<Pane>,
10524    destination: &Entity<Pane>,
10525    focus_destination: bool,
10526    close_if_empty: bool,
10527    window: &mut Window,
10528    cx: &mut App,
10529) {
10530    if source == destination {
10531        return;
10532    }
10533    let Some(active_item) = source.read(cx).active_item() else {
10534        return;
10535    };
10536    source.update(cx, |source_pane, cx| {
10537        let item_id = active_item.item_id();
10538        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10539        destination.update(cx, |target_pane, cx| {
10540            target_pane.add_item(
10541                active_item,
10542                focus_destination,
10543                focus_destination,
10544                Some(target_pane.items_len()),
10545                window,
10546                cx,
10547            );
10548        });
10549    });
10550}
10551
10552pub fn clone_active_item(
10553    workspace_id: Option<WorkspaceId>,
10554    source: &Entity<Pane>,
10555    destination: &Entity<Pane>,
10556    focus_destination: bool,
10557    window: &mut Window,
10558    cx: &mut App,
10559) {
10560    if source == destination {
10561        return;
10562    }
10563    let Some(active_item) = source.read(cx).active_item() else {
10564        return;
10565    };
10566    if !active_item.can_split(cx) {
10567        return;
10568    }
10569    let destination = destination.downgrade();
10570    let task = active_item.clone_on_split(workspace_id, window, cx);
10571    window
10572        .spawn(cx, async move |cx| {
10573            let Some(clone) = task.await else {
10574                return;
10575            };
10576            destination
10577                .update_in(cx, |target_pane, window, cx| {
10578                    target_pane.add_item(
10579                        clone,
10580                        focus_destination,
10581                        focus_destination,
10582                        Some(target_pane.items_len()),
10583                        window,
10584                        cx,
10585                    );
10586                })
10587                .log_err();
10588        })
10589        .detach();
10590}
10591
10592#[derive(Debug)]
10593pub struct WorkspacePosition {
10594    pub window_bounds: Option<WindowBounds>,
10595    pub display: Option<Uuid>,
10596    pub centered_layout: bool,
10597}
10598
10599pub fn remote_workspace_position_from_db(
10600    connection_options: RemoteConnectionOptions,
10601    paths_to_open: &[PathBuf],
10602    cx: &App,
10603) -> Task<Result<WorkspacePosition>> {
10604    let paths = paths_to_open.to_vec();
10605    let db = WorkspaceDb::global(cx);
10606    let kvp = db::kvp::KeyValueStore::global(cx);
10607
10608    cx.background_spawn(async move {
10609        let remote_connection_id = db
10610            .get_or_create_remote_connection(connection_options)
10611            .await
10612            .context("fetching serialized ssh project")?;
10613        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10614
10615        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10616            (Some(WindowBounds::Windowed(bounds)), None)
10617        } else {
10618            let restorable_bounds = serialized_workspace
10619                .as_ref()
10620                .and_then(|workspace| {
10621                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10622                })
10623                .or_else(|| persistence::read_default_window_bounds(&kvp));
10624
10625            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10626                (Some(serialized_bounds), Some(serialized_display))
10627            } else {
10628                (None, None)
10629            }
10630        };
10631
10632        let centered_layout = serialized_workspace
10633            .as_ref()
10634            .map(|w| w.centered_layout)
10635            .unwrap_or(false);
10636
10637        Ok(WorkspacePosition {
10638            window_bounds,
10639            display,
10640            centered_layout,
10641        })
10642    })
10643}
10644
10645pub fn with_active_or_new_workspace(
10646    cx: &mut App,
10647    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10648) {
10649    match cx
10650        .active_window()
10651        .and_then(|w| w.downcast::<MultiWorkspace>())
10652    {
10653        Some(multi_workspace) => {
10654            cx.defer(move |cx| {
10655                multi_workspace
10656                    .update(cx, |multi_workspace, window, cx| {
10657                        let workspace = multi_workspace.workspace().clone();
10658                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10659                    })
10660                    .log_err();
10661            });
10662        }
10663        None => {
10664            let app_state = AppState::global(cx);
10665            open_new(
10666                OpenOptions::default(),
10667                app_state,
10668                cx,
10669                move |workspace, window, cx| f(workspace, window, cx),
10670            )
10671            .detach_and_log_err(cx);
10672        }
10673    }
10674}
10675
10676/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10677/// key. This migration path only runs once per panel per workspace.
10678fn load_legacy_panel_size(
10679    panel_key: &str,
10680    dock_position: DockPosition,
10681    workspace: &Workspace,
10682    cx: &mut App,
10683) -> Option<Pixels> {
10684    #[derive(Deserialize)]
10685    struct LegacyPanelState {
10686        #[serde(default)]
10687        width: Option<Pixels>,
10688        #[serde(default)]
10689        height: Option<Pixels>,
10690    }
10691
10692    let workspace_id = workspace
10693        .database_id()
10694        .map(|id| i64::from(id).to_string())
10695        .or_else(|| workspace.session_id())?;
10696
10697    let legacy_key = match panel_key {
10698        "ProjectPanel" => {
10699            format!("{}-{:?}", "ProjectPanel", workspace_id)
10700        }
10701        "OutlinePanel" => {
10702            format!("{}-{:?}", "OutlinePanel", workspace_id)
10703        }
10704        "GitPanel" => {
10705            format!("{}-{:?}", "GitPanel", workspace_id)
10706        }
10707        "TerminalPanel" => {
10708            format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10709        }
10710        _ => return None,
10711    };
10712
10713    let kvp = db::kvp::KeyValueStore::global(cx);
10714    let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10715    let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10716    let size = match dock_position {
10717        DockPosition::Bottom => state.height,
10718        DockPosition::Left | DockPosition::Right => state.width,
10719    }?;
10720
10721    cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10722        .detach_and_log_err(cx);
10723
10724    Some(size)
10725}
10726
10727#[cfg(test)]
10728mod tests {
10729    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10730
10731    use super::*;
10732    use crate::{
10733        dock::{PanelEvent, test::TestPanel},
10734        item::{
10735            ItemBufferKind, ItemEvent,
10736            test::{TestItem, TestProjectItem},
10737        },
10738    };
10739    use fs::FakeFs;
10740    use gpui::{
10741        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10742        UpdateGlobal, VisualTestContext, px,
10743    };
10744    use project::{Project, ProjectEntryId};
10745    use serde_json::json;
10746    use settings::SettingsStore;
10747    use util::path;
10748    use util::rel_path::rel_path;
10749
10750    #[gpui::test]
10751    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10752        init_test(cx);
10753
10754        let fs = FakeFs::new(cx.executor());
10755        let project = Project::test(fs, [], cx).await;
10756        let (workspace, cx) =
10757            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10758
10759        // Adding an item with no ambiguity renders the tab without detail.
10760        let item1 = cx.new(|cx| {
10761            let mut item = TestItem::new(cx);
10762            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10763            item
10764        });
10765        workspace.update_in(cx, |workspace, window, cx| {
10766            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10767        });
10768        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10769
10770        // Adding an item that creates ambiguity increases the level of detail on
10771        // both tabs.
10772        let item2 = cx.new_window_entity(|_window, cx| {
10773            let mut item = TestItem::new(cx);
10774            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10775            item
10776        });
10777        workspace.update_in(cx, |workspace, window, cx| {
10778            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10779        });
10780        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10781        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10782
10783        // Adding an item that creates ambiguity increases the level of detail only
10784        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10785        // we stop at the highest detail available.
10786        let item3 = cx.new(|cx| {
10787            let mut item = TestItem::new(cx);
10788            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10789            item
10790        });
10791        workspace.update_in(cx, |workspace, window, cx| {
10792            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10793        });
10794        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10795        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10796        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10797    }
10798
10799    #[gpui::test]
10800    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10801        init_test(cx);
10802
10803        let fs = FakeFs::new(cx.executor());
10804        fs.insert_tree(
10805            "/root1",
10806            json!({
10807                "one.txt": "",
10808                "two.txt": "",
10809            }),
10810        )
10811        .await;
10812        fs.insert_tree(
10813            "/root2",
10814            json!({
10815                "three.txt": "",
10816            }),
10817        )
10818        .await;
10819
10820        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10821        let (workspace, cx) =
10822            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10823        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10824        let worktree_id = project.update(cx, |project, cx| {
10825            project.worktrees(cx).next().unwrap().read(cx).id()
10826        });
10827
10828        let item1 = cx.new(|cx| {
10829            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10830        });
10831        let item2 = cx.new(|cx| {
10832            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10833        });
10834
10835        // Add an item to an empty pane
10836        workspace.update_in(cx, |workspace, window, cx| {
10837            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10838        });
10839        project.update(cx, |project, cx| {
10840            assert_eq!(
10841                project.active_entry(),
10842                project
10843                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10844                    .map(|e| e.id)
10845            );
10846        });
10847        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10848
10849        // Add a second item to a non-empty pane
10850        workspace.update_in(cx, |workspace, window, cx| {
10851            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10852        });
10853        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10854        project.update(cx, |project, cx| {
10855            assert_eq!(
10856                project.active_entry(),
10857                project
10858                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10859                    .map(|e| e.id)
10860            );
10861        });
10862
10863        // Close the active item
10864        pane.update_in(cx, |pane, window, cx| {
10865            pane.close_active_item(&Default::default(), window, cx)
10866        })
10867        .await
10868        .unwrap();
10869        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10870        project.update(cx, |project, cx| {
10871            assert_eq!(
10872                project.active_entry(),
10873                project
10874                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10875                    .map(|e| e.id)
10876            );
10877        });
10878
10879        // Add a project folder
10880        project
10881            .update(cx, |project, cx| {
10882                project.find_or_create_worktree("root2", true, cx)
10883            })
10884            .await
10885            .unwrap();
10886        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10887
10888        // Remove a project folder
10889        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10890        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10891    }
10892
10893    #[gpui::test]
10894    async fn test_close_window(cx: &mut TestAppContext) {
10895        init_test(cx);
10896
10897        let fs = FakeFs::new(cx.executor());
10898        fs.insert_tree("/root", json!({ "one": "" })).await;
10899
10900        let project = Project::test(fs, ["root".as_ref()], cx).await;
10901        let (workspace, cx) =
10902            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10903
10904        // When there are no dirty items, there's nothing to do.
10905        let item1 = cx.new(TestItem::new);
10906        workspace.update_in(cx, |w, window, cx| {
10907            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10908        });
10909        let task = workspace.update_in(cx, |w, window, cx| {
10910            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10911        });
10912        assert!(task.await.unwrap());
10913
10914        // When there are dirty untitled items, prompt to save each one. If the user
10915        // cancels any prompt, then abort.
10916        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10917        let item3 = cx.new(|cx| {
10918            TestItem::new(cx)
10919                .with_dirty(true)
10920                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10921        });
10922        workspace.update_in(cx, |w, window, cx| {
10923            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10924            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10925        });
10926        let task = workspace.update_in(cx, |w, window, cx| {
10927            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10928        });
10929        cx.executor().run_until_parked();
10930        cx.simulate_prompt_answer("Cancel"); // cancel save all
10931        cx.executor().run_until_parked();
10932        assert!(!cx.has_pending_prompt());
10933        assert!(!task.await.unwrap());
10934    }
10935
10936    #[gpui::test]
10937    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10938        init_test(cx);
10939
10940        let fs = FakeFs::new(cx.executor());
10941        fs.insert_tree("/root", json!({ "one": "" })).await;
10942
10943        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10944        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10945        let multi_workspace_handle =
10946            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10947        cx.run_until_parked();
10948
10949        multi_workspace_handle
10950            .update(cx, |mw, _window, cx| {
10951                mw.open_sidebar(cx);
10952            })
10953            .unwrap();
10954
10955        let workspace_a = multi_workspace_handle
10956            .read_with(cx, |mw, _| mw.workspace().clone())
10957            .unwrap();
10958
10959        let workspace_b = multi_workspace_handle
10960            .update(cx, |mw, window, cx| {
10961                mw.test_add_workspace(project_b, window, cx)
10962            })
10963            .unwrap();
10964
10965        // Activate workspace A
10966        multi_workspace_handle
10967            .update(cx, |mw, window, cx| {
10968                mw.activate(workspace_a.clone(), window, cx);
10969            })
10970            .unwrap();
10971
10972        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10973
10974        // Workspace A has a clean item
10975        let item_a = cx.new(TestItem::new);
10976        workspace_a.update_in(cx, |w, window, cx| {
10977            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10978        });
10979
10980        // Workspace B has a dirty item
10981        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10982        workspace_b.update_in(cx, |w, window, cx| {
10983            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10984        });
10985
10986        // Verify workspace A is active
10987        multi_workspace_handle
10988            .read_with(cx, |mw, _| {
10989                assert_eq!(mw.workspace(), &workspace_a);
10990            })
10991            .unwrap();
10992
10993        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10994        multi_workspace_handle
10995            .update(cx, |mw, window, cx| {
10996                mw.close_window(&CloseWindow, window, cx);
10997            })
10998            .unwrap();
10999        cx.run_until_parked();
11000
11001        // Workspace B should now be active since it has dirty items that need attention
11002        multi_workspace_handle
11003            .read_with(cx, |mw, _| {
11004                assert_eq!(
11005                    mw.workspace(),
11006                    &workspace_b,
11007                    "workspace B should be activated when it prompts"
11008                );
11009            })
11010            .unwrap();
11011
11012        // User cancels the save prompt from workspace B
11013        cx.simulate_prompt_answer("Cancel");
11014        cx.run_until_parked();
11015
11016        // Window should still exist because workspace B's close was cancelled
11017        assert!(
11018            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
11019            "window should still exist after cancelling one workspace's close"
11020        );
11021    }
11022
11023    #[gpui::test]
11024    async fn test_remove_workspace_prompts_for_unsaved_changes(cx: &mut TestAppContext) {
11025        init_test(cx);
11026
11027        let fs = FakeFs::new(cx.executor());
11028        fs.insert_tree("/root", json!({ "one": "" })).await;
11029
11030        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
11031        let project_b = Project::test(fs.clone(), ["root".as_ref()], cx).await;
11032        let multi_workspace_handle =
11033            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
11034        cx.run_until_parked();
11035
11036        multi_workspace_handle
11037            .update(cx, |mw, _window, cx| mw.open_sidebar(cx))
11038            .unwrap();
11039
11040        let workspace_a = multi_workspace_handle
11041            .read_with(cx, |mw, _| mw.workspace().clone())
11042            .unwrap();
11043
11044        let workspace_b = multi_workspace_handle
11045            .update(cx, |mw, window, cx| {
11046                mw.test_add_workspace(project_b, window, cx)
11047            })
11048            .unwrap();
11049
11050        // Activate workspace A.
11051        multi_workspace_handle
11052            .update(cx, |mw, window, cx| {
11053                mw.activate(workspace_a.clone(), window, cx);
11054            })
11055            .unwrap();
11056
11057        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
11058
11059        // Workspace B has a dirty item.
11060        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
11061        workspace_b.update_in(cx, |w, window, cx| {
11062            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
11063        });
11064
11065        // Try to remove workspace B. It should prompt because of the dirty item.
11066        let remove_task = multi_workspace_handle
11067            .update(cx, |mw, window, cx| {
11068                mw.remove([workspace_b.clone()], |_, _, _| unreachable!(), window, cx)
11069            })
11070            .unwrap();
11071        cx.run_until_parked();
11072
11073        // The prompt should have activated workspace B.
11074        multi_workspace_handle
11075            .read_with(cx, |mw, _| {
11076                assert_eq!(
11077                    mw.workspace(),
11078                    &workspace_b,
11079                    "workspace B should be active while prompting"
11080                );
11081            })
11082            .unwrap();
11083
11084        // Cancel the prompt — user stays on workspace B.
11085        cx.simulate_prompt_answer("Cancel");
11086        cx.run_until_parked();
11087        let removed = remove_task.await.unwrap();
11088        assert!(!removed, "removal should have been cancelled");
11089
11090        multi_workspace_handle
11091            .read_with(cx, |mw, _cx| {
11092                assert_eq!(
11093                    mw.workspace(),
11094                    &workspace_b,
11095                    "user should stay on workspace B after cancelling"
11096                );
11097                assert_eq!(mw.workspaces().count(), 2, "both workspaces should remain");
11098            })
11099            .unwrap();
11100
11101        // Try again. This time accept the prompt.
11102        let remove_task = multi_workspace_handle
11103            .update(cx, |mw, window, cx| {
11104                // First switch back to A.
11105                mw.activate(workspace_a.clone(), window, cx);
11106                mw.remove([workspace_b.clone()], |_, _, _| unreachable!(), window, cx)
11107            })
11108            .unwrap();
11109        cx.run_until_parked();
11110
11111        // Accept the save prompt.
11112        cx.simulate_prompt_answer("Don't Save");
11113        cx.run_until_parked();
11114        let removed = remove_task.await.unwrap();
11115        assert!(removed, "removal should have succeeded");
11116
11117        // Should be back on workspace A, and B should be gone.
11118        multi_workspace_handle
11119            .read_with(cx, |mw, _cx| {
11120                assert_eq!(
11121                    mw.workspace(),
11122                    &workspace_a,
11123                    "should be back on workspace A after removing B"
11124                );
11125                assert_eq!(mw.workspaces().count(), 1, "only workspace A should remain");
11126            })
11127            .unwrap();
11128    }
11129
11130    #[gpui::test]
11131    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
11132        init_test(cx);
11133
11134        // Register TestItem as a serializable item
11135        cx.update(|cx| {
11136            register_serializable_item::<TestItem>(cx);
11137        });
11138
11139        let fs = FakeFs::new(cx.executor());
11140        fs.insert_tree("/root", json!({ "one": "" })).await;
11141
11142        let project = Project::test(fs, ["root".as_ref()], cx).await;
11143        let (workspace, cx) =
11144            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11145
11146        // When there are dirty untitled items, but they can serialize, then there is no prompt.
11147        let item1 = cx.new(|cx| {
11148            TestItem::new(cx)
11149                .with_dirty(true)
11150                .with_serialize(|| Some(Task::ready(Ok(()))))
11151        });
11152        let item2 = cx.new(|cx| {
11153            TestItem::new(cx)
11154                .with_dirty(true)
11155                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11156                .with_serialize(|| Some(Task::ready(Ok(()))))
11157        });
11158        workspace.update_in(cx, |w, window, cx| {
11159            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
11160            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
11161        });
11162        let task = workspace.update_in(cx, |w, window, cx| {
11163            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
11164        });
11165        assert!(task.await.unwrap());
11166    }
11167
11168    #[gpui::test]
11169    async fn test_close_pane_items(cx: &mut TestAppContext) {
11170        init_test(cx);
11171
11172        let fs = FakeFs::new(cx.executor());
11173
11174        let project = Project::test(fs, None, cx).await;
11175        let (workspace, cx) =
11176            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11177
11178        let item1 = cx.new(|cx| {
11179            TestItem::new(cx)
11180                .with_dirty(true)
11181                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11182        });
11183        let item2 = cx.new(|cx| {
11184            TestItem::new(cx)
11185                .with_dirty(true)
11186                .with_conflict(true)
11187                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11188        });
11189        let item3 = cx.new(|cx| {
11190            TestItem::new(cx)
11191                .with_dirty(true)
11192                .with_conflict(true)
11193                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
11194        });
11195        let item4 = cx.new(|cx| {
11196            TestItem::new(cx).with_dirty(true).with_project_items(&[{
11197                let project_item = TestProjectItem::new_untitled(cx);
11198                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11199                project_item
11200            }])
11201        });
11202        let pane = workspace.update_in(cx, |workspace, window, cx| {
11203            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
11204            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
11205            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
11206            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
11207            workspace.active_pane().clone()
11208        });
11209
11210        let close_items = pane.update_in(cx, |pane, window, cx| {
11211            pane.activate_item(1, true, true, window, cx);
11212            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
11213            let item1_id = item1.item_id();
11214            let item3_id = item3.item_id();
11215            let item4_id = item4.item_id();
11216            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
11217                [item1_id, item3_id, item4_id].contains(&id)
11218            })
11219        });
11220        cx.executor().run_until_parked();
11221
11222        assert!(cx.has_pending_prompt());
11223        cx.simulate_prompt_answer("Save all");
11224
11225        cx.executor().run_until_parked();
11226
11227        // Item 1 is saved. There's a prompt to save item 3.
11228        pane.update(cx, |pane, cx| {
11229            assert_eq!(item1.read(cx).save_count, 1);
11230            assert_eq!(item1.read(cx).save_as_count, 0);
11231            assert_eq!(item1.read(cx).reload_count, 0);
11232            assert_eq!(pane.items_len(), 3);
11233            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
11234        });
11235        assert!(cx.has_pending_prompt());
11236
11237        // Cancel saving item 3.
11238        cx.simulate_prompt_answer("Discard");
11239        cx.executor().run_until_parked();
11240
11241        // Item 3 is reloaded. There's a prompt to save item 4.
11242        pane.update(cx, |pane, cx| {
11243            assert_eq!(item3.read(cx).save_count, 0);
11244            assert_eq!(item3.read(cx).save_as_count, 0);
11245            assert_eq!(item3.read(cx).reload_count, 1);
11246            assert_eq!(pane.items_len(), 2);
11247            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
11248        });
11249
11250        // There's a prompt for a path for item 4.
11251        cx.simulate_new_path_selection(|_| Some(Default::default()));
11252        close_items.await.unwrap();
11253
11254        // The requested items are closed.
11255        pane.update(cx, |pane, cx| {
11256            assert_eq!(item4.read(cx).save_count, 0);
11257            assert_eq!(item4.read(cx).save_as_count, 1);
11258            assert_eq!(item4.read(cx).reload_count, 0);
11259            assert_eq!(pane.items_len(), 1);
11260            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
11261        });
11262    }
11263
11264    #[gpui::test]
11265    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
11266        init_test(cx);
11267
11268        let fs = FakeFs::new(cx.executor());
11269        let project = Project::test(fs, [], cx).await;
11270        let (workspace, cx) =
11271            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11272
11273        // Create several workspace items with single project entries, and two
11274        // workspace items with multiple project entries.
11275        let single_entry_items = (0..=4)
11276            .map(|project_entry_id| {
11277                cx.new(|cx| {
11278                    TestItem::new(cx)
11279                        .with_dirty(true)
11280                        .with_project_items(&[dirty_project_item(
11281                            project_entry_id,
11282                            &format!("{project_entry_id}.txt"),
11283                            cx,
11284                        )])
11285                })
11286            })
11287            .collect::<Vec<_>>();
11288        let item_2_3 = cx.new(|cx| {
11289            TestItem::new(cx)
11290                .with_dirty(true)
11291                .with_buffer_kind(ItemBufferKind::Multibuffer)
11292                .with_project_items(&[
11293                    single_entry_items[2].read(cx).project_items[0].clone(),
11294                    single_entry_items[3].read(cx).project_items[0].clone(),
11295                ])
11296        });
11297        let item_3_4 = cx.new(|cx| {
11298            TestItem::new(cx)
11299                .with_dirty(true)
11300                .with_buffer_kind(ItemBufferKind::Multibuffer)
11301                .with_project_items(&[
11302                    single_entry_items[3].read(cx).project_items[0].clone(),
11303                    single_entry_items[4].read(cx).project_items[0].clone(),
11304                ])
11305        });
11306
11307        // Create two panes that contain the following project entries:
11308        //   left pane:
11309        //     multi-entry items:   (2, 3)
11310        //     single-entry items:  0, 2, 3, 4
11311        //   right pane:
11312        //     single-entry items:  4, 1
11313        //     multi-entry items:   (3, 4)
11314        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
11315            let left_pane = workspace.active_pane().clone();
11316            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
11317            workspace.add_item_to_active_pane(
11318                single_entry_items[0].boxed_clone(),
11319                None,
11320                true,
11321                window,
11322                cx,
11323            );
11324            workspace.add_item_to_active_pane(
11325                single_entry_items[2].boxed_clone(),
11326                None,
11327                true,
11328                window,
11329                cx,
11330            );
11331            workspace.add_item_to_active_pane(
11332                single_entry_items[3].boxed_clone(),
11333                None,
11334                true,
11335                window,
11336                cx,
11337            );
11338            workspace.add_item_to_active_pane(
11339                single_entry_items[4].boxed_clone(),
11340                None,
11341                true,
11342                window,
11343                cx,
11344            );
11345
11346            let right_pane =
11347                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11348
11349            let boxed_clone = single_entry_items[1].boxed_clone();
11350            let right_pane = window.spawn(cx, async move |cx| {
11351                right_pane.await.inspect(|right_pane| {
11352                    right_pane
11353                        .update_in(cx, |pane, window, cx| {
11354                            pane.add_item(boxed_clone, true, true, None, window, cx);
11355                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11356                        })
11357                        .unwrap();
11358                })
11359            });
11360
11361            (left_pane, right_pane)
11362        });
11363        let right_pane = right_pane.await.unwrap();
11364        cx.focus(&right_pane);
11365
11366        let close = right_pane.update_in(cx, |pane, window, cx| {
11367            pane.close_all_items(&CloseAllItems::default(), window, cx)
11368                .unwrap()
11369        });
11370        cx.executor().run_until_parked();
11371
11372        let msg = cx.pending_prompt().unwrap().0;
11373        assert!(msg.contains("1.txt"));
11374        assert!(!msg.contains("2.txt"));
11375        assert!(!msg.contains("3.txt"));
11376        assert!(!msg.contains("4.txt"));
11377
11378        // With best-effort close, cancelling item 1 keeps it open but items 4
11379        // and (3,4) still close since their entries exist in left pane.
11380        cx.simulate_prompt_answer("Cancel");
11381        close.await;
11382
11383        right_pane.read_with(cx, |pane, _| {
11384            assert_eq!(pane.items_len(), 1);
11385        });
11386
11387        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11388        left_pane
11389            .update_in(cx, |left_pane, window, cx| {
11390                left_pane.close_item_by_id(
11391                    single_entry_items[3].entity_id(),
11392                    SaveIntent::Skip,
11393                    window,
11394                    cx,
11395                )
11396            })
11397            .await
11398            .unwrap();
11399
11400        let close = left_pane.update_in(cx, |pane, window, cx| {
11401            pane.close_all_items(&CloseAllItems::default(), window, cx)
11402                .unwrap()
11403        });
11404        cx.executor().run_until_parked();
11405
11406        let details = cx.pending_prompt().unwrap().1;
11407        assert!(details.contains("0.txt"));
11408        assert!(details.contains("3.txt"));
11409        assert!(details.contains("4.txt"));
11410        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11411        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11412        // assert!(!details.contains("2.txt"));
11413
11414        cx.simulate_prompt_answer("Save all");
11415        cx.executor().run_until_parked();
11416        close.await;
11417
11418        left_pane.read_with(cx, |pane, _| {
11419            assert_eq!(pane.items_len(), 0);
11420        });
11421    }
11422
11423    #[gpui::test]
11424    async fn test_autosave(cx: &mut gpui::TestAppContext) {
11425        init_test(cx);
11426
11427        let fs = FakeFs::new(cx.executor());
11428        let project = Project::test(fs, [], cx).await;
11429        let (workspace, cx) =
11430            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11431        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11432
11433        let item = cx.new(|cx| {
11434            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11435        });
11436        let item_id = item.entity_id();
11437        workspace.update_in(cx, |workspace, window, cx| {
11438            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11439        });
11440
11441        // Autosave on window change.
11442        item.update(cx, |item, cx| {
11443            SettingsStore::update_global(cx, |settings, cx| {
11444                settings.update_user_settings(cx, |settings| {
11445                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11446                })
11447            });
11448            item.is_dirty = true;
11449        });
11450
11451        // Deactivating the window saves the file.
11452        cx.deactivate_window();
11453        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11454
11455        // Re-activating the window doesn't save the file.
11456        cx.update(|window, _| window.activate_window());
11457        cx.executor().run_until_parked();
11458        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11459
11460        // Autosave on focus change.
11461        item.update_in(cx, |item, window, cx| {
11462            cx.focus_self(window);
11463            SettingsStore::update_global(cx, |settings, cx| {
11464                settings.update_user_settings(cx, |settings| {
11465                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11466                })
11467            });
11468            item.is_dirty = true;
11469        });
11470        // Blurring the item saves the file.
11471        item.update_in(cx, |_, window, _| window.blur());
11472        cx.executor().run_until_parked();
11473        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11474
11475        // Deactivating the window still saves the file.
11476        item.update_in(cx, |item, window, cx| {
11477            cx.focus_self(window);
11478            item.is_dirty = true;
11479        });
11480        cx.deactivate_window();
11481        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11482
11483        // Autosave after delay.
11484        item.update(cx, |item, cx| {
11485            SettingsStore::update_global(cx, |settings, cx| {
11486                settings.update_user_settings(cx, |settings| {
11487                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11488                        milliseconds: 500.into(),
11489                    });
11490                })
11491            });
11492            item.is_dirty = true;
11493            cx.emit(ItemEvent::Edit);
11494        });
11495
11496        // Delay hasn't fully expired, so the file is still dirty and unsaved.
11497        cx.executor().advance_clock(Duration::from_millis(250));
11498        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11499
11500        // After delay expires, the file is saved.
11501        cx.executor().advance_clock(Duration::from_millis(250));
11502        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11503
11504        // Autosave after delay, should save earlier than delay if tab is closed
11505        item.update(cx, |item, cx| {
11506            item.is_dirty = true;
11507            cx.emit(ItemEvent::Edit);
11508        });
11509        cx.executor().advance_clock(Duration::from_millis(250));
11510        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11511
11512        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11513        pane.update_in(cx, |pane, window, cx| {
11514            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11515        })
11516        .await
11517        .unwrap();
11518        assert!(!cx.has_pending_prompt());
11519        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11520
11521        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11522        workspace.update_in(cx, |workspace, window, cx| {
11523            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11524        });
11525        item.update_in(cx, |item, _window, cx| {
11526            item.is_dirty = true;
11527            for project_item in &mut item.project_items {
11528                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11529            }
11530        });
11531        cx.run_until_parked();
11532        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11533
11534        // Autosave on focus change, ensuring closing the tab counts as such.
11535        item.update(cx, |item, cx| {
11536            SettingsStore::update_global(cx, |settings, cx| {
11537                settings.update_user_settings(cx, |settings| {
11538                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11539                })
11540            });
11541            item.is_dirty = true;
11542            for project_item in &mut item.project_items {
11543                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11544            }
11545        });
11546
11547        pane.update_in(cx, |pane, window, cx| {
11548            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11549        })
11550        .await
11551        .unwrap();
11552        assert!(!cx.has_pending_prompt());
11553        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11554
11555        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11556        workspace.update_in(cx, |workspace, window, cx| {
11557            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11558        });
11559        item.update_in(cx, |item, window, cx| {
11560            item.project_items[0].update(cx, |item, _| {
11561                item.entry_id = None;
11562            });
11563            item.is_dirty = true;
11564            window.blur();
11565        });
11566        cx.run_until_parked();
11567        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11568
11569        // Ensure autosave is prevented for deleted files also when closing the buffer.
11570        let _close_items = pane.update_in(cx, |pane, window, cx| {
11571            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11572        });
11573        cx.run_until_parked();
11574        assert!(cx.has_pending_prompt());
11575        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11576    }
11577
11578    #[gpui::test]
11579    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11580        init_test(cx);
11581
11582        let fs = FakeFs::new(cx.executor());
11583        let project = Project::test(fs, [], cx).await;
11584        let (workspace, cx) =
11585            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11586
11587        // Create a multibuffer-like item with two child focus handles,
11588        // simulating individual buffer editors within a multibuffer.
11589        let item = cx.new(|cx| {
11590            TestItem::new(cx)
11591                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11592                .with_child_focus_handles(2, cx)
11593        });
11594        workspace.update_in(cx, |workspace, window, cx| {
11595            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11596        });
11597
11598        // Set autosave to OnFocusChange and focus the first child handle,
11599        // simulating the user's cursor being inside one of the multibuffer's excerpts.
11600        item.update_in(cx, |item, window, cx| {
11601            SettingsStore::update_global(cx, |settings, cx| {
11602                settings.update_user_settings(cx, |settings| {
11603                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11604                })
11605            });
11606            item.is_dirty = true;
11607            window.focus(&item.child_focus_handles[0], cx);
11608        });
11609        cx.executor().run_until_parked();
11610        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11611
11612        // Moving focus from one child to another within the same item should
11613        // NOT trigger autosave — focus is still within the item's focus hierarchy.
11614        item.update_in(cx, |item, window, cx| {
11615            window.focus(&item.child_focus_handles[1], cx);
11616        });
11617        cx.executor().run_until_parked();
11618        item.read_with(cx, |item, _| {
11619            assert_eq!(
11620                item.save_count, 0,
11621                "Switching focus between children within the same item should not autosave"
11622            );
11623        });
11624
11625        // Blurring the item saves the file. This is the core regression scenario:
11626        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11627        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11628        // the leaf is always a child focus handle, so `on_blur` never detected
11629        // focus leaving the item.
11630        item.update_in(cx, |_, window, _| window.blur());
11631        cx.executor().run_until_parked();
11632        item.read_with(cx, |item, _| {
11633            assert_eq!(
11634                item.save_count, 1,
11635                "Blurring should trigger autosave when focus was on a child of the item"
11636            );
11637        });
11638
11639        // Deactivating the window should also trigger autosave when a child of
11640        // the multibuffer item currently owns focus.
11641        item.update_in(cx, |item, window, cx| {
11642            item.is_dirty = true;
11643            window.focus(&item.child_focus_handles[0], cx);
11644        });
11645        cx.executor().run_until_parked();
11646        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11647
11648        cx.deactivate_window();
11649        item.read_with(cx, |item, _| {
11650            assert_eq!(
11651                item.save_count, 2,
11652                "Deactivating window should trigger autosave when focus was on a child"
11653            );
11654        });
11655    }
11656
11657    #[gpui::test]
11658    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11659        init_test(cx);
11660
11661        let fs = FakeFs::new(cx.executor());
11662
11663        let project = Project::test(fs, [], cx).await;
11664        let (workspace, cx) =
11665            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11666
11667        let item = cx.new(|cx| {
11668            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11669        });
11670        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11671        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11672        let toolbar_notify_count = Rc::new(RefCell::new(0));
11673
11674        workspace.update_in(cx, |workspace, window, cx| {
11675            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11676            let toolbar_notification_count = toolbar_notify_count.clone();
11677            cx.observe_in(&toolbar, window, move |_, _, _, _| {
11678                *toolbar_notification_count.borrow_mut() += 1
11679            })
11680            .detach();
11681        });
11682
11683        pane.read_with(cx, |pane, _| {
11684            assert!(!pane.can_navigate_backward());
11685            assert!(!pane.can_navigate_forward());
11686        });
11687
11688        item.update_in(cx, |item, _, cx| {
11689            item.set_state("one".to_string(), cx);
11690        });
11691
11692        // Toolbar must be notified to re-render the navigation buttons
11693        assert_eq!(*toolbar_notify_count.borrow(), 1);
11694
11695        pane.read_with(cx, |pane, _| {
11696            assert!(pane.can_navigate_backward());
11697            assert!(!pane.can_navigate_forward());
11698        });
11699
11700        workspace
11701            .update_in(cx, |workspace, window, cx| {
11702                workspace.go_back(pane.downgrade(), window, cx)
11703            })
11704            .await
11705            .unwrap();
11706
11707        assert_eq!(*toolbar_notify_count.borrow(), 2);
11708        pane.read_with(cx, |pane, _| {
11709            assert!(!pane.can_navigate_backward());
11710            assert!(pane.can_navigate_forward());
11711        });
11712    }
11713
11714    /// Tests that the navigation history deduplicates entries for the same item.
11715    ///
11716    /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11717    /// the navigation history deduplicates by keeping only the most recent visit to each item,
11718    /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11719    /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11720    /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11721    ///
11722    /// This behavior prevents the navigation history from growing unnecessarily large and provides
11723    /// a better user experience by eliminating redundant navigation steps when jumping between files.
11724    #[gpui::test]
11725    async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11726        init_test(cx);
11727
11728        let fs = FakeFs::new(cx.executor());
11729        let project = Project::test(fs, [], cx).await;
11730        let (workspace, cx) =
11731            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11732
11733        let item_a = cx.new(|cx| {
11734            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11735        });
11736        let item_b = cx.new(|cx| {
11737            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11738        });
11739        let item_c = cx.new(|cx| {
11740            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11741        });
11742
11743        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11744
11745        workspace.update_in(cx, |workspace, window, cx| {
11746            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11747            workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11748            workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11749        });
11750
11751        workspace.update_in(cx, |workspace, window, cx| {
11752            workspace.activate_item(&item_a, false, false, window, cx);
11753        });
11754        cx.run_until_parked();
11755
11756        workspace.update_in(cx, |workspace, window, cx| {
11757            workspace.activate_item(&item_b, false, false, window, cx);
11758        });
11759        cx.run_until_parked();
11760
11761        workspace.update_in(cx, |workspace, window, cx| {
11762            workspace.activate_item(&item_a, false, false, window, cx);
11763        });
11764        cx.run_until_parked();
11765
11766        workspace.update_in(cx, |workspace, window, cx| {
11767            workspace.activate_item(&item_b, false, false, window, cx);
11768        });
11769        cx.run_until_parked();
11770
11771        workspace.update_in(cx, |workspace, window, cx| {
11772            workspace.activate_item(&item_a, false, false, window, cx);
11773        });
11774        cx.run_until_parked();
11775
11776        workspace.update_in(cx, |workspace, window, cx| {
11777            workspace.activate_item(&item_b, false, false, window, cx);
11778        });
11779        cx.run_until_parked();
11780
11781        workspace.update_in(cx, |workspace, window, cx| {
11782            workspace.activate_item(&item_c, false, false, window, cx);
11783        });
11784        cx.run_until_parked();
11785
11786        let backward_count = pane.read_with(cx, |pane, cx| {
11787            let mut count = 0;
11788            pane.nav_history().for_each_entry(cx, &mut |_, _| {
11789                count += 1;
11790            });
11791            count
11792        });
11793        assert!(
11794            backward_count <= 4,
11795            "Should have at most 4 entries, got {}",
11796            backward_count
11797        );
11798
11799        workspace
11800            .update_in(cx, |workspace, window, cx| {
11801                workspace.go_back(pane.downgrade(), window, cx)
11802            })
11803            .await
11804            .unwrap();
11805
11806        let active_item = workspace.read_with(cx, |workspace, cx| {
11807            workspace.active_item(cx).unwrap().item_id()
11808        });
11809        assert_eq!(
11810            active_item,
11811            item_b.entity_id(),
11812            "After first go_back, should be at item B"
11813        );
11814
11815        workspace
11816            .update_in(cx, |workspace, window, cx| {
11817                workspace.go_back(pane.downgrade(), window, cx)
11818            })
11819            .await
11820            .unwrap();
11821
11822        let active_item = workspace.read_with(cx, |workspace, cx| {
11823            workspace.active_item(cx).unwrap().item_id()
11824        });
11825        assert_eq!(
11826            active_item,
11827            item_a.entity_id(),
11828            "After second go_back, should be at item A"
11829        );
11830
11831        pane.read_with(cx, |pane, _| {
11832            assert!(pane.can_navigate_forward(), "Should be able to go forward");
11833        });
11834    }
11835
11836    #[gpui::test]
11837    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11838        init_test(cx);
11839        let fs = FakeFs::new(cx.executor());
11840        let project = Project::test(fs, [], cx).await;
11841        let (multi_workspace, cx) =
11842            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11843        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11844
11845        workspace.update_in(cx, |workspace, window, cx| {
11846            let first_item = cx.new(|cx| {
11847                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11848            });
11849            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11850            workspace.split_pane(
11851                workspace.active_pane().clone(),
11852                SplitDirection::Right,
11853                window,
11854                cx,
11855            );
11856            workspace.split_pane(
11857                workspace.active_pane().clone(),
11858                SplitDirection::Right,
11859                window,
11860                cx,
11861            );
11862        });
11863
11864        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11865            let panes = workspace.center.panes();
11866            assert!(panes.len() >= 2);
11867            (
11868                panes.first().expect("at least one pane").entity_id(),
11869                panes.last().expect("at least one pane").entity_id(),
11870            )
11871        });
11872
11873        workspace.update_in(cx, |workspace, window, cx| {
11874            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11875        });
11876        workspace.update(cx, |workspace, _| {
11877            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11878            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11879        });
11880
11881        cx.dispatch_action(ActivateLastPane);
11882
11883        workspace.update(cx, |workspace, _| {
11884            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11885        });
11886    }
11887
11888    #[gpui::test]
11889    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11890        init_test(cx);
11891        let fs = FakeFs::new(cx.executor());
11892
11893        let project = Project::test(fs, [], cx).await;
11894        let (workspace, cx) =
11895            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11896
11897        let panel = workspace.update_in(cx, |workspace, window, cx| {
11898            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11899            workspace.add_panel(panel.clone(), window, cx);
11900
11901            workspace
11902                .right_dock()
11903                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11904
11905            panel
11906        });
11907
11908        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11909        pane.update_in(cx, |pane, window, cx| {
11910            let item = cx.new(TestItem::new);
11911            pane.add_item(Box::new(item), true, true, None, window, cx);
11912        });
11913
11914        // Transfer focus from center to panel
11915        workspace.update_in(cx, |workspace, window, cx| {
11916            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11917        });
11918
11919        workspace.update_in(cx, |workspace, window, cx| {
11920            assert!(workspace.right_dock().read(cx).is_open());
11921            assert!(!panel.is_zoomed(window, cx));
11922            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11923        });
11924
11925        // Transfer focus from panel to center
11926        workspace.update_in(cx, |workspace, window, cx| {
11927            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11928        });
11929
11930        workspace.update_in(cx, |workspace, window, cx| {
11931            assert!(workspace.right_dock().read(cx).is_open());
11932            assert!(!panel.is_zoomed(window, cx));
11933            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11934            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11935        });
11936
11937        // Close the dock
11938        workspace.update_in(cx, |workspace, window, cx| {
11939            workspace.toggle_dock(DockPosition::Right, window, cx);
11940        });
11941
11942        workspace.update_in(cx, |workspace, window, cx| {
11943            assert!(!workspace.right_dock().read(cx).is_open());
11944            assert!(!panel.is_zoomed(window, cx));
11945            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11946            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11947        });
11948
11949        // Open the dock
11950        workspace.update_in(cx, |workspace, window, cx| {
11951            workspace.toggle_dock(DockPosition::Right, window, cx);
11952        });
11953
11954        workspace.update_in(cx, |workspace, window, cx| {
11955            assert!(workspace.right_dock().read(cx).is_open());
11956            assert!(!panel.is_zoomed(window, cx));
11957            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11958        });
11959
11960        // Focus and zoom panel
11961        panel.update_in(cx, |panel, window, cx| {
11962            cx.focus_self(window);
11963            panel.set_zoomed(true, window, cx)
11964        });
11965
11966        workspace.update_in(cx, |workspace, window, cx| {
11967            assert!(workspace.right_dock().read(cx).is_open());
11968            assert!(panel.is_zoomed(window, cx));
11969            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11970        });
11971
11972        // Transfer focus to the center closes the dock
11973        workspace.update_in(cx, |workspace, window, cx| {
11974            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11975        });
11976
11977        workspace.update_in(cx, |workspace, window, cx| {
11978            assert!(!workspace.right_dock().read(cx).is_open());
11979            assert!(panel.is_zoomed(window, cx));
11980            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11981        });
11982
11983        // Transferring focus back to the panel keeps it zoomed
11984        workspace.update_in(cx, |workspace, window, cx| {
11985            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11986        });
11987
11988        workspace.update_in(cx, |workspace, window, cx| {
11989            assert!(workspace.right_dock().read(cx).is_open());
11990            assert!(panel.is_zoomed(window, cx));
11991            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11992        });
11993
11994        // Close the dock while it is zoomed
11995        workspace.update_in(cx, |workspace, window, cx| {
11996            workspace.toggle_dock(DockPosition::Right, window, cx)
11997        });
11998
11999        workspace.update_in(cx, |workspace, window, cx| {
12000            assert!(!workspace.right_dock().read(cx).is_open());
12001            assert!(panel.is_zoomed(window, cx));
12002            assert!(workspace.zoomed.is_none());
12003            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12004        });
12005
12006        // Opening the dock, when it's zoomed, retains focus
12007        workspace.update_in(cx, |workspace, window, cx| {
12008            workspace.toggle_dock(DockPosition::Right, window, cx)
12009        });
12010
12011        workspace.update_in(cx, |workspace, window, cx| {
12012            assert!(workspace.right_dock().read(cx).is_open());
12013            assert!(panel.is_zoomed(window, cx));
12014            assert!(workspace.zoomed.is_some());
12015            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12016        });
12017
12018        // Unzoom and close the panel, zoom the active pane.
12019        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
12020        workspace.update_in(cx, |workspace, window, cx| {
12021            workspace.toggle_dock(DockPosition::Right, window, cx)
12022        });
12023        pane.update_in(cx, |pane, window, cx| {
12024            pane.toggle_zoom(&Default::default(), window, cx)
12025        });
12026
12027        // Opening a dock unzooms the pane.
12028        workspace.update_in(cx, |workspace, window, cx| {
12029            workspace.toggle_dock(DockPosition::Right, window, cx)
12030        });
12031        workspace.update_in(cx, |workspace, window, cx| {
12032            let pane = pane.read(cx);
12033            assert!(!pane.is_zoomed());
12034            assert!(!pane.focus_handle(cx).is_focused(window));
12035            assert!(workspace.right_dock().read(cx).is_open());
12036            assert!(workspace.zoomed.is_none());
12037        });
12038    }
12039
12040    #[gpui::test]
12041    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
12042        init_test(cx);
12043        let fs = FakeFs::new(cx.executor());
12044
12045        let project = Project::test(fs, [], cx).await;
12046        let (workspace, cx) =
12047            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12048
12049        let panel = workspace.update_in(cx, |workspace, window, cx| {
12050            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12051            workspace.add_panel(panel.clone(), window, cx);
12052            panel
12053        });
12054
12055        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12056        pane.update_in(cx, |pane, window, cx| {
12057            let item = cx.new(TestItem::new);
12058            pane.add_item(Box::new(item), true, true, None, window, cx);
12059        });
12060
12061        // Enable close_panel_on_toggle
12062        cx.update_global(|store: &mut SettingsStore, cx| {
12063            store.update_user_settings(cx, |settings| {
12064                settings.workspace.close_panel_on_toggle = Some(true);
12065            });
12066        });
12067
12068        // Panel starts closed. Toggling should open and focus it.
12069        workspace.update_in(cx, |workspace, window, cx| {
12070            assert!(!workspace.right_dock().read(cx).is_open());
12071            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12072        });
12073
12074        workspace.update_in(cx, |workspace, window, cx| {
12075            assert!(
12076                workspace.right_dock().read(cx).is_open(),
12077                "Dock should be open after toggling from center"
12078            );
12079            assert!(
12080                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12081                "Panel should be focused after toggling from center"
12082            );
12083        });
12084
12085        // Panel is open and focused. Toggling should close the panel and
12086        // return focus to the center.
12087        workspace.update_in(cx, |workspace, window, cx| {
12088            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12089        });
12090
12091        workspace.update_in(cx, |workspace, window, cx| {
12092            assert!(
12093                !workspace.right_dock().read(cx).is_open(),
12094                "Dock should be closed after toggling from focused panel"
12095            );
12096            assert!(
12097                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12098                "Panel should not be focused after toggling from focused panel"
12099            );
12100        });
12101
12102        // Open the dock and focus something else so the panel is open but not
12103        // focused. Toggling should focus the panel (not close it).
12104        workspace.update_in(cx, |workspace, window, cx| {
12105            workspace
12106                .right_dock()
12107                .update(cx, |dock, cx| dock.set_open(true, window, cx));
12108            window.focus(&pane.read(cx).focus_handle(cx), cx);
12109        });
12110
12111        workspace.update_in(cx, |workspace, window, cx| {
12112            assert!(workspace.right_dock().read(cx).is_open());
12113            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12114            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12115        });
12116
12117        workspace.update_in(cx, |workspace, window, cx| {
12118            assert!(
12119                workspace.right_dock().read(cx).is_open(),
12120                "Dock should remain open when toggling focuses an open-but-unfocused panel"
12121            );
12122            assert!(
12123                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12124                "Panel should be focused after toggling an open-but-unfocused panel"
12125            );
12126        });
12127
12128        // Now disable the setting and verify the original behavior: toggling
12129        // from a focused panel moves focus to center but leaves the dock open.
12130        cx.update_global(|store: &mut SettingsStore, cx| {
12131            store.update_user_settings(cx, |settings| {
12132                settings.workspace.close_panel_on_toggle = Some(false);
12133            });
12134        });
12135
12136        workspace.update_in(cx, |workspace, window, cx| {
12137            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12138        });
12139
12140        workspace.update_in(cx, |workspace, window, cx| {
12141            assert!(
12142                workspace.right_dock().read(cx).is_open(),
12143                "Dock should remain open when setting is disabled"
12144            );
12145            assert!(
12146                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12147                "Panel should not be focused after toggling with setting disabled"
12148            );
12149        });
12150    }
12151
12152    #[gpui::test]
12153    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
12154        init_test(cx);
12155        let fs = FakeFs::new(cx.executor());
12156
12157        let project = Project::test(fs, [], cx).await;
12158        let (workspace, cx) =
12159            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12160
12161        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
12162            workspace.active_pane().clone()
12163        });
12164
12165        // Add an item to the pane so it can be zoomed
12166        workspace.update_in(cx, |workspace, window, cx| {
12167            let item = cx.new(TestItem::new);
12168            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
12169        });
12170
12171        // Initially not zoomed
12172        workspace.update_in(cx, |workspace, _window, cx| {
12173            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
12174            assert!(
12175                workspace.zoomed.is_none(),
12176                "Workspace should track no zoomed pane"
12177            );
12178            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
12179        });
12180
12181        // Zoom In
12182        pane.update_in(cx, |pane, window, cx| {
12183            pane.zoom_in(&crate::ZoomIn, window, cx);
12184        });
12185
12186        workspace.update_in(cx, |workspace, window, cx| {
12187            assert!(
12188                pane.read(cx).is_zoomed(),
12189                "Pane should be zoomed after ZoomIn"
12190            );
12191            assert!(
12192                workspace.zoomed.is_some(),
12193                "Workspace should track the zoomed pane"
12194            );
12195            assert!(
12196                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
12197                "ZoomIn should focus the pane"
12198            );
12199        });
12200
12201        // Zoom In again is a no-op
12202        pane.update_in(cx, |pane, window, cx| {
12203            pane.zoom_in(&crate::ZoomIn, window, cx);
12204        });
12205
12206        workspace.update_in(cx, |workspace, window, cx| {
12207            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
12208            assert!(
12209                workspace.zoomed.is_some(),
12210                "Workspace still tracks zoomed pane"
12211            );
12212            assert!(
12213                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
12214                "Pane remains focused after repeated ZoomIn"
12215            );
12216        });
12217
12218        // Zoom Out
12219        pane.update_in(cx, |pane, window, cx| {
12220            pane.zoom_out(&crate::ZoomOut, window, cx);
12221        });
12222
12223        workspace.update_in(cx, |workspace, _window, cx| {
12224            assert!(
12225                !pane.read(cx).is_zoomed(),
12226                "Pane should unzoom after ZoomOut"
12227            );
12228            assert!(
12229                workspace.zoomed.is_none(),
12230                "Workspace clears zoom tracking after ZoomOut"
12231            );
12232        });
12233
12234        // Zoom Out again is a no-op
12235        pane.update_in(cx, |pane, window, cx| {
12236            pane.zoom_out(&crate::ZoomOut, window, cx);
12237        });
12238
12239        workspace.update_in(cx, |workspace, _window, cx| {
12240            assert!(
12241                !pane.read(cx).is_zoomed(),
12242                "Second ZoomOut keeps pane unzoomed"
12243            );
12244            assert!(
12245                workspace.zoomed.is_none(),
12246                "Workspace remains without zoomed pane"
12247            );
12248        });
12249    }
12250
12251    #[gpui::test]
12252    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
12253        init_test(cx);
12254        let fs = FakeFs::new(cx.executor());
12255
12256        let project = Project::test(fs, [], cx).await;
12257        let (workspace, cx) =
12258            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12259        workspace.update_in(cx, |workspace, window, cx| {
12260            // Open two docks
12261            let left_dock = workspace.dock_at_position(DockPosition::Left);
12262            let right_dock = workspace.dock_at_position(DockPosition::Right);
12263
12264            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12265            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12266
12267            assert!(left_dock.read(cx).is_open());
12268            assert!(right_dock.read(cx).is_open());
12269        });
12270
12271        workspace.update_in(cx, |workspace, window, cx| {
12272            // Toggle all docks - should close both
12273            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12274
12275            let left_dock = workspace.dock_at_position(DockPosition::Left);
12276            let right_dock = workspace.dock_at_position(DockPosition::Right);
12277            assert!(!left_dock.read(cx).is_open());
12278            assert!(!right_dock.read(cx).is_open());
12279        });
12280
12281        workspace.update_in(cx, |workspace, window, cx| {
12282            // Toggle again - should reopen both
12283            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12284
12285            let left_dock = workspace.dock_at_position(DockPosition::Left);
12286            let right_dock = workspace.dock_at_position(DockPosition::Right);
12287            assert!(left_dock.read(cx).is_open());
12288            assert!(right_dock.read(cx).is_open());
12289        });
12290    }
12291
12292    #[gpui::test]
12293    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
12294        init_test(cx);
12295        let fs = FakeFs::new(cx.executor());
12296
12297        let project = Project::test(fs, [], cx).await;
12298        let (workspace, cx) =
12299            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12300        workspace.update_in(cx, |workspace, window, cx| {
12301            // Open two docks
12302            let left_dock = workspace.dock_at_position(DockPosition::Left);
12303            let right_dock = workspace.dock_at_position(DockPosition::Right);
12304
12305            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12306            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12307
12308            assert!(left_dock.read(cx).is_open());
12309            assert!(right_dock.read(cx).is_open());
12310        });
12311
12312        workspace.update_in(cx, |workspace, window, cx| {
12313            // Close them manually
12314            workspace.toggle_dock(DockPosition::Left, window, cx);
12315            workspace.toggle_dock(DockPosition::Right, window, cx);
12316
12317            let left_dock = workspace.dock_at_position(DockPosition::Left);
12318            let right_dock = workspace.dock_at_position(DockPosition::Right);
12319            assert!(!left_dock.read(cx).is_open());
12320            assert!(!right_dock.read(cx).is_open());
12321        });
12322
12323        workspace.update_in(cx, |workspace, window, cx| {
12324            // Toggle all docks - only last closed (right dock) should reopen
12325            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12326
12327            let left_dock = workspace.dock_at_position(DockPosition::Left);
12328            let right_dock = workspace.dock_at_position(DockPosition::Right);
12329            assert!(!left_dock.read(cx).is_open());
12330            assert!(right_dock.read(cx).is_open());
12331        });
12332    }
12333
12334    #[gpui::test]
12335    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
12336        init_test(cx);
12337        let fs = FakeFs::new(cx.executor());
12338        let project = Project::test(fs, [], cx).await;
12339        let (multi_workspace, cx) =
12340            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12341        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12342
12343        // Open two docks (left and right) with one panel each
12344        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12345            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12346            workspace.add_panel(left_panel.clone(), window, cx);
12347
12348            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12349            workspace.add_panel(right_panel.clone(), window, cx);
12350
12351            workspace.toggle_dock(DockPosition::Left, window, cx);
12352            workspace.toggle_dock(DockPosition::Right, window, cx);
12353
12354            // Verify initial state
12355            assert!(
12356                workspace.left_dock().read(cx).is_open(),
12357                "Left dock should be open"
12358            );
12359            assert_eq!(
12360                workspace
12361                    .left_dock()
12362                    .read(cx)
12363                    .visible_panel()
12364                    .unwrap()
12365                    .panel_id(),
12366                left_panel.panel_id(),
12367                "Left panel should be visible in left dock"
12368            );
12369            assert!(
12370                workspace.right_dock().read(cx).is_open(),
12371                "Right dock should be open"
12372            );
12373            assert_eq!(
12374                workspace
12375                    .right_dock()
12376                    .read(cx)
12377                    .visible_panel()
12378                    .unwrap()
12379                    .panel_id(),
12380                right_panel.panel_id(),
12381                "Right panel should be visible in right dock"
12382            );
12383            assert!(
12384                !workspace.bottom_dock().read(cx).is_open(),
12385                "Bottom dock should be closed"
12386            );
12387
12388            (left_panel, right_panel)
12389        });
12390
12391        // Focus the left panel and move it to the next position (bottom dock)
12392        workspace.update_in(cx, |workspace, window, cx| {
12393            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12394            assert!(
12395                left_panel.read(cx).focus_handle(cx).is_focused(window),
12396                "Left panel should be focused"
12397            );
12398        });
12399
12400        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12401
12402        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12403        workspace.update(cx, |workspace, cx| {
12404            assert!(
12405                !workspace.left_dock().read(cx).is_open(),
12406                "Left dock should be closed"
12407            );
12408            assert!(
12409                workspace.bottom_dock().read(cx).is_open(),
12410                "Bottom dock should now be open"
12411            );
12412            assert_eq!(
12413                left_panel.read(cx).position,
12414                DockPosition::Bottom,
12415                "Left panel should now be in the bottom dock"
12416            );
12417            assert_eq!(
12418                workspace
12419                    .bottom_dock()
12420                    .read(cx)
12421                    .visible_panel()
12422                    .unwrap()
12423                    .panel_id(),
12424                left_panel.panel_id(),
12425                "Left panel should be the visible panel in the bottom dock"
12426            );
12427        });
12428
12429        // Toggle all docks off
12430        workspace.update_in(cx, |workspace, window, cx| {
12431            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12432            assert!(
12433                !workspace.left_dock().read(cx).is_open(),
12434                "Left dock should be closed"
12435            );
12436            assert!(
12437                !workspace.right_dock().read(cx).is_open(),
12438                "Right dock should be closed"
12439            );
12440            assert!(
12441                !workspace.bottom_dock().read(cx).is_open(),
12442                "Bottom dock should be closed"
12443            );
12444        });
12445
12446        // Toggle all docks back on and verify positions are restored
12447        workspace.update_in(cx, |workspace, window, cx| {
12448            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12449            assert!(
12450                !workspace.left_dock().read(cx).is_open(),
12451                "Left dock should remain closed"
12452            );
12453            assert!(
12454                workspace.right_dock().read(cx).is_open(),
12455                "Right dock should remain open"
12456            );
12457            assert!(
12458                workspace.bottom_dock().read(cx).is_open(),
12459                "Bottom dock should remain open"
12460            );
12461            assert_eq!(
12462                left_panel.read(cx).position,
12463                DockPosition::Bottom,
12464                "Left panel should remain in the bottom dock"
12465            );
12466            assert_eq!(
12467                right_panel.read(cx).position,
12468                DockPosition::Right,
12469                "Right panel should remain in the right dock"
12470            );
12471            assert_eq!(
12472                workspace
12473                    .bottom_dock()
12474                    .read(cx)
12475                    .visible_panel()
12476                    .unwrap()
12477                    .panel_id(),
12478                left_panel.panel_id(),
12479                "Left panel should be the visible panel in the right dock"
12480            );
12481        });
12482    }
12483
12484    #[gpui::test]
12485    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12486        init_test(cx);
12487
12488        let fs = FakeFs::new(cx.executor());
12489
12490        let project = Project::test(fs, None, cx).await;
12491        let (workspace, cx) =
12492            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12493
12494        // Let's arrange the panes like this:
12495        //
12496        // +-----------------------+
12497        // |         top           |
12498        // +------+--------+-------+
12499        // | left | center | right |
12500        // +------+--------+-------+
12501        // |        bottom         |
12502        // +-----------------------+
12503
12504        let top_item = cx.new(|cx| {
12505            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12506        });
12507        let bottom_item = cx.new(|cx| {
12508            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12509        });
12510        let left_item = cx.new(|cx| {
12511            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12512        });
12513        let right_item = cx.new(|cx| {
12514            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12515        });
12516        let center_item = cx.new(|cx| {
12517            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12518        });
12519
12520        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12521            let top_pane_id = workspace.active_pane().entity_id();
12522            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12523            workspace.split_pane(
12524                workspace.active_pane().clone(),
12525                SplitDirection::Down,
12526                window,
12527                cx,
12528            );
12529            top_pane_id
12530        });
12531        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12532            let bottom_pane_id = workspace.active_pane().entity_id();
12533            workspace.add_item_to_active_pane(
12534                Box::new(bottom_item.clone()),
12535                None,
12536                false,
12537                window,
12538                cx,
12539            );
12540            workspace.split_pane(
12541                workspace.active_pane().clone(),
12542                SplitDirection::Up,
12543                window,
12544                cx,
12545            );
12546            bottom_pane_id
12547        });
12548        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12549            let left_pane_id = workspace.active_pane().entity_id();
12550            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12551            workspace.split_pane(
12552                workspace.active_pane().clone(),
12553                SplitDirection::Right,
12554                window,
12555                cx,
12556            );
12557            left_pane_id
12558        });
12559        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12560            let right_pane_id = workspace.active_pane().entity_id();
12561            workspace.add_item_to_active_pane(
12562                Box::new(right_item.clone()),
12563                None,
12564                false,
12565                window,
12566                cx,
12567            );
12568            workspace.split_pane(
12569                workspace.active_pane().clone(),
12570                SplitDirection::Left,
12571                window,
12572                cx,
12573            );
12574            right_pane_id
12575        });
12576        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12577            let center_pane_id = workspace.active_pane().entity_id();
12578            workspace.add_item_to_active_pane(
12579                Box::new(center_item.clone()),
12580                None,
12581                false,
12582                window,
12583                cx,
12584            );
12585            center_pane_id
12586        });
12587        cx.executor().run_until_parked();
12588
12589        workspace.update_in(cx, |workspace, window, cx| {
12590            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12591
12592            // Join into next from center pane into right
12593            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12594        });
12595
12596        workspace.update_in(cx, |workspace, window, cx| {
12597            let active_pane = workspace.active_pane();
12598            assert_eq!(right_pane_id, active_pane.entity_id());
12599            assert_eq!(2, active_pane.read(cx).items_len());
12600            let item_ids_in_pane =
12601                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12602            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12603            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12604
12605            // Join into next from right pane into bottom
12606            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12607        });
12608
12609        workspace.update_in(cx, |workspace, window, cx| {
12610            let active_pane = workspace.active_pane();
12611            assert_eq!(bottom_pane_id, active_pane.entity_id());
12612            assert_eq!(3, active_pane.read(cx).items_len());
12613            let item_ids_in_pane =
12614                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12615            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12616            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12617            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12618
12619            // Join into next from bottom pane into left
12620            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12621        });
12622
12623        workspace.update_in(cx, |workspace, window, cx| {
12624            let active_pane = workspace.active_pane();
12625            assert_eq!(left_pane_id, active_pane.entity_id());
12626            assert_eq!(4, active_pane.read(cx).items_len());
12627            let item_ids_in_pane =
12628                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12629            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12630            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12631            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12632            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12633
12634            // Join into next from left pane into top
12635            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12636        });
12637
12638        workspace.update_in(cx, |workspace, window, cx| {
12639            let active_pane = workspace.active_pane();
12640            assert_eq!(top_pane_id, active_pane.entity_id());
12641            assert_eq!(5, active_pane.read(cx).items_len());
12642            let item_ids_in_pane =
12643                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12644            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12645            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12646            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12647            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12648            assert!(item_ids_in_pane.contains(&top_item.item_id()));
12649
12650            // Single pane left: no-op
12651            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12652        });
12653
12654        workspace.update(cx, |workspace, _cx| {
12655            let active_pane = workspace.active_pane();
12656            assert_eq!(top_pane_id, active_pane.entity_id());
12657        });
12658    }
12659
12660    fn add_an_item_to_active_pane(
12661        cx: &mut VisualTestContext,
12662        workspace: &Entity<Workspace>,
12663        item_id: u64,
12664    ) -> Entity<TestItem> {
12665        let item = cx.new(|cx| {
12666            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12667                item_id,
12668                "item{item_id}.txt",
12669                cx,
12670            )])
12671        });
12672        workspace.update_in(cx, |workspace, window, cx| {
12673            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12674        });
12675        item
12676    }
12677
12678    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12679        workspace.update_in(cx, |workspace, window, cx| {
12680            workspace.split_pane(
12681                workspace.active_pane().clone(),
12682                SplitDirection::Right,
12683                window,
12684                cx,
12685            )
12686        })
12687    }
12688
12689    #[gpui::test]
12690    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12691        init_test(cx);
12692        let fs = FakeFs::new(cx.executor());
12693        let project = Project::test(fs, None, cx).await;
12694        let (workspace, cx) =
12695            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12696
12697        add_an_item_to_active_pane(cx, &workspace, 1);
12698        split_pane(cx, &workspace);
12699        add_an_item_to_active_pane(cx, &workspace, 2);
12700        split_pane(cx, &workspace); // empty pane
12701        split_pane(cx, &workspace);
12702        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12703
12704        cx.executor().run_until_parked();
12705
12706        workspace.update(cx, |workspace, cx| {
12707            let num_panes = workspace.panes().len();
12708            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12709            let active_item = workspace
12710                .active_pane()
12711                .read(cx)
12712                .active_item()
12713                .expect("item is in focus");
12714
12715            assert_eq!(num_panes, 4);
12716            assert_eq!(num_items_in_current_pane, 1);
12717            assert_eq!(active_item.item_id(), last_item.item_id());
12718        });
12719
12720        workspace.update_in(cx, |workspace, window, cx| {
12721            workspace.join_all_panes(window, cx);
12722        });
12723
12724        workspace.update(cx, |workspace, cx| {
12725            let num_panes = workspace.panes().len();
12726            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12727            let active_item = workspace
12728                .active_pane()
12729                .read(cx)
12730                .active_item()
12731                .expect("item is in focus");
12732
12733            assert_eq!(num_panes, 1);
12734            assert_eq!(num_items_in_current_pane, 3);
12735            assert_eq!(active_item.item_id(), last_item.item_id());
12736        });
12737    }
12738
12739    #[gpui::test]
12740    async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12741        init_test(cx);
12742        let fs = FakeFs::new(cx.executor());
12743
12744        let project = Project::test(fs, [], cx).await;
12745        let (multi_workspace, cx) =
12746            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12747        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12748
12749        workspace.update(cx, |workspace, _cx| {
12750            workspace.bounds.size.width = px(800.);
12751        });
12752
12753        workspace.update_in(cx, |workspace, window, cx| {
12754            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12755            workspace.add_panel(panel, window, cx);
12756            workspace.toggle_dock(DockPosition::Right, window, cx);
12757        });
12758
12759        let (panel, resized_width, ratio_basis_width) =
12760            workspace.update_in(cx, |workspace, window, cx| {
12761                let item = cx.new(|cx| {
12762                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12763                });
12764                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12765
12766                let dock = workspace.right_dock().read(cx);
12767                let workspace_width = workspace.bounds.size.width;
12768                let initial_width = workspace
12769                    .dock_size(&dock, window, cx)
12770                    .expect("flexible dock should have an initial width");
12771
12772                assert_eq!(initial_width, workspace_width / 2.);
12773
12774                workspace.resize_right_dock(px(300.), window, cx);
12775
12776                let dock = workspace.right_dock().read(cx);
12777                let resized_width = workspace
12778                    .dock_size(&dock, window, cx)
12779                    .expect("flexible dock should keep its resized width");
12780
12781                assert_eq!(resized_width, px(300.));
12782
12783                let panel = workspace
12784                    .right_dock()
12785                    .read(cx)
12786                    .visible_panel()
12787                    .expect("flexible dock should have a visible panel")
12788                    .panel_id();
12789
12790                (panel, resized_width, workspace_width)
12791            });
12792
12793        workspace.update_in(cx, |workspace, window, cx| {
12794            workspace.toggle_dock(DockPosition::Right, window, cx);
12795            workspace.toggle_dock(DockPosition::Right, window, cx);
12796
12797            let dock = workspace.right_dock().read(cx);
12798            let reopened_width = workspace
12799                .dock_size(&dock, window, cx)
12800                .expect("flexible dock should restore when reopened");
12801
12802            assert_eq!(reopened_width, resized_width);
12803
12804            let right_dock = workspace.right_dock().read(cx);
12805            let flexible_panel = right_dock
12806                .visible_panel()
12807                .expect("flexible dock should still have a visible panel");
12808            assert_eq!(flexible_panel.panel_id(), panel);
12809            assert_eq!(
12810                right_dock
12811                    .stored_panel_size_state(flexible_panel.as_ref())
12812                    .and_then(|size_state| size_state.flex),
12813                Some(
12814                    resized_width.to_f64() as f32
12815                        / (workspace.bounds.size.width - resized_width).to_f64() as f32
12816                )
12817            );
12818        });
12819
12820        workspace.update_in(cx, |workspace, window, cx| {
12821            workspace.split_pane(
12822                workspace.active_pane().clone(),
12823                SplitDirection::Right,
12824                window,
12825                cx,
12826            );
12827
12828            let dock = workspace.right_dock().read(cx);
12829            let split_width = workspace
12830                .dock_size(&dock, window, cx)
12831                .expect("flexible dock should keep its user-resized proportion");
12832
12833            assert_eq!(split_width, px(300.));
12834
12835            workspace.bounds.size.width = px(1600.);
12836
12837            let dock = workspace.right_dock().read(cx);
12838            let resized_window_width = workspace
12839                .dock_size(&dock, window, cx)
12840                .expect("flexible dock should preserve proportional size on window resize");
12841
12842            assert_eq!(
12843                resized_window_width,
12844                workspace.bounds.size.width
12845                    * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12846            );
12847        });
12848    }
12849
12850    #[gpui::test]
12851    async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12852        init_test(cx);
12853        let fs = FakeFs::new(cx.executor());
12854
12855        // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12856        {
12857            let project = Project::test(fs.clone(), [], cx).await;
12858            let (multi_workspace, cx) =
12859                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12860            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12861
12862            workspace.update(cx, |workspace, _cx| {
12863                workspace.set_random_database_id();
12864                workspace.bounds.size.width = px(800.);
12865            });
12866
12867            let panel = workspace.update_in(cx, |workspace, window, cx| {
12868                let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12869                workspace.add_panel(panel.clone(), window, cx);
12870                workspace.toggle_dock(DockPosition::Left, window, cx);
12871                panel
12872            });
12873
12874            workspace.update_in(cx, |workspace, window, cx| {
12875                workspace.resize_left_dock(px(350.), window, cx);
12876            });
12877
12878            cx.run_until_parked();
12879
12880            let persisted = workspace.read_with(cx, |workspace, cx| {
12881                workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12882            });
12883            assert_eq!(
12884                persisted.and_then(|s| s.size),
12885                Some(px(350.)),
12886                "fixed-width panel size should be persisted to KVP"
12887            );
12888
12889            // Remove the panel and re-add a fresh instance with the same key.
12890            // The new instance should have its size state restored from KVP.
12891            workspace.update_in(cx, |workspace, window, cx| {
12892                workspace.remove_panel(&panel, window, cx);
12893            });
12894
12895            workspace.update_in(cx, |workspace, window, cx| {
12896                let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12897                workspace.add_panel(new_panel, window, cx);
12898
12899                let left_dock = workspace.left_dock().read(cx);
12900                let size_state = left_dock
12901                    .panel::<TestPanel>()
12902                    .and_then(|p| left_dock.stored_panel_size_state(&p));
12903                assert_eq!(
12904                    size_state.and_then(|s| s.size),
12905                    Some(px(350.)),
12906                    "re-added fixed-width panel should restore persisted size from KVP"
12907                );
12908            });
12909        }
12910
12911        // Flexible panel: both pixel size and ratio are persisted and restored.
12912        {
12913            let project = Project::test(fs.clone(), [], cx).await;
12914            let (multi_workspace, cx) =
12915                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12916            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12917
12918            workspace.update(cx, |workspace, _cx| {
12919                workspace.set_random_database_id();
12920                workspace.bounds.size.width = px(800.);
12921            });
12922
12923            let panel = workspace.update_in(cx, |workspace, window, cx| {
12924                let item = cx.new(|cx| {
12925                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12926                });
12927                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12928
12929                let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12930                workspace.add_panel(panel.clone(), window, cx);
12931                workspace.toggle_dock(DockPosition::Right, window, cx);
12932                panel
12933            });
12934
12935            workspace.update_in(cx, |workspace, window, cx| {
12936                workspace.resize_right_dock(px(300.), window, cx);
12937            });
12938
12939            cx.run_until_parked();
12940
12941            let persisted = workspace
12942                .read_with(cx, |workspace, cx| {
12943                    workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12944                })
12945                .expect("flexible panel state should be persisted to KVP");
12946            assert_eq!(
12947                persisted.size, None,
12948                "flexible panel should not persist a redundant pixel size"
12949            );
12950            let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12951
12952            // Remove the panel and re-add: both size and ratio should be restored.
12953            workspace.update_in(cx, |workspace, window, cx| {
12954                workspace.remove_panel(&panel, window, cx);
12955            });
12956
12957            workspace.update_in(cx, |workspace, window, cx| {
12958                let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12959                workspace.add_panel(new_panel, window, cx);
12960
12961                let right_dock = workspace.right_dock().read(cx);
12962                let size_state = right_dock
12963                    .panel::<TestPanel>()
12964                    .and_then(|p| right_dock.stored_panel_size_state(&p))
12965                    .expect("re-added flexible panel should have restored size state from KVP");
12966                assert_eq!(
12967                    size_state.size, None,
12968                    "re-added flexible panel should not have a persisted pixel size"
12969                );
12970                assert_eq!(
12971                    size_state.flex,
12972                    Some(original_ratio),
12973                    "re-added flexible panel should restore persisted flex"
12974                );
12975            });
12976        }
12977    }
12978
12979    #[gpui::test]
12980    async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12981        init_test(cx);
12982        let fs = FakeFs::new(cx.executor());
12983
12984        let project = Project::test(fs, [], cx).await;
12985        let (multi_workspace, cx) =
12986            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12987        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12988
12989        workspace.update(cx, |workspace, _cx| {
12990            workspace.bounds.size.width = px(900.);
12991        });
12992
12993        // Step 1: Add a tab to the center pane then open a flexible panel in the left
12994        // dock. With one full-width center pane the default ratio is 0.5, so the panel
12995        // and the center pane each take half the workspace width.
12996        workspace.update_in(cx, |workspace, window, cx| {
12997            let item = cx.new(|cx| {
12998                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12999            });
13000            workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
13001
13002            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
13003            workspace.add_panel(panel, window, cx);
13004            workspace.toggle_dock(DockPosition::Left, window, cx);
13005
13006            let left_dock = workspace.left_dock().read(cx);
13007            let left_width = workspace
13008                .dock_size(&left_dock, window, cx)
13009                .expect("left dock should have an active panel");
13010
13011            assert_eq!(
13012                left_width,
13013                workspace.bounds.size.width / 2.,
13014                "flexible left panel should split evenly with the center pane"
13015            );
13016        });
13017
13018        // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
13019        // change horizontal width fractions, so the flexible panel stays at the same
13020        // width as each half of the split.
13021        workspace.update_in(cx, |workspace, window, cx| {
13022            workspace.split_pane(
13023                workspace.active_pane().clone(),
13024                SplitDirection::Down,
13025                window,
13026                cx,
13027            );
13028
13029            let left_dock = workspace.left_dock().read(cx);
13030            let left_width = workspace
13031                .dock_size(&left_dock, window, cx)
13032                .expect("left dock should still have an active panel after vertical split");
13033
13034            assert_eq!(
13035                left_width,
13036                workspace.bounds.size.width / 2.,
13037                "flexible left panel width should match each vertically-split pane"
13038            );
13039        });
13040
13041        // Step 3: Open a fixed-width panel in the right dock. The right dock's default
13042        // size reduces the available width, so the flexible left panel and the center
13043        // panes all shrink proportionally to accommodate it.
13044        workspace.update_in(cx, |workspace, window, cx| {
13045            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
13046            workspace.add_panel(panel, window, cx);
13047            workspace.toggle_dock(DockPosition::Right, window, cx);
13048
13049            let right_dock = workspace.right_dock().read(cx);
13050            let right_width = workspace
13051                .dock_size(&right_dock, window, cx)
13052                .expect("right dock should have an active panel");
13053
13054            let left_dock = workspace.left_dock().read(cx);
13055            let left_width = workspace
13056                .dock_size(&left_dock, window, cx)
13057                .expect("left dock should still have an active panel");
13058
13059            let available_width = workspace.bounds.size.width - right_width;
13060            assert_eq!(
13061                left_width,
13062                available_width / 2.,
13063                "flexible left panel should shrink proportionally as the right dock takes space"
13064            );
13065        });
13066
13067        // Step 4: Toggle the right dock's panel to flexible. Now both docks use
13068        // flex sizing and the workspace width is divided among left-flex, center
13069        // (implicit flex 1.0), and right-flex.
13070        workspace.update_in(cx, |workspace, window, cx| {
13071            let right_dock = workspace.right_dock().clone();
13072            let right_panel = right_dock
13073                .read(cx)
13074                .visible_panel()
13075                .expect("right dock should have a visible panel")
13076                .clone();
13077            workspace.toggle_dock_panel_flexible_size(
13078                &right_dock,
13079                right_panel.as_ref(),
13080                window,
13081                cx,
13082            );
13083
13084            let right_dock = right_dock.read(cx);
13085            let right_panel = right_dock
13086                .visible_panel()
13087                .expect("right dock should still have a visible panel");
13088            assert!(
13089                right_panel.has_flexible_size(window, cx),
13090                "right panel should now be flexible"
13091            );
13092
13093            let right_size_state = right_dock
13094                .stored_panel_size_state(right_panel.as_ref())
13095                .expect("right panel should have a stored size state after toggling");
13096            let right_flex = right_size_state
13097                .flex
13098                .expect("right panel should have a flex value after toggling");
13099
13100            let left_dock = workspace.left_dock().read(cx);
13101            let left_width = workspace
13102                .dock_size(&left_dock, window, cx)
13103                .expect("left dock should still have an active panel");
13104            let right_width = workspace
13105                .dock_size(&right_dock, window, cx)
13106                .expect("right dock should still have an active panel");
13107
13108            let left_flex = workspace
13109                .default_dock_flex(DockPosition::Left)
13110                .expect("left dock should have a default flex");
13111
13112            let total_flex = left_flex + 1.0 + right_flex;
13113            let expected_left = left_flex / total_flex * workspace.bounds.size.width;
13114            let expected_right = right_flex / total_flex * workspace.bounds.size.width;
13115            assert_eq!(
13116                left_width, expected_left,
13117                "flexible left panel should share workspace width via flex ratios"
13118            );
13119            assert_eq!(
13120                right_width, expected_right,
13121                "flexible right panel should share workspace width via flex ratios"
13122            );
13123        });
13124    }
13125
13126    struct TestModal(FocusHandle);
13127
13128    impl TestModal {
13129        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
13130            Self(cx.focus_handle())
13131        }
13132    }
13133
13134    impl EventEmitter<DismissEvent> for TestModal {}
13135
13136    impl Focusable for TestModal {
13137        fn focus_handle(&self, _cx: &App) -> FocusHandle {
13138            self.0.clone()
13139        }
13140    }
13141
13142    impl ModalView for TestModal {}
13143
13144    impl Render for TestModal {
13145        fn render(
13146            &mut self,
13147            _window: &mut Window,
13148            _cx: &mut Context<TestModal>,
13149        ) -> impl IntoElement {
13150            div().track_focus(&self.0)
13151        }
13152    }
13153
13154    #[gpui::test]
13155    async fn test_panels(cx: &mut gpui::TestAppContext) {
13156        init_test(cx);
13157        let fs = FakeFs::new(cx.executor());
13158
13159        let project = Project::test(fs, [], cx).await;
13160        let (multi_workspace, cx) =
13161            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13162        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13163
13164        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
13165            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
13166            workspace.add_panel(panel_1.clone(), window, cx);
13167            workspace.toggle_dock(DockPosition::Left, window, cx);
13168            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
13169            workspace.add_panel(panel_2.clone(), window, cx);
13170            workspace.toggle_dock(DockPosition::Right, window, cx);
13171
13172            let left_dock = workspace.left_dock();
13173            assert_eq!(
13174                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13175                panel_1.panel_id()
13176            );
13177            assert_eq!(
13178                workspace.dock_size(&left_dock.read(cx), window, cx),
13179                Some(px(300.))
13180            );
13181
13182            workspace.resize_left_dock(px(1337.), window, cx);
13183            assert_eq!(
13184                workspace
13185                    .right_dock()
13186                    .read(cx)
13187                    .visible_panel()
13188                    .unwrap()
13189                    .panel_id(),
13190                panel_2.panel_id(),
13191            );
13192
13193            (panel_1, panel_2)
13194        });
13195
13196        // Move panel_1 to the right
13197        panel_1.update_in(cx, |panel_1, window, cx| {
13198            panel_1.set_position(DockPosition::Right, window, cx)
13199        });
13200
13201        workspace.update_in(cx, |workspace, window, cx| {
13202            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
13203            // Since it was the only panel on the left, the left dock should now be closed.
13204            assert!(!workspace.left_dock().read(cx).is_open());
13205            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
13206            let right_dock = workspace.right_dock();
13207            assert_eq!(
13208                right_dock.read(cx).visible_panel().unwrap().panel_id(),
13209                panel_1.panel_id()
13210            );
13211            assert_eq!(
13212                right_dock
13213                    .read(cx)
13214                    .active_panel_size()
13215                    .unwrap()
13216                    .size
13217                    .unwrap(),
13218                px(1337.)
13219            );
13220
13221            // Now we move panel_2 to the left
13222            panel_2.set_position(DockPosition::Left, window, cx);
13223        });
13224
13225        workspace.update(cx, |workspace, cx| {
13226            // Since panel_2 was not visible on the right, we don't open the left dock.
13227            assert!(!workspace.left_dock().read(cx).is_open());
13228            // And the right dock is unaffected in its displaying of panel_1
13229            assert!(workspace.right_dock().read(cx).is_open());
13230            assert_eq!(
13231                workspace
13232                    .right_dock()
13233                    .read(cx)
13234                    .visible_panel()
13235                    .unwrap()
13236                    .panel_id(),
13237                panel_1.panel_id(),
13238            );
13239        });
13240
13241        // Move panel_1 back to the left
13242        panel_1.update_in(cx, |panel_1, window, cx| {
13243            panel_1.set_position(DockPosition::Left, window, cx)
13244        });
13245
13246        workspace.update_in(cx, |workspace, window, cx| {
13247            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
13248            let left_dock = workspace.left_dock();
13249            assert!(left_dock.read(cx).is_open());
13250            assert_eq!(
13251                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13252                panel_1.panel_id()
13253            );
13254            assert_eq!(
13255                workspace.dock_size(&left_dock.read(cx), window, cx),
13256                Some(px(1337.))
13257            );
13258            // And the right dock should be closed as it no longer has any panels.
13259            assert!(!workspace.right_dock().read(cx).is_open());
13260
13261            // Now we move panel_1 to the bottom
13262            panel_1.set_position(DockPosition::Bottom, window, cx);
13263        });
13264
13265        workspace.update_in(cx, |workspace, window, cx| {
13266            // Since panel_1 was visible on the left, we close the left dock.
13267            assert!(!workspace.left_dock().read(cx).is_open());
13268            // The bottom dock is sized based on the panel's default size,
13269            // since the panel orientation changed from vertical to horizontal.
13270            let bottom_dock = workspace.bottom_dock();
13271            assert_eq!(
13272                workspace.dock_size(&bottom_dock.read(cx), window, cx),
13273                Some(px(300.))
13274            );
13275            // Close bottom dock and move panel_1 back to the left.
13276            bottom_dock.update(cx, |bottom_dock, cx| {
13277                bottom_dock.set_open(false, window, cx)
13278            });
13279            panel_1.set_position(DockPosition::Left, window, cx);
13280        });
13281
13282        // Emit activated event on panel 1
13283        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
13284
13285        // Now the left dock is open and panel_1 is active and focused.
13286        workspace.update_in(cx, |workspace, window, cx| {
13287            let left_dock = workspace.left_dock();
13288            assert!(left_dock.read(cx).is_open());
13289            assert_eq!(
13290                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13291                panel_1.panel_id(),
13292            );
13293            assert!(panel_1.focus_handle(cx).is_focused(window));
13294        });
13295
13296        // Emit closed event on panel 2, which is not active
13297        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13298
13299        // Wo don't close the left dock, because panel_2 wasn't the active panel
13300        workspace.update(cx, |workspace, cx| {
13301            let left_dock = workspace.left_dock();
13302            assert!(left_dock.read(cx).is_open());
13303            assert_eq!(
13304                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13305                panel_1.panel_id(),
13306            );
13307        });
13308
13309        // Emitting a ZoomIn event shows the panel as zoomed.
13310        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
13311        workspace.read_with(cx, |workspace, _| {
13312            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13313            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
13314        });
13315
13316        // Move panel to another dock while it is zoomed
13317        panel_1.update_in(cx, |panel, window, cx| {
13318            panel.set_position(DockPosition::Right, window, cx)
13319        });
13320        workspace.read_with(cx, |workspace, _| {
13321            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13322
13323            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13324        });
13325
13326        // This is a helper for getting a:
13327        // - valid focus on an element,
13328        // - that isn't a part of the panes and panels system of the Workspace,
13329        // - and doesn't trigger the 'on_focus_lost' API.
13330        let focus_other_view = {
13331            let workspace = workspace.clone();
13332            move |cx: &mut VisualTestContext| {
13333                workspace.update_in(cx, |workspace, window, cx| {
13334                    if workspace.active_modal::<TestModal>(cx).is_some() {
13335                        workspace.toggle_modal(window, cx, TestModal::new);
13336                        workspace.toggle_modal(window, cx, TestModal::new);
13337                    } else {
13338                        workspace.toggle_modal(window, cx, TestModal::new);
13339                    }
13340                })
13341            }
13342        };
13343
13344        // If focus is transferred to another view that's not a panel or another pane, we still show
13345        // the panel as zoomed.
13346        focus_other_view(cx);
13347        workspace.read_with(cx, |workspace, _| {
13348            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13349            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13350        });
13351
13352        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13353        workspace.update_in(cx, |_workspace, window, cx| {
13354            cx.focus_self(window);
13355        });
13356        workspace.read_with(cx, |workspace, _| {
13357            assert_eq!(workspace.zoomed, None);
13358            assert_eq!(workspace.zoomed_position, None);
13359        });
13360
13361        // If focus is transferred again to another view that's not a panel or a pane, we won't
13362        // show the panel as zoomed because it wasn't zoomed before.
13363        focus_other_view(cx);
13364        workspace.read_with(cx, |workspace, _| {
13365            assert_eq!(workspace.zoomed, None);
13366            assert_eq!(workspace.zoomed_position, None);
13367        });
13368
13369        // When the panel is activated, it is zoomed again.
13370        cx.dispatch_action(ToggleRightDock);
13371        workspace.read_with(cx, |workspace, _| {
13372            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13373            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13374        });
13375
13376        // Emitting a ZoomOut event unzooms the panel.
13377        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13378        workspace.read_with(cx, |workspace, _| {
13379            assert_eq!(workspace.zoomed, None);
13380            assert_eq!(workspace.zoomed_position, None);
13381        });
13382
13383        // Emit closed event on panel 1, which is active
13384        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13385
13386        // Now the left dock is closed, because panel_1 was the active panel
13387        workspace.update(cx, |workspace, cx| {
13388            let right_dock = workspace.right_dock();
13389            assert!(!right_dock.read(cx).is_open());
13390        });
13391    }
13392
13393    #[gpui::test]
13394    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13395        init_test(cx);
13396
13397        let fs = FakeFs::new(cx.background_executor.clone());
13398        let project = Project::test(fs, [], cx).await;
13399        let (workspace, cx) =
13400            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13401        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13402
13403        let dirty_regular_buffer = cx.new(|cx| {
13404            TestItem::new(cx)
13405                .with_dirty(true)
13406                .with_label("1.txt")
13407                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13408        });
13409        let dirty_regular_buffer_2 = cx.new(|cx| {
13410            TestItem::new(cx)
13411                .with_dirty(true)
13412                .with_label("2.txt")
13413                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13414        });
13415        let dirty_multi_buffer_with_both = cx.new(|cx| {
13416            TestItem::new(cx)
13417                .with_dirty(true)
13418                .with_buffer_kind(ItemBufferKind::Multibuffer)
13419                .with_label("Fake Project Search")
13420                .with_project_items(&[
13421                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13422                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13423                ])
13424        });
13425        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13426        workspace.update_in(cx, |workspace, window, cx| {
13427            workspace.add_item(
13428                pane.clone(),
13429                Box::new(dirty_regular_buffer.clone()),
13430                None,
13431                false,
13432                false,
13433                window,
13434                cx,
13435            );
13436            workspace.add_item(
13437                pane.clone(),
13438                Box::new(dirty_regular_buffer_2.clone()),
13439                None,
13440                false,
13441                false,
13442                window,
13443                cx,
13444            );
13445            workspace.add_item(
13446                pane.clone(),
13447                Box::new(dirty_multi_buffer_with_both.clone()),
13448                None,
13449                false,
13450                false,
13451                window,
13452                cx,
13453            );
13454        });
13455
13456        pane.update_in(cx, |pane, window, cx| {
13457            pane.activate_item(2, true, true, window, cx);
13458            assert_eq!(
13459                pane.active_item().unwrap().item_id(),
13460                multi_buffer_with_both_files_id,
13461                "Should select the multi buffer in the pane"
13462            );
13463        });
13464        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13465            pane.close_other_items(
13466                &CloseOtherItems {
13467                    save_intent: Some(SaveIntent::Save),
13468                    close_pinned: true,
13469                },
13470                None,
13471                window,
13472                cx,
13473            )
13474        });
13475        cx.background_executor.run_until_parked();
13476        assert!(!cx.has_pending_prompt());
13477        close_all_but_multi_buffer_task
13478            .await
13479            .expect("Closing all buffers but the multi buffer failed");
13480        pane.update(cx, |pane, cx| {
13481            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13482            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13483            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13484            assert_eq!(pane.items_len(), 1);
13485            assert_eq!(
13486                pane.active_item().unwrap().item_id(),
13487                multi_buffer_with_both_files_id,
13488                "Should have only the multi buffer left in the pane"
13489            );
13490            assert!(
13491                dirty_multi_buffer_with_both.read(cx).is_dirty,
13492                "The multi buffer containing the unsaved buffer should still be dirty"
13493            );
13494        });
13495
13496        dirty_regular_buffer.update(cx, |buffer, cx| {
13497            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13498        });
13499
13500        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13501            pane.close_active_item(
13502                &CloseActiveItem {
13503                    save_intent: Some(SaveIntent::Close),
13504                    close_pinned: false,
13505                },
13506                window,
13507                cx,
13508            )
13509        });
13510        cx.background_executor.run_until_parked();
13511        assert!(
13512            cx.has_pending_prompt(),
13513            "Dirty multi buffer should prompt a save dialog"
13514        );
13515        cx.simulate_prompt_answer("Save");
13516        cx.background_executor.run_until_parked();
13517        close_multi_buffer_task
13518            .await
13519            .expect("Closing the multi buffer failed");
13520        pane.update(cx, |pane, cx| {
13521            assert_eq!(
13522                dirty_multi_buffer_with_both.read(cx).save_count,
13523                1,
13524                "Multi buffer item should get be saved"
13525            );
13526            // Test impl does not save inner items, so we do not assert them
13527            assert_eq!(
13528                pane.items_len(),
13529                0,
13530                "No more items should be left in the pane"
13531            );
13532            assert!(pane.active_item().is_none());
13533        });
13534    }
13535
13536    #[gpui::test]
13537    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13538        cx: &mut TestAppContext,
13539    ) {
13540        init_test(cx);
13541
13542        let fs = FakeFs::new(cx.background_executor.clone());
13543        let project = Project::test(fs, [], cx).await;
13544        let (workspace, cx) =
13545            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13546        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13547
13548        let dirty_regular_buffer = cx.new(|cx| {
13549            TestItem::new(cx)
13550                .with_dirty(true)
13551                .with_label("1.txt")
13552                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13553        });
13554        let dirty_regular_buffer_2 = cx.new(|cx| {
13555            TestItem::new(cx)
13556                .with_dirty(true)
13557                .with_label("2.txt")
13558                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13559        });
13560        let clear_regular_buffer = cx.new(|cx| {
13561            TestItem::new(cx)
13562                .with_label("3.txt")
13563                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13564        });
13565
13566        let dirty_multi_buffer_with_both = cx.new(|cx| {
13567            TestItem::new(cx)
13568                .with_dirty(true)
13569                .with_buffer_kind(ItemBufferKind::Multibuffer)
13570                .with_label("Fake Project Search")
13571                .with_project_items(&[
13572                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13573                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13574                    clear_regular_buffer.read(cx).project_items[0].clone(),
13575                ])
13576        });
13577        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13578        workspace.update_in(cx, |workspace, window, cx| {
13579            workspace.add_item(
13580                pane.clone(),
13581                Box::new(dirty_regular_buffer.clone()),
13582                None,
13583                false,
13584                false,
13585                window,
13586                cx,
13587            );
13588            workspace.add_item(
13589                pane.clone(),
13590                Box::new(dirty_multi_buffer_with_both.clone()),
13591                None,
13592                false,
13593                false,
13594                window,
13595                cx,
13596            );
13597        });
13598
13599        pane.update_in(cx, |pane, window, cx| {
13600            pane.activate_item(1, true, true, window, cx);
13601            assert_eq!(
13602                pane.active_item().unwrap().item_id(),
13603                multi_buffer_with_both_files_id,
13604                "Should select the multi buffer in the pane"
13605            );
13606        });
13607        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13608            pane.close_active_item(
13609                &CloseActiveItem {
13610                    save_intent: None,
13611                    close_pinned: false,
13612                },
13613                window,
13614                cx,
13615            )
13616        });
13617        cx.background_executor.run_until_parked();
13618        assert!(
13619            cx.has_pending_prompt(),
13620            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13621        );
13622    }
13623
13624    /// Tests that when `close_on_file_delete` is enabled, files are automatically
13625    /// closed when they are deleted from disk.
13626    #[gpui::test]
13627    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13628        init_test(cx);
13629
13630        // Enable the close_on_disk_deletion setting
13631        cx.update_global(|store: &mut SettingsStore, cx| {
13632            store.update_user_settings(cx, |settings| {
13633                settings.workspace.close_on_file_delete = Some(true);
13634            });
13635        });
13636
13637        let fs = FakeFs::new(cx.background_executor.clone());
13638        let project = Project::test(fs, [], cx).await;
13639        let (workspace, cx) =
13640            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13641        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13642
13643        // Create a test item that simulates a file
13644        let item = cx.new(|cx| {
13645            TestItem::new(cx)
13646                .with_label("test.txt")
13647                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13648        });
13649
13650        // Add item to workspace
13651        workspace.update_in(cx, |workspace, window, cx| {
13652            workspace.add_item(
13653                pane.clone(),
13654                Box::new(item.clone()),
13655                None,
13656                false,
13657                false,
13658                window,
13659                cx,
13660            );
13661        });
13662
13663        // Verify the item is in the pane
13664        pane.read_with(cx, |pane, _| {
13665            assert_eq!(pane.items().count(), 1);
13666        });
13667
13668        // Simulate file deletion by setting the item's deleted state
13669        item.update(cx, |item, _| {
13670            item.set_has_deleted_file(true);
13671        });
13672
13673        // Emit UpdateTab event to trigger the close behavior
13674        cx.run_until_parked();
13675        item.update(cx, |_, cx| {
13676            cx.emit(ItemEvent::UpdateTab);
13677        });
13678
13679        // Allow the close operation to complete
13680        cx.run_until_parked();
13681
13682        // Verify the item was automatically closed
13683        pane.read_with(cx, |pane, _| {
13684            assert_eq!(
13685                pane.items().count(),
13686                0,
13687                "Item should be automatically closed when file is deleted"
13688            );
13689        });
13690    }
13691
13692    /// Tests that when `close_on_file_delete` is disabled (default), files remain
13693    /// open with a strikethrough when they are deleted from disk.
13694    #[gpui::test]
13695    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13696        init_test(cx);
13697
13698        // Ensure close_on_disk_deletion is disabled (default)
13699        cx.update_global(|store: &mut SettingsStore, cx| {
13700            store.update_user_settings(cx, |settings| {
13701                settings.workspace.close_on_file_delete = Some(false);
13702            });
13703        });
13704
13705        let fs = FakeFs::new(cx.background_executor.clone());
13706        let project = Project::test(fs, [], cx).await;
13707        let (workspace, cx) =
13708            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13709        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13710
13711        // Create a test item that simulates a file
13712        let item = cx.new(|cx| {
13713            TestItem::new(cx)
13714                .with_label("test.txt")
13715                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13716        });
13717
13718        // Add item to workspace
13719        workspace.update_in(cx, |workspace, window, cx| {
13720            workspace.add_item(
13721                pane.clone(),
13722                Box::new(item.clone()),
13723                None,
13724                false,
13725                false,
13726                window,
13727                cx,
13728            );
13729        });
13730
13731        // Verify the item is in the pane
13732        pane.read_with(cx, |pane, _| {
13733            assert_eq!(pane.items().count(), 1);
13734        });
13735
13736        // Simulate file deletion
13737        item.update(cx, |item, _| {
13738            item.set_has_deleted_file(true);
13739        });
13740
13741        // Emit UpdateTab event
13742        cx.run_until_parked();
13743        item.update(cx, |_, cx| {
13744            cx.emit(ItemEvent::UpdateTab);
13745        });
13746
13747        // Allow any potential close operation to complete
13748        cx.run_until_parked();
13749
13750        // Verify the item remains open (with strikethrough)
13751        pane.read_with(cx, |pane, _| {
13752            assert_eq!(
13753                pane.items().count(),
13754                1,
13755                "Item should remain open when close_on_disk_deletion is disabled"
13756            );
13757        });
13758
13759        // Verify the item shows as deleted
13760        item.read_with(cx, |item, _| {
13761            assert!(
13762                item.has_deleted_file,
13763                "Item should be marked as having deleted file"
13764            );
13765        });
13766    }
13767
13768    /// Tests that dirty files are not automatically closed when deleted from disk,
13769    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13770    /// unsaved changes without being prompted.
13771    #[gpui::test]
13772    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13773        init_test(cx);
13774
13775        // Enable the close_on_file_delete setting
13776        cx.update_global(|store: &mut SettingsStore, cx| {
13777            store.update_user_settings(cx, |settings| {
13778                settings.workspace.close_on_file_delete = Some(true);
13779            });
13780        });
13781
13782        let fs = FakeFs::new(cx.background_executor.clone());
13783        let project = Project::test(fs, [], cx).await;
13784        let (workspace, cx) =
13785            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13786        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13787
13788        // Create a dirty test item
13789        let item = cx.new(|cx| {
13790            TestItem::new(cx)
13791                .with_dirty(true)
13792                .with_label("test.txt")
13793                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13794        });
13795
13796        // Add item to workspace
13797        workspace.update_in(cx, |workspace, window, cx| {
13798            workspace.add_item(
13799                pane.clone(),
13800                Box::new(item.clone()),
13801                None,
13802                false,
13803                false,
13804                window,
13805                cx,
13806            );
13807        });
13808
13809        // Simulate file deletion
13810        item.update(cx, |item, _| {
13811            item.set_has_deleted_file(true);
13812        });
13813
13814        // Emit UpdateTab event to trigger the close behavior
13815        cx.run_until_parked();
13816        item.update(cx, |_, cx| {
13817            cx.emit(ItemEvent::UpdateTab);
13818        });
13819
13820        // Allow any potential close operation to complete
13821        cx.run_until_parked();
13822
13823        // Verify the item remains open (dirty files are not auto-closed)
13824        pane.read_with(cx, |pane, _| {
13825            assert_eq!(
13826                pane.items().count(),
13827                1,
13828                "Dirty items should not be automatically closed even when file is deleted"
13829            );
13830        });
13831
13832        // Verify the item is marked as deleted and still dirty
13833        item.read_with(cx, |item, _| {
13834            assert!(
13835                item.has_deleted_file,
13836                "Item should be marked as having deleted file"
13837            );
13838            assert!(item.is_dirty, "Item should still be dirty");
13839        });
13840    }
13841
13842    /// Tests that navigation history is cleaned up when files are auto-closed
13843    /// due to deletion from disk.
13844    #[gpui::test]
13845    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13846        init_test(cx);
13847
13848        // Enable the close_on_file_delete setting
13849        cx.update_global(|store: &mut SettingsStore, cx| {
13850            store.update_user_settings(cx, |settings| {
13851                settings.workspace.close_on_file_delete = Some(true);
13852            });
13853        });
13854
13855        let fs = FakeFs::new(cx.background_executor.clone());
13856        let project = Project::test(fs, [], cx).await;
13857        let (workspace, cx) =
13858            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13859        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13860
13861        // Create test items
13862        let item1 = cx.new(|cx| {
13863            TestItem::new(cx)
13864                .with_label("test1.txt")
13865                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13866        });
13867        let item1_id = item1.item_id();
13868
13869        let item2 = cx.new(|cx| {
13870            TestItem::new(cx)
13871                .with_label("test2.txt")
13872                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13873        });
13874
13875        // Add items to workspace
13876        workspace.update_in(cx, |workspace, window, cx| {
13877            workspace.add_item(
13878                pane.clone(),
13879                Box::new(item1.clone()),
13880                None,
13881                false,
13882                false,
13883                window,
13884                cx,
13885            );
13886            workspace.add_item(
13887                pane.clone(),
13888                Box::new(item2.clone()),
13889                None,
13890                false,
13891                false,
13892                window,
13893                cx,
13894            );
13895        });
13896
13897        // Activate item1 to ensure it gets navigation entries
13898        pane.update_in(cx, |pane, window, cx| {
13899            pane.activate_item(0, true, true, window, cx);
13900        });
13901
13902        // Switch to item2 and back to create navigation history
13903        pane.update_in(cx, |pane, window, cx| {
13904            pane.activate_item(1, true, true, window, cx);
13905        });
13906        cx.run_until_parked();
13907
13908        pane.update_in(cx, |pane, window, cx| {
13909            pane.activate_item(0, true, true, window, cx);
13910        });
13911        cx.run_until_parked();
13912
13913        // Simulate file deletion for item1
13914        item1.update(cx, |item, _| {
13915            item.set_has_deleted_file(true);
13916        });
13917
13918        // Emit UpdateTab event to trigger the close behavior
13919        item1.update(cx, |_, cx| {
13920            cx.emit(ItemEvent::UpdateTab);
13921        });
13922        cx.run_until_parked();
13923
13924        // Verify item1 was closed
13925        pane.read_with(cx, |pane, _| {
13926            assert_eq!(
13927                pane.items().count(),
13928                1,
13929                "Should have 1 item remaining after auto-close"
13930            );
13931        });
13932
13933        // Check navigation history after close
13934        let has_item = pane.read_with(cx, |pane, cx| {
13935            let mut has_item = false;
13936            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13937                if entry.item.id() == item1_id {
13938                    has_item = true;
13939                }
13940            });
13941            has_item
13942        });
13943
13944        assert!(
13945            !has_item,
13946            "Navigation history should not contain closed item entries"
13947        );
13948    }
13949
13950    #[gpui::test]
13951    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13952        cx: &mut TestAppContext,
13953    ) {
13954        init_test(cx);
13955
13956        let fs = FakeFs::new(cx.background_executor.clone());
13957        let project = Project::test(fs, [], cx).await;
13958        let (workspace, cx) =
13959            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13960        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13961
13962        let dirty_regular_buffer = cx.new(|cx| {
13963            TestItem::new(cx)
13964                .with_dirty(true)
13965                .with_label("1.txt")
13966                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13967        });
13968        let dirty_regular_buffer_2 = cx.new(|cx| {
13969            TestItem::new(cx)
13970                .with_dirty(true)
13971                .with_label("2.txt")
13972                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13973        });
13974        let clear_regular_buffer = cx.new(|cx| {
13975            TestItem::new(cx)
13976                .with_label("3.txt")
13977                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13978        });
13979
13980        let dirty_multi_buffer = cx.new(|cx| {
13981            TestItem::new(cx)
13982                .with_dirty(true)
13983                .with_buffer_kind(ItemBufferKind::Multibuffer)
13984                .with_label("Fake Project Search")
13985                .with_project_items(&[
13986                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13987                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13988                    clear_regular_buffer.read(cx).project_items[0].clone(),
13989                ])
13990        });
13991        workspace.update_in(cx, |workspace, window, cx| {
13992            workspace.add_item(
13993                pane.clone(),
13994                Box::new(dirty_regular_buffer.clone()),
13995                None,
13996                false,
13997                false,
13998                window,
13999                cx,
14000            );
14001            workspace.add_item(
14002                pane.clone(),
14003                Box::new(dirty_regular_buffer_2.clone()),
14004                None,
14005                false,
14006                false,
14007                window,
14008                cx,
14009            );
14010            workspace.add_item(
14011                pane.clone(),
14012                Box::new(dirty_multi_buffer.clone()),
14013                None,
14014                false,
14015                false,
14016                window,
14017                cx,
14018            );
14019        });
14020
14021        pane.update_in(cx, |pane, window, cx| {
14022            pane.activate_item(2, true, true, window, cx);
14023            assert_eq!(
14024                pane.active_item().unwrap().item_id(),
14025                dirty_multi_buffer.item_id(),
14026                "Should select the multi buffer in the pane"
14027            );
14028        });
14029        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
14030            pane.close_active_item(
14031                &CloseActiveItem {
14032                    save_intent: None,
14033                    close_pinned: false,
14034                },
14035                window,
14036                cx,
14037            )
14038        });
14039        cx.background_executor.run_until_parked();
14040        assert!(
14041            !cx.has_pending_prompt(),
14042            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
14043        );
14044        close_multi_buffer_task
14045            .await
14046            .expect("Closing multi buffer failed");
14047        pane.update(cx, |pane, cx| {
14048            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
14049            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
14050            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
14051            assert_eq!(
14052                pane.items()
14053                    .map(|item| item.item_id())
14054                    .sorted()
14055                    .collect::<Vec<_>>(),
14056                vec![
14057                    dirty_regular_buffer.item_id(),
14058                    dirty_regular_buffer_2.item_id(),
14059                ],
14060                "Should have no multi buffer left in the pane"
14061            );
14062            assert!(dirty_regular_buffer.read(cx).is_dirty);
14063            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
14064        });
14065    }
14066
14067    #[gpui::test]
14068    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
14069        init_test(cx);
14070        let fs = FakeFs::new(cx.executor());
14071        let project = Project::test(fs, [], cx).await;
14072        let (multi_workspace, cx) =
14073            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14074        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14075
14076        // Add a new panel to the right dock, opening the dock and setting the
14077        // focus to the new panel.
14078        let panel = workspace.update_in(cx, |workspace, window, cx| {
14079            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14080            workspace.add_panel(panel.clone(), window, cx);
14081
14082            workspace
14083                .right_dock()
14084                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14085
14086            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14087
14088            panel
14089        });
14090
14091        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
14092        // panel to the next valid position which, in this case, is the left
14093        // dock.
14094        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14095        workspace.update(cx, |workspace, cx| {
14096            assert!(workspace.left_dock().read(cx).is_open());
14097            assert_eq!(panel.read(cx).position, DockPosition::Left);
14098        });
14099
14100        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
14101        // panel to the next valid position which, in this case, is the bottom
14102        // dock.
14103        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14104        workspace.update(cx, |workspace, cx| {
14105            assert!(workspace.bottom_dock().read(cx).is_open());
14106            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
14107        });
14108
14109        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
14110        // around moving the panel to its initial position, the right dock.
14111        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14112        workspace.update(cx, |workspace, cx| {
14113            assert!(workspace.right_dock().read(cx).is_open());
14114            assert_eq!(panel.read(cx).position, DockPosition::Right);
14115        });
14116
14117        // Remove focus from the panel, ensuring that, if the panel is not
14118        // focused, the `MoveFocusedPanelToNextPosition` action does not update
14119        // the panel's position, so the panel is still in the right dock.
14120        workspace.update_in(cx, |workspace, window, cx| {
14121            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14122        });
14123
14124        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14125        workspace.update(cx, |workspace, cx| {
14126            assert!(workspace.right_dock().read(cx).is_open());
14127            assert_eq!(panel.read(cx).position, DockPosition::Right);
14128        });
14129    }
14130
14131    #[gpui::test]
14132    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
14133        init_test(cx);
14134
14135        let fs = FakeFs::new(cx.executor());
14136        let project = Project::test(fs, [], cx).await;
14137        let (workspace, cx) =
14138            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14139
14140        let item_1 = cx.new(|cx| {
14141            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14142        });
14143        workspace.update_in(cx, |workspace, window, cx| {
14144            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14145            workspace.move_item_to_pane_in_direction(
14146                &MoveItemToPaneInDirection {
14147                    direction: SplitDirection::Right,
14148                    focus: true,
14149                    clone: false,
14150                },
14151                window,
14152                cx,
14153            );
14154            workspace.move_item_to_pane_at_index(
14155                &MoveItemToPane {
14156                    destination: 3,
14157                    focus: true,
14158                    clone: false,
14159                },
14160                window,
14161                cx,
14162            );
14163
14164            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
14165            assert_eq!(
14166                pane_items_paths(&workspace.active_pane, cx),
14167                vec!["first.txt".to_string()],
14168                "Single item was not moved anywhere"
14169            );
14170        });
14171
14172        let item_2 = cx.new(|cx| {
14173            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
14174        });
14175        workspace.update_in(cx, |workspace, window, cx| {
14176            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
14177            assert_eq!(
14178                pane_items_paths(&workspace.panes[0], cx),
14179                vec!["first.txt".to_string(), "second.txt".to_string()],
14180            );
14181            workspace.move_item_to_pane_in_direction(
14182                &MoveItemToPaneInDirection {
14183                    direction: SplitDirection::Right,
14184                    focus: true,
14185                    clone: false,
14186                },
14187                window,
14188                cx,
14189            );
14190
14191            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
14192            assert_eq!(
14193                pane_items_paths(&workspace.panes[0], cx),
14194                vec!["first.txt".to_string()],
14195                "After moving, one item should be left in the original pane"
14196            );
14197            assert_eq!(
14198                pane_items_paths(&workspace.panes[1], cx),
14199                vec!["second.txt".to_string()],
14200                "New item should have been moved to the new pane"
14201            );
14202        });
14203
14204        let item_3 = cx.new(|cx| {
14205            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
14206        });
14207        workspace.update_in(cx, |workspace, window, cx| {
14208            let original_pane = workspace.panes[0].clone();
14209            workspace.set_active_pane(&original_pane, window, cx);
14210            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
14211            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
14212            assert_eq!(
14213                pane_items_paths(&workspace.active_pane, cx),
14214                vec!["first.txt".to_string(), "third.txt".to_string()],
14215                "New pane should be ready to move one item out"
14216            );
14217
14218            workspace.move_item_to_pane_at_index(
14219                &MoveItemToPane {
14220                    destination: 3,
14221                    focus: true,
14222                    clone: false,
14223                },
14224                window,
14225                cx,
14226            );
14227            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
14228            assert_eq!(
14229                pane_items_paths(&workspace.active_pane, cx),
14230                vec!["first.txt".to_string()],
14231                "After moving, one item should be left in the original pane"
14232            );
14233            assert_eq!(
14234                pane_items_paths(&workspace.panes[1], cx),
14235                vec!["second.txt".to_string()],
14236                "Previously created pane should be unchanged"
14237            );
14238            assert_eq!(
14239                pane_items_paths(&workspace.panes[2], cx),
14240                vec!["third.txt".to_string()],
14241                "New item should have been moved to the new pane"
14242            );
14243        });
14244    }
14245
14246    #[gpui::test]
14247    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
14248        init_test(cx);
14249
14250        let fs = FakeFs::new(cx.executor());
14251        let project = Project::test(fs, [], cx).await;
14252        let (workspace, cx) =
14253            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14254
14255        let item_1 = cx.new(|cx| {
14256            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14257        });
14258        workspace.update_in(cx, |workspace, window, cx| {
14259            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14260            workspace.move_item_to_pane_in_direction(
14261                &MoveItemToPaneInDirection {
14262                    direction: SplitDirection::Right,
14263                    focus: true,
14264                    clone: true,
14265                },
14266                window,
14267                cx,
14268            );
14269        });
14270        cx.run_until_parked();
14271        workspace.update_in(cx, |workspace, window, cx| {
14272            workspace.move_item_to_pane_at_index(
14273                &MoveItemToPane {
14274                    destination: 3,
14275                    focus: true,
14276                    clone: true,
14277                },
14278                window,
14279                cx,
14280            );
14281        });
14282        cx.run_until_parked();
14283
14284        workspace.update(cx, |workspace, cx| {
14285            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
14286            for pane in workspace.panes() {
14287                assert_eq!(
14288                    pane_items_paths(pane, cx),
14289                    vec!["first.txt".to_string()],
14290                    "Single item exists in all panes"
14291                );
14292            }
14293        });
14294
14295        // verify that the active pane has been updated after waiting for the
14296        // pane focus event to fire and resolve
14297        workspace.read_with(cx, |workspace, _app| {
14298            assert_eq!(
14299                workspace.active_pane(),
14300                &workspace.panes[2],
14301                "The third pane should be the active one: {:?}",
14302                workspace.panes
14303            );
14304        })
14305    }
14306
14307    #[gpui::test]
14308    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
14309        init_test(cx);
14310
14311        let fs = FakeFs::new(cx.executor());
14312        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
14313
14314        let project = Project::test(fs, ["root".as_ref()], cx).await;
14315        let (workspace, cx) =
14316            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14317
14318        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14319        // Add item to pane A with project path
14320        let item_a = cx.new(|cx| {
14321            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14322        });
14323        workspace.update_in(cx, |workspace, window, cx| {
14324            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14325        });
14326
14327        // Split to create pane B
14328        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14329            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14330        });
14331
14332        // Add item with SAME project path to pane B, and pin it
14333        let item_b = cx.new(|cx| {
14334            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14335        });
14336        pane_b.update_in(cx, |pane, window, cx| {
14337            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14338            pane.set_pinned_count(1);
14339        });
14340
14341        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14342        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14343
14344        // close_pinned: false should only close the unpinned copy
14345        workspace.update_in(cx, |workspace, window, cx| {
14346            workspace.close_item_in_all_panes(
14347                &CloseItemInAllPanes {
14348                    save_intent: Some(SaveIntent::Close),
14349                    close_pinned: false,
14350                },
14351                window,
14352                cx,
14353            )
14354        });
14355        cx.executor().run_until_parked();
14356
14357        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14358        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14359        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14360        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14361
14362        // Split again, seeing as closing the previous item also closed its
14363        // pane, so only pane remains, which does not allow us to properly test
14364        // that both items close when `close_pinned: true`.
14365        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14366            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14367        });
14368
14369        // Add an item with the same project path to pane C so that
14370        // close_item_in_all_panes can determine what to close across all panes
14371        // (it reads the active item from the active pane, and split_pane
14372        // creates an empty pane).
14373        let item_c = cx.new(|cx| {
14374            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14375        });
14376        pane_c.update_in(cx, |pane, window, cx| {
14377            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14378        });
14379
14380        // close_pinned: true should close the pinned copy too
14381        workspace.update_in(cx, |workspace, window, cx| {
14382            let panes_count = workspace.panes().len();
14383            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14384
14385            workspace.close_item_in_all_panes(
14386                &CloseItemInAllPanes {
14387                    save_intent: Some(SaveIntent::Close),
14388                    close_pinned: true,
14389                },
14390                window,
14391                cx,
14392            )
14393        });
14394        cx.executor().run_until_parked();
14395
14396        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14397        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14398        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14399        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14400    }
14401
14402    mod register_project_item_tests {
14403
14404        use super::*;
14405
14406        // View
14407        struct TestPngItemView {
14408            focus_handle: FocusHandle,
14409        }
14410        // Model
14411        struct TestPngItem {}
14412
14413        impl project::ProjectItem for TestPngItem {
14414            fn try_open(
14415                _project: &Entity<Project>,
14416                path: &ProjectPath,
14417                cx: &mut App,
14418            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14419                if path.path.extension().unwrap() == "png" {
14420                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14421                } else {
14422                    None
14423                }
14424            }
14425
14426            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14427                None
14428            }
14429
14430            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14431                None
14432            }
14433
14434            fn is_dirty(&self) -> bool {
14435                false
14436            }
14437        }
14438
14439        impl Item for TestPngItemView {
14440            type Event = ();
14441            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14442                "".into()
14443            }
14444        }
14445        impl EventEmitter<()> for TestPngItemView {}
14446        impl Focusable for TestPngItemView {
14447            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14448                self.focus_handle.clone()
14449            }
14450        }
14451
14452        impl Render for TestPngItemView {
14453            fn render(
14454                &mut self,
14455                _window: &mut Window,
14456                _cx: &mut Context<Self>,
14457            ) -> impl IntoElement {
14458                Empty
14459            }
14460        }
14461
14462        impl ProjectItem for TestPngItemView {
14463            type Item = TestPngItem;
14464
14465            fn for_project_item(
14466                _project: Entity<Project>,
14467                _pane: Option<&Pane>,
14468                _item: Entity<Self::Item>,
14469                _: &mut Window,
14470                cx: &mut Context<Self>,
14471            ) -> Self
14472            where
14473                Self: Sized,
14474            {
14475                Self {
14476                    focus_handle: cx.focus_handle(),
14477                }
14478            }
14479        }
14480
14481        // View
14482        struct TestIpynbItemView {
14483            focus_handle: FocusHandle,
14484        }
14485        // Model
14486        struct TestIpynbItem {}
14487
14488        impl project::ProjectItem for TestIpynbItem {
14489            fn try_open(
14490                _project: &Entity<Project>,
14491                path: &ProjectPath,
14492                cx: &mut App,
14493            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14494                if path.path.extension().unwrap() == "ipynb" {
14495                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14496                } else {
14497                    None
14498                }
14499            }
14500
14501            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14502                None
14503            }
14504
14505            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14506                None
14507            }
14508
14509            fn is_dirty(&self) -> bool {
14510                false
14511            }
14512        }
14513
14514        impl Item for TestIpynbItemView {
14515            type Event = ();
14516            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14517                "".into()
14518            }
14519        }
14520        impl EventEmitter<()> for TestIpynbItemView {}
14521        impl Focusable for TestIpynbItemView {
14522            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14523                self.focus_handle.clone()
14524            }
14525        }
14526
14527        impl Render for TestIpynbItemView {
14528            fn render(
14529                &mut self,
14530                _window: &mut Window,
14531                _cx: &mut Context<Self>,
14532            ) -> impl IntoElement {
14533                Empty
14534            }
14535        }
14536
14537        impl ProjectItem for TestIpynbItemView {
14538            type Item = TestIpynbItem;
14539
14540            fn for_project_item(
14541                _project: Entity<Project>,
14542                _pane: Option<&Pane>,
14543                _item: Entity<Self::Item>,
14544                _: &mut Window,
14545                cx: &mut Context<Self>,
14546            ) -> Self
14547            where
14548                Self: Sized,
14549            {
14550                Self {
14551                    focus_handle: cx.focus_handle(),
14552                }
14553            }
14554        }
14555
14556        struct TestAlternatePngItemView {
14557            focus_handle: FocusHandle,
14558        }
14559
14560        impl Item for TestAlternatePngItemView {
14561            type Event = ();
14562            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14563                "".into()
14564            }
14565        }
14566
14567        impl EventEmitter<()> for TestAlternatePngItemView {}
14568        impl Focusable for TestAlternatePngItemView {
14569            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14570                self.focus_handle.clone()
14571            }
14572        }
14573
14574        impl Render for TestAlternatePngItemView {
14575            fn render(
14576                &mut self,
14577                _window: &mut Window,
14578                _cx: &mut Context<Self>,
14579            ) -> impl IntoElement {
14580                Empty
14581            }
14582        }
14583
14584        impl ProjectItem for TestAlternatePngItemView {
14585            type Item = TestPngItem;
14586
14587            fn for_project_item(
14588                _project: Entity<Project>,
14589                _pane: Option<&Pane>,
14590                _item: Entity<Self::Item>,
14591                _: &mut Window,
14592                cx: &mut Context<Self>,
14593            ) -> Self
14594            where
14595                Self: Sized,
14596            {
14597                Self {
14598                    focus_handle: cx.focus_handle(),
14599                }
14600            }
14601        }
14602
14603        #[gpui::test]
14604        async fn test_register_project_item(cx: &mut TestAppContext) {
14605            init_test(cx);
14606
14607            cx.update(|cx| {
14608                register_project_item::<TestPngItemView>(cx);
14609                register_project_item::<TestIpynbItemView>(cx);
14610            });
14611
14612            let fs = FakeFs::new(cx.executor());
14613            fs.insert_tree(
14614                "/root1",
14615                json!({
14616                    "one.png": "BINARYDATAHERE",
14617                    "two.ipynb": "{ totally a notebook }",
14618                    "three.txt": "editing text, sure why not?"
14619                }),
14620            )
14621            .await;
14622
14623            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14624            let (workspace, cx) =
14625                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14626
14627            let worktree_id = project.update(cx, |project, cx| {
14628                project.worktrees(cx).next().unwrap().read(cx).id()
14629            });
14630
14631            let handle = workspace
14632                .update_in(cx, |workspace, window, cx| {
14633                    let project_path = (worktree_id, rel_path("one.png"));
14634                    workspace.open_path(project_path, None, true, window, cx)
14635                })
14636                .await
14637                .unwrap();
14638
14639            // Now we can check if the handle we got back errored or not
14640            assert_eq!(
14641                handle.to_any_view().entity_type(),
14642                TypeId::of::<TestPngItemView>()
14643            );
14644
14645            let handle = workspace
14646                .update_in(cx, |workspace, window, cx| {
14647                    let project_path = (worktree_id, rel_path("two.ipynb"));
14648                    workspace.open_path(project_path, None, true, window, cx)
14649                })
14650                .await
14651                .unwrap();
14652
14653            assert_eq!(
14654                handle.to_any_view().entity_type(),
14655                TypeId::of::<TestIpynbItemView>()
14656            );
14657
14658            let handle = workspace
14659                .update_in(cx, |workspace, window, cx| {
14660                    let project_path = (worktree_id, rel_path("three.txt"));
14661                    workspace.open_path(project_path, None, true, window, cx)
14662                })
14663                .await;
14664            assert!(handle.is_err());
14665        }
14666
14667        #[gpui::test]
14668        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14669            init_test(cx);
14670
14671            cx.update(|cx| {
14672                register_project_item::<TestPngItemView>(cx);
14673                register_project_item::<TestAlternatePngItemView>(cx);
14674            });
14675
14676            let fs = FakeFs::new(cx.executor());
14677            fs.insert_tree(
14678                "/root1",
14679                json!({
14680                    "one.png": "BINARYDATAHERE",
14681                    "two.ipynb": "{ totally a notebook }",
14682                    "three.txt": "editing text, sure why not?"
14683                }),
14684            )
14685            .await;
14686            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14687            let (workspace, cx) =
14688                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14689            let worktree_id = project.update(cx, |project, cx| {
14690                project.worktrees(cx).next().unwrap().read(cx).id()
14691            });
14692
14693            let handle = workspace
14694                .update_in(cx, |workspace, window, cx| {
14695                    let project_path = (worktree_id, rel_path("one.png"));
14696                    workspace.open_path(project_path, None, true, window, cx)
14697                })
14698                .await
14699                .unwrap();
14700
14701            // This _must_ be the second item registered
14702            assert_eq!(
14703                handle.to_any_view().entity_type(),
14704                TypeId::of::<TestAlternatePngItemView>()
14705            );
14706
14707            let handle = workspace
14708                .update_in(cx, |workspace, window, cx| {
14709                    let project_path = (worktree_id, rel_path("three.txt"));
14710                    workspace.open_path(project_path, None, true, window, cx)
14711                })
14712                .await;
14713            assert!(handle.is_err());
14714        }
14715    }
14716
14717    #[gpui::test]
14718    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14719        init_test(cx);
14720
14721        let fs = FakeFs::new(cx.executor());
14722        let project = Project::test(fs, [], cx).await;
14723        let (workspace, _cx) =
14724            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14725
14726        // Test with status bar shown (default)
14727        workspace.read_with(cx, |workspace, cx| {
14728            let visible = workspace.status_bar_visible(cx);
14729            assert!(visible, "Status bar should be visible by default");
14730        });
14731
14732        // Test with status bar hidden
14733        cx.update_global(|store: &mut SettingsStore, cx| {
14734            store.update_user_settings(cx, |settings| {
14735                settings.status_bar.get_or_insert_default().show = Some(false);
14736            });
14737        });
14738
14739        workspace.read_with(cx, |workspace, cx| {
14740            let visible = workspace.status_bar_visible(cx);
14741            assert!(!visible, "Status bar should be hidden when show is false");
14742        });
14743
14744        // Test with status bar shown explicitly
14745        cx.update_global(|store: &mut SettingsStore, cx| {
14746            store.update_user_settings(cx, |settings| {
14747                settings.status_bar.get_or_insert_default().show = Some(true);
14748            });
14749        });
14750
14751        workspace.read_with(cx, |workspace, cx| {
14752            let visible = workspace.status_bar_visible(cx);
14753            assert!(visible, "Status bar should be visible when show is true");
14754        });
14755    }
14756
14757    #[gpui::test]
14758    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14759        init_test(cx);
14760
14761        let fs = FakeFs::new(cx.executor());
14762        let project = Project::test(fs, [], cx).await;
14763        let (multi_workspace, cx) =
14764            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14765        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14766        let panel = workspace.update_in(cx, |workspace, window, cx| {
14767            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14768            workspace.add_panel(panel.clone(), window, cx);
14769
14770            workspace
14771                .right_dock()
14772                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14773
14774            panel
14775        });
14776
14777        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14778        let item_a = cx.new(TestItem::new);
14779        let item_b = cx.new(TestItem::new);
14780        let item_a_id = item_a.entity_id();
14781        let item_b_id = item_b.entity_id();
14782
14783        pane.update_in(cx, |pane, window, cx| {
14784            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14785            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14786        });
14787
14788        pane.read_with(cx, |pane, _| {
14789            assert_eq!(pane.items_len(), 2);
14790            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14791        });
14792
14793        workspace.update_in(cx, |workspace, window, cx| {
14794            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14795        });
14796
14797        workspace.update_in(cx, |_, window, cx| {
14798            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14799        });
14800
14801        // Assert that the `pane::CloseActiveItem` action is handled at the
14802        // workspace level when one of the dock panels is focused and, in that
14803        // case, the center pane's active item is closed but the focus is not
14804        // moved.
14805        cx.dispatch_action(pane::CloseActiveItem::default());
14806        cx.run_until_parked();
14807
14808        pane.read_with(cx, |pane, _| {
14809            assert_eq!(pane.items_len(), 1);
14810            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14811        });
14812
14813        workspace.update_in(cx, |workspace, window, cx| {
14814            assert!(workspace.right_dock().read(cx).is_open());
14815            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14816        });
14817    }
14818
14819    #[gpui::test]
14820    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14821        init_test(cx);
14822        let fs = FakeFs::new(cx.executor());
14823
14824        let project_a = Project::test(fs.clone(), [], cx).await;
14825        let project_b = Project::test(fs, [], cx).await;
14826
14827        let multi_workspace_handle =
14828            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14829        cx.run_until_parked();
14830
14831        multi_workspace_handle
14832            .update(cx, |mw, _window, cx| {
14833                mw.open_sidebar(cx);
14834            })
14835            .unwrap();
14836
14837        let workspace_a = multi_workspace_handle
14838            .read_with(cx, |mw, _| mw.workspace().clone())
14839            .unwrap();
14840
14841        let _workspace_b = multi_workspace_handle
14842            .update(cx, |mw, window, cx| {
14843                mw.test_add_workspace(project_b, window, cx)
14844            })
14845            .unwrap();
14846
14847        // Switch to workspace A
14848        multi_workspace_handle
14849            .update(cx, |mw, window, cx| {
14850                let workspace = mw.workspaces().next().unwrap().clone();
14851                mw.activate(workspace, window, cx);
14852            })
14853            .unwrap();
14854
14855        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14856
14857        // Add a panel to workspace A's right dock and open the dock
14858        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14859            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14860            workspace.add_panel(panel.clone(), window, cx);
14861            workspace
14862                .right_dock()
14863                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14864            panel
14865        });
14866
14867        // Focus the panel through the workspace (matching existing test pattern)
14868        workspace_a.update_in(cx, |workspace, window, cx| {
14869            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14870        });
14871
14872        // Zoom the panel
14873        panel.update_in(cx, |panel, window, cx| {
14874            panel.set_zoomed(true, window, cx);
14875        });
14876
14877        // Verify the panel is zoomed and the dock is open
14878        workspace_a.update_in(cx, |workspace, window, cx| {
14879            assert!(
14880                workspace.right_dock().read(cx).is_open(),
14881                "dock should be open before switch"
14882            );
14883            assert!(
14884                panel.is_zoomed(window, cx),
14885                "panel should be zoomed before switch"
14886            );
14887            assert!(
14888                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14889                "panel should be focused before switch"
14890            );
14891        });
14892
14893        // Switch to workspace B
14894        multi_workspace_handle
14895            .update(cx, |mw, window, cx| {
14896                let workspace = mw.workspaces().nth(1).unwrap().clone();
14897                mw.activate(workspace, window, cx);
14898            })
14899            .unwrap();
14900        cx.run_until_parked();
14901
14902        // Switch back to workspace A
14903        multi_workspace_handle
14904            .update(cx, |mw, window, cx| {
14905                let workspace = mw.workspaces().next().unwrap().clone();
14906                mw.activate(workspace, window, cx);
14907            })
14908            .unwrap();
14909        cx.run_until_parked();
14910
14911        // Verify the panel is still zoomed and the dock is still open
14912        workspace_a.update_in(cx, |workspace, window, cx| {
14913            assert!(
14914                workspace.right_dock().read(cx).is_open(),
14915                "dock should still be open after switching back"
14916            );
14917            assert!(
14918                panel.is_zoomed(window, cx),
14919                "panel should still be zoomed after switching back"
14920            );
14921        });
14922    }
14923
14924    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14925        pane.read(cx)
14926            .items()
14927            .flat_map(|item| {
14928                item.project_paths(cx)
14929                    .into_iter()
14930                    .map(|path| path.path.display(PathStyle::local()).into_owned())
14931            })
14932            .collect()
14933    }
14934
14935    pub fn init_test(cx: &mut TestAppContext) {
14936        cx.update(|cx| {
14937            let settings_store = SettingsStore::test(cx);
14938            cx.set_global(settings_store);
14939            cx.set_global(db::AppDatabase::test_new());
14940            theme_settings::init(theme::LoadThemes::JustBase, cx);
14941        });
14942    }
14943
14944    #[gpui::test]
14945    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14946        use settings::{ThemeName, ThemeSelection};
14947        use theme::SystemAppearance;
14948        use zed_actions::theme::ToggleMode;
14949
14950        init_test(cx);
14951
14952        let fs = FakeFs::new(cx.executor());
14953        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14954
14955        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14956            .await;
14957
14958        // Build a test project and workspace view so the test can invoke
14959        // the workspace action handler the same way the UI would.
14960        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14961        let (workspace, cx) =
14962            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14963
14964        // Seed the settings file with a plain static light theme so the
14965        // first toggle always starts from a known persisted state.
14966        workspace.update_in(cx, |_workspace, _window, cx| {
14967            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14968            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14969                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14970            });
14971        });
14972        cx.executor().advance_clock(Duration::from_millis(200));
14973        cx.run_until_parked();
14974
14975        // Confirm the initial persisted settings contain the static theme
14976        // we just wrote before any toggling happens.
14977        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14978        assert!(settings_text.contains(r#""theme": "One Light""#));
14979
14980        // Toggle once. This should migrate the persisted theme settings
14981        // into light/dark slots and enable system mode.
14982        workspace.update_in(cx, |workspace, window, cx| {
14983            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14984        });
14985        cx.executor().advance_clock(Duration::from_millis(200));
14986        cx.run_until_parked();
14987
14988        // 1. Static -> Dynamic
14989        // this assertion checks theme changed from static to dynamic.
14990        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14991        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14992        assert_eq!(
14993            parsed["theme"],
14994            serde_json::json!({
14995                "mode": "system",
14996                "light": "One Light",
14997                "dark": "One Dark"
14998            })
14999        );
15000
15001        // 2. Toggle again, suppose it will change the mode to light
15002        workspace.update_in(cx, |workspace, window, cx| {
15003            workspace.toggle_theme_mode(&ToggleMode, window, cx);
15004        });
15005        cx.executor().advance_clock(Duration::from_millis(200));
15006        cx.run_until_parked();
15007
15008        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
15009        assert!(settings_text.contains(r#""mode": "light""#));
15010    }
15011
15012    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
15013        let item = TestProjectItem::new(id, path, cx);
15014        item.update(cx, |item, _| {
15015            item.is_dirty = true;
15016        });
15017        item
15018    }
15019
15020    #[gpui::test]
15021    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
15022        cx: &mut gpui::TestAppContext,
15023    ) {
15024        init_test(cx);
15025        let fs = FakeFs::new(cx.executor());
15026
15027        let project = Project::test(fs, [], cx).await;
15028        let (workspace, cx) =
15029            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
15030
15031        let panel = workspace.update_in(cx, |workspace, window, cx| {
15032            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
15033            workspace.add_panel(panel.clone(), window, cx);
15034            workspace
15035                .right_dock()
15036                .update(cx, |dock, cx| dock.set_open(true, window, cx));
15037            panel
15038        });
15039
15040        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
15041        pane.update_in(cx, |pane, window, cx| {
15042            let item = cx.new(TestItem::new);
15043            pane.add_item(Box::new(item), true, true, None, window, cx);
15044        });
15045
15046        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
15047        // mirrors the real-world flow and avoids side effects from directly
15048        // focusing the panel while the center pane is active.
15049        workspace.update_in(cx, |workspace, window, cx| {
15050            workspace.toggle_panel_focus::<TestPanel>(window, cx);
15051        });
15052
15053        panel.update_in(cx, |panel, window, cx| {
15054            panel.set_zoomed(true, window, cx);
15055        });
15056
15057        workspace.update_in(cx, |workspace, window, cx| {
15058            assert!(workspace.right_dock().read(cx).is_open());
15059            assert!(panel.is_zoomed(window, cx));
15060            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
15061        });
15062
15063        // Simulate a spurious pane::Event::Focus on the center pane while the
15064        // panel still has focus. This mirrors what happens during macOS window
15065        // activation: the center pane fires a focus event even though actual
15066        // focus remains on the dock panel.
15067        pane.update_in(cx, |_, _, cx| {
15068            cx.emit(pane::Event::Focus);
15069        });
15070
15071        // The dock must remain open because the panel had focus at the time the
15072        // event was processed. Before the fix, dock_to_preserve was None for
15073        // panels that don't implement pane(), causing the dock to close.
15074        workspace.update_in(cx, |workspace, window, cx| {
15075            assert!(
15076                workspace.right_dock().read(cx).is_open(),
15077                "Dock should stay open when its zoomed panel (without pane()) still has focus"
15078            );
15079            assert!(panel.is_zoomed(window, cx));
15080        });
15081    }
15082
15083    #[gpui::test]
15084    async fn test_panels_stay_open_after_position_change_and_settings_update(
15085        cx: &mut gpui::TestAppContext,
15086    ) {
15087        init_test(cx);
15088        let fs = FakeFs::new(cx.executor());
15089        let project = Project::test(fs, [], cx).await;
15090        let (workspace, cx) =
15091            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
15092
15093        // Add two panels to the left dock and open it.
15094        let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
15095            let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
15096            let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
15097            workspace.add_panel(panel_a.clone(), window, cx);
15098            workspace.add_panel(panel_b.clone(), window, cx);
15099            workspace.left_dock().update(cx, |dock, cx| {
15100                dock.set_open(true, window, cx);
15101                dock.activate_panel(0, window, cx);
15102            });
15103            (panel_a, panel_b)
15104        });
15105
15106        workspace.update_in(cx, |workspace, _, cx| {
15107            assert!(workspace.left_dock().read(cx).is_open());
15108        });
15109
15110        // Simulate a feature flag changing default dock positions: both panels
15111        // move from Left to Right.
15112        workspace.update_in(cx, |_workspace, _window, cx| {
15113            panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
15114            panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
15115            cx.update_global::<SettingsStore, _>(|_, _| {});
15116        });
15117
15118        // Both panels should now be in the right dock.
15119        workspace.update_in(cx, |workspace, _, cx| {
15120            let right_dock = workspace.right_dock().read(cx);
15121            assert_eq!(right_dock.panels_len(), 2);
15122        });
15123
15124        // Open the right dock and activate panel_b (simulating the user
15125        // opening the panel after it moved).
15126        workspace.update_in(cx, |workspace, window, cx| {
15127            workspace.right_dock().update(cx, |dock, cx| {
15128                dock.set_open(true, window, cx);
15129                dock.activate_panel(1, window, cx);
15130            });
15131        });
15132
15133        // Now trigger another SettingsStore change
15134        workspace.update_in(cx, |_workspace, _window, cx| {
15135            cx.update_global::<SettingsStore, _>(|_, _| {});
15136        });
15137
15138        workspace.update_in(cx, |workspace, _, cx| {
15139            assert!(
15140                workspace.right_dock().read(cx).is_open(),
15141                "Right dock should still be open after a settings change"
15142            );
15143            assert_eq!(
15144                workspace.right_dock().read(cx).panels_len(),
15145                2,
15146                "Both panels should still be in the right dock"
15147            );
15148        });
15149    }
15150}