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, Sidebar,
   37    SidebarEvent, SidebarHandle, SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar,
   38    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 center_column_count = self.center_full_height_column_count();
 2306            let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2307            if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2308                let total_flex = flex + center_column_count + opposite_flex;
 2309                return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
 2310            } else {
 2311                let opposite_fixed = opposite
 2312                    .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2313                    .unwrap_or_default();
 2314                let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
 2315                return Some(
 2316                    (flex / (flex + center_column_count) * available).max(RESIZE_HANDLE_SIZE),
 2317                );
 2318            }
 2319        }
 2320
 2321        Some(
 2322            size_state
 2323                .size
 2324                .unwrap_or_else(|| panel.default_size(window, cx)),
 2325        )
 2326    }
 2327
 2328    pub fn dock_flex_for_size(
 2329        &self,
 2330        position: DockPosition,
 2331        size: Pixels,
 2332        window: &Window,
 2333        cx: &App,
 2334    ) -> Option<f32> {
 2335        if position.axis() != Axis::Horizontal {
 2336            return None;
 2337        }
 2338
 2339        let workspace_width = self.bounds.size.width;
 2340        if workspace_width <= Pixels::ZERO {
 2341            return None;
 2342        }
 2343
 2344        let center_column_count = self.center_full_height_column_count();
 2345        let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2346        if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2347            let size = size.clamp(px(0.), workspace_width - px(1.));
 2348            Some((size * (center_column_count + opposite_flex) / (workspace_width - size)).max(0.0))
 2349        } else {
 2350            let opposite_width = opposite
 2351                .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2352                .unwrap_or_default();
 2353            let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
 2354            let remaining = (available - size).max(px(1.));
 2355            Some((size * center_column_count / remaining).max(0.0))
 2356        }
 2357    }
 2358
 2359    fn opposite_dock_panel_and_size_state(
 2360        &self,
 2361        position: DockPosition,
 2362        window: &Window,
 2363        cx: &App,
 2364    ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
 2365        let opposite_position = match position {
 2366            DockPosition::Left => DockPosition::Right,
 2367            DockPosition::Right => DockPosition::Left,
 2368            DockPosition::Bottom => return None,
 2369        };
 2370
 2371        let opposite_dock = self.dock_at_position(opposite_position).read(cx);
 2372        let panel = opposite_dock.visible_panel()?;
 2373        let mut size_state = opposite_dock
 2374            .stored_panel_size_state(panel.as_ref())
 2375            .unwrap_or_default();
 2376        if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
 2377            size_state.flex = self.default_dock_flex(opposite_position);
 2378        }
 2379        Some((panel.clone(), size_state))
 2380    }
 2381
 2382    fn center_full_height_column_count(&self) -> f32 {
 2383        self.center.full_height_column_count().max(1) as f32
 2384    }
 2385
 2386    pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
 2387        if position.axis() != Axis::Horizontal {
 2388            return None;
 2389        }
 2390
 2391        Some(1.0)
 2392    }
 2393
 2394    pub fn is_edited(&self) -> bool {
 2395        self.window_edited
 2396    }
 2397
 2398    pub fn add_panel<T: Panel>(
 2399        &mut self,
 2400        panel: Entity<T>,
 2401        window: &mut Window,
 2402        cx: &mut Context<Self>,
 2403    ) {
 2404        let focus_handle = panel.panel_focus_handle(cx);
 2405        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2406            .detach();
 2407
 2408        let dock_position = panel.position(window, cx);
 2409        let dock = self.dock_at_position(dock_position);
 2410        let any_panel = panel.to_any();
 2411        let persisted_size_state =
 2412            self.persisted_panel_size_state(T::panel_key(), cx)
 2413                .or_else(|| {
 2414                    load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
 2415                        let state = dock::PanelSizeState {
 2416                            size: Some(size),
 2417                            flex: None,
 2418                        };
 2419                        self.persist_panel_size_state(T::panel_key(), state, cx);
 2420                        state
 2421                    })
 2422                });
 2423
 2424        dock.update(cx, |dock, cx| {
 2425            let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
 2426            if let Some(size_state) = persisted_size_state {
 2427                dock.set_panel_size_state(&panel, size_state, cx);
 2428            }
 2429            index
 2430        });
 2431
 2432        cx.emit(Event::PanelAdded(any_panel));
 2433    }
 2434
 2435    pub fn remove_panel<T: Panel>(
 2436        &mut self,
 2437        panel: &Entity<T>,
 2438        window: &mut Window,
 2439        cx: &mut Context<Self>,
 2440    ) {
 2441        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2442            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2443        }
 2444    }
 2445
 2446    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2447        &self.status_bar
 2448    }
 2449
 2450    pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
 2451        self.sidebar_focus_handle = handle;
 2452    }
 2453
 2454    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2455        StatusBarSettings::get_global(cx).show
 2456    }
 2457
 2458    pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
 2459        self.multi_workspace.as_ref()
 2460    }
 2461
 2462    pub fn set_multi_workspace(
 2463        &mut self,
 2464        multi_workspace: WeakEntity<MultiWorkspace>,
 2465        cx: &mut App,
 2466    ) {
 2467        self.status_bar.update(cx, |status_bar, cx| {
 2468            status_bar.set_multi_workspace(multi_workspace.clone(), cx);
 2469        });
 2470        self.multi_workspace = Some(multi_workspace);
 2471    }
 2472
 2473    pub fn app_state(&self) -> &Arc<AppState> {
 2474        &self.app_state
 2475    }
 2476
 2477    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2478        self._panels_task = Some(task);
 2479    }
 2480
 2481    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2482        self._panels_task.take()
 2483    }
 2484
 2485    pub fn user_store(&self) -> &Entity<UserStore> {
 2486        &self.app_state.user_store
 2487    }
 2488
 2489    pub fn project(&self) -> &Entity<Project> {
 2490        &self.project
 2491    }
 2492
 2493    pub fn path_style(&self, cx: &App) -> PathStyle {
 2494        self.project.read(cx).path_style(cx)
 2495    }
 2496
 2497    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2498        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2499
 2500        for pane_handle in &self.panes {
 2501            let pane = pane_handle.read(cx);
 2502
 2503            for entry in pane.activation_history() {
 2504                history.insert(
 2505                    entry.entity_id,
 2506                    history
 2507                        .get(&entry.entity_id)
 2508                        .cloned()
 2509                        .unwrap_or(0)
 2510                        .max(entry.timestamp),
 2511                );
 2512            }
 2513        }
 2514
 2515        history
 2516    }
 2517
 2518    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2519        let mut recent_item: Option<Entity<T>> = None;
 2520        let mut recent_timestamp = 0;
 2521        for pane_handle in &self.panes {
 2522            let pane = pane_handle.read(cx);
 2523            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2524                pane.items().map(|item| (item.item_id(), item)).collect();
 2525            for entry in pane.activation_history() {
 2526                if entry.timestamp > recent_timestamp
 2527                    && let Some(&item) = item_map.get(&entry.entity_id)
 2528                    && let Some(typed_item) = item.act_as::<T>(cx)
 2529                {
 2530                    recent_timestamp = entry.timestamp;
 2531                    recent_item = Some(typed_item);
 2532                }
 2533            }
 2534        }
 2535        recent_item
 2536    }
 2537
 2538    pub fn recent_navigation_history_iter(
 2539        &self,
 2540        cx: &App,
 2541    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2542        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2543        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2544
 2545        for pane in &self.panes {
 2546            let pane = pane.read(cx);
 2547
 2548            pane.nav_history()
 2549                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2550                    if let Some(fs_path) = &fs_path {
 2551                        abs_paths_opened
 2552                            .entry(fs_path.clone())
 2553                            .or_default()
 2554                            .insert(project_path.clone());
 2555                    }
 2556                    let timestamp = entry.timestamp;
 2557                    match history.entry(project_path) {
 2558                        hash_map::Entry::Occupied(mut entry) => {
 2559                            let (_, old_timestamp) = entry.get();
 2560                            if &timestamp > old_timestamp {
 2561                                entry.insert((fs_path, timestamp));
 2562                            }
 2563                        }
 2564                        hash_map::Entry::Vacant(entry) => {
 2565                            entry.insert((fs_path, timestamp));
 2566                        }
 2567                    }
 2568                });
 2569
 2570            if let Some(item) = pane.active_item()
 2571                && let Some(project_path) = item.project_path(cx)
 2572            {
 2573                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2574
 2575                if let Some(fs_path) = &fs_path {
 2576                    abs_paths_opened
 2577                        .entry(fs_path.clone())
 2578                        .or_default()
 2579                        .insert(project_path.clone());
 2580                }
 2581
 2582                history.insert(project_path, (fs_path, std::usize::MAX));
 2583            }
 2584        }
 2585
 2586        history
 2587            .into_iter()
 2588            .sorted_by_key(|(_, (_, order))| *order)
 2589            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2590            .rev()
 2591            .filter(move |(history_path, abs_path)| {
 2592                let latest_project_path_opened = abs_path
 2593                    .as_ref()
 2594                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2595                    .and_then(|project_paths| {
 2596                        project_paths
 2597                            .iter()
 2598                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2599                    });
 2600
 2601                latest_project_path_opened.is_none_or(|path| path == history_path)
 2602            })
 2603    }
 2604
 2605    pub fn recent_navigation_history(
 2606        &self,
 2607        limit: Option<usize>,
 2608        cx: &App,
 2609    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2610        self.recent_navigation_history_iter(cx)
 2611            .take(limit.unwrap_or(usize::MAX))
 2612            .collect()
 2613    }
 2614
 2615    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2616        for pane in &self.panes {
 2617            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2618        }
 2619    }
 2620
 2621    fn navigate_history(
 2622        &mut self,
 2623        pane: WeakEntity<Pane>,
 2624        mode: NavigationMode,
 2625        window: &mut Window,
 2626        cx: &mut Context<Workspace>,
 2627    ) -> Task<Result<()>> {
 2628        self.navigate_history_impl(
 2629            pane,
 2630            mode,
 2631            window,
 2632            &mut |history, cx| history.pop(mode, cx),
 2633            cx,
 2634        )
 2635    }
 2636
 2637    fn navigate_tag_history(
 2638        &mut self,
 2639        pane: WeakEntity<Pane>,
 2640        mode: TagNavigationMode,
 2641        window: &mut Window,
 2642        cx: &mut Context<Workspace>,
 2643    ) -> Task<Result<()>> {
 2644        self.navigate_history_impl(
 2645            pane,
 2646            NavigationMode::Normal,
 2647            window,
 2648            &mut |history, _cx| history.pop_tag(mode),
 2649            cx,
 2650        )
 2651    }
 2652
 2653    fn navigate_history_impl(
 2654        &mut self,
 2655        pane: WeakEntity<Pane>,
 2656        mode: NavigationMode,
 2657        window: &mut Window,
 2658        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2659        cx: &mut Context<Workspace>,
 2660    ) -> Task<Result<()>> {
 2661        let to_load = if let Some(pane) = pane.upgrade() {
 2662            pane.update(cx, |pane, cx| {
 2663                window.focus(&pane.focus_handle(cx), cx);
 2664                loop {
 2665                    // Retrieve the weak item handle from the history.
 2666                    let entry = cb(pane.nav_history_mut(), cx)?;
 2667
 2668                    // If the item is still present in this pane, then activate it.
 2669                    if let Some(index) = entry
 2670                        .item
 2671                        .upgrade()
 2672                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2673                    {
 2674                        let prev_active_item_index = pane.active_item_index();
 2675                        pane.nav_history_mut().set_mode(mode);
 2676                        pane.activate_item(index, true, true, window, cx);
 2677                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2678
 2679                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2680                        if let Some(data) = entry.data {
 2681                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2682                        }
 2683
 2684                        if navigated {
 2685                            break None;
 2686                        }
 2687                    } else {
 2688                        // If the item is no longer present in this pane, then retrieve its
 2689                        // path info in order to reopen it.
 2690                        break pane
 2691                            .nav_history()
 2692                            .path_for_item(entry.item.id())
 2693                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2694                    }
 2695                }
 2696            })
 2697        } else {
 2698            None
 2699        };
 2700
 2701        if let Some((project_path, abs_path, entry)) = to_load {
 2702            // If the item was no longer present, then load it again from its previous path, first try the local path
 2703            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2704
 2705            cx.spawn_in(window, async move  |workspace, cx| {
 2706                let open_by_project_path = open_by_project_path.await;
 2707                let mut navigated = false;
 2708                match open_by_project_path
 2709                    .with_context(|| format!("Navigating to {project_path:?}"))
 2710                {
 2711                    Ok((project_entry_id, build_item)) => {
 2712                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2713                            pane.nav_history_mut().set_mode(mode);
 2714                            pane.active_item().map(|p| p.item_id())
 2715                        })?;
 2716
 2717                        pane.update_in(cx, |pane, window, cx| {
 2718                            let item = pane.open_item(
 2719                                project_entry_id,
 2720                                project_path,
 2721                                true,
 2722                                entry.is_preview,
 2723                                true,
 2724                                None,
 2725                                window, cx,
 2726                                build_item,
 2727                            );
 2728                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2729                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2730                            if let Some(data) = entry.data {
 2731                                navigated |= item.navigate(data, window, cx);
 2732                            }
 2733                        })?;
 2734                    }
 2735                    Err(open_by_project_path_e) => {
 2736                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2737                        // and its worktree is now dropped
 2738                        if let Some(abs_path) = abs_path {
 2739                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2740                                pane.nav_history_mut().set_mode(mode);
 2741                                pane.active_item().map(|p| p.item_id())
 2742                            })?;
 2743                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2744                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2745                            })?;
 2746                            match open_by_abs_path
 2747                                .await
 2748                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2749                            {
 2750                                Ok(item) => {
 2751                                    pane.update_in(cx, |pane, window, cx| {
 2752                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2753                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2754                                        if let Some(data) = entry.data {
 2755                                            navigated |= item.navigate(data, window, cx);
 2756                                        }
 2757                                    })?;
 2758                                }
 2759                                Err(open_by_abs_path_e) => {
 2760                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2761                                }
 2762                            }
 2763                        }
 2764                    }
 2765                }
 2766
 2767                if !navigated {
 2768                    workspace
 2769                        .update_in(cx, |workspace, window, cx| {
 2770                            Self::navigate_history(workspace, pane, mode, window, cx)
 2771                        })?
 2772                        .await?;
 2773                }
 2774
 2775                Ok(())
 2776            })
 2777        } else {
 2778            Task::ready(Ok(()))
 2779        }
 2780    }
 2781
 2782    pub fn go_back(
 2783        &mut self,
 2784        pane: WeakEntity<Pane>,
 2785        window: &mut Window,
 2786        cx: &mut Context<Workspace>,
 2787    ) -> Task<Result<()>> {
 2788        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2789    }
 2790
 2791    pub fn go_forward(
 2792        &mut self,
 2793        pane: WeakEntity<Pane>,
 2794        window: &mut Window,
 2795        cx: &mut Context<Workspace>,
 2796    ) -> Task<Result<()>> {
 2797        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2798    }
 2799
 2800    pub fn reopen_closed_item(
 2801        &mut self,
 2802        window: &mut Window,
 2803        cx: &mut Context<Workspace>,
 2804    ) -> Task<Result<()>> {
 2805        self.navigate_history(
 2806            self.active_pane().downgrade(),
 2807            NavigationMode::ReopeningClosedItem,
 2808            window,
 2809            cx,
 2810        )
 2811    }
 2812
 2813    pub fn client(&self) -> &Arc<Client> {
 2814        &self.app_state.client
 2815    }
 2816
 2817    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2818        self.titlebar_item = Some(item);
 2819        cx.notify();
 2820    }
 2821
 2822    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2823        self.on_prompt_for_new_path = Some(prompt)
 2824    }
 2825
 2826    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2827        self.on_prompt_for_open_path = Some(prompt)
 2828    }
 2829
 2830    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2831        self.terminal_provider = Some(Box::new(provider));
 2832    }
 2833
 2834    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2835        self.debugger_provider = Some(Arc::new(provider));
 2836    }
 2837
 2838    pub fn set_open_in_dev_container(&mut self, value: bool) {
 2839        self.open_in_dev_container = value;
 2840    }
 2841
 2842    pub fn open_in_dev_container(&self) -> bool {
 2843        self.open_in_dev_container
 2844    }
 2845
 2846    pub fn set_dev_container_task(&mut self, task: Task<Result<()>>) {
 2847        self._dev_container_task = Some(task);
 2848    }
 2849
 2850    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2851        self.debugger_provider.clone()
 2852    }
 2853
 2854    pub fn prompt_for_open_path(
 2855        &mut self,
 2856        path_prompt_options: PathPromptOptions,
 2857        lister: DirectoryLister,
 2858        window: &mut Window,
 2859        cx: &mut Context<Self>,
 2860    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2861        // TODO: If `on_prompt_for_open_path` is set, we should always use it
 2862        // rather than gating on `use_system_path_prompts`. This would let tests
 2863        // inject a mock without also having to disable the setting.
 2864        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2865            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2866            let rx = prompt(self, lister, window, cx);
 2867            self.on_prompt_for_open_path = Some(prompt);
 2868            rx
 2869        } else {
 2870            let (tx, rx) = oneshot::channel();
 2871            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2872
 2873            cx.spawn_in(window, async move |workspace, cx| {
 2874                let Ok(result) = abs_path.await else {
 2875                    return Ok(());
 2876                };
 2877
 2878                match result {
 2879                    Ok(result) => {
 2880                        tx.send(result).ok();
 2881                    }
 2882                    Err(err) => {
 2883                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2884                            workspace.show_portal_error(err.to_string(), cx);
 2885                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2886                            let rx = prompt(workspace, lister, window, cx);
 2887                            workspace.on_prompt_for_open_path = Some(prompt);
 2888                            rx
 2889                        })?;
 2890                        if let Ok(path) = rx.await {
 2891                            tx.send(path).ok();
 2892                        }
 2893                    }
 2894                };
 2895                anyhow::Ok(())
 2896            })
 2897            .detach();
 2898
 2899            rx
 2900        }
 2901    }
 2902
 2903    pub fn prompt_for_new_path(
 2904        &mut self,
 2905        lister: DirectoryLister,
 2906        suggested_name: Option<String>,
 2907        window: &mut Window,
 2908        cx: &mut Context<Self>,
 2909    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2910        if self.project.read(cx).is_via_collab()
 2911            || self.project.read(cx).is_via_remote_server()
 2912            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2913        {
 2914            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2915            let rx = prompt(self, lister, suggested_name, window, cx);
 2916            self.on_prompt_for_new_path = Some(prompt);
 2917            return rx;
 2918        }
 2919
 2920        let (tx, rx) = oneshot::channel();
 2921        cx.spawn_in(window, async move |workspace, cx| {
 2922            let abs_path = workspace.update(cx, |workspace, cx| {
 2923                let relative_to = workspace
 2924                    .most_recent_active_path(cx)
 2925                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2926                    .or_else(|| {
 2927                        let project = workspace.project.read(cx);
 2928                        project.visible_worktrees(cx).find_map(|worktree| {
 2929                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2930                        })
 2931                    })
 2932                    .or_else(std::env::home_dir)
 2933                    .unwrap_or_else(|| PathBuf::from(""));
 2934                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2935            })?;
 2936            let abs_path = match abs_path.await? {
 2937                Ok(path) => path,
 2938                Err(err) => {
 2939                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2940                        workspace.show_portal_error(err.to_string(), cx);
 2941
 2942                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2943                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2944                        workspace.on_prompt_for_new_path = Some(prompt);
 2945                        rx
 2946                    })?;
 2947                    if let Ok(path) = rx.await {
 2948                        tx.send(path).ok();
 2949                    }
 2950                    return anyhow::Ok(());
 2951                }
 2952            };
 2953
 2954            tx.send(abs_path.map(|path| vec![path])).ok();
 2955            anyhow::Ok(())
 2956        })
 2957        .detach();
 2958
 2959        rx
 2960    }
 2961
 2962    pub fn titlebar_item(&self) -> Option<AnyView> {
 2963        self.titlebar_item.clone()
 2964    }
 2965
 2966    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2967    ///
 2968    /// If the given workspace has a local project, then it will be passed
 2969    /// to the callback. Otherwise, a new empty window will be created.
 2970    pub fn with_local_workspace<T, F>(
 2971        &mut self,
 2972        window: &mut Window,
 2973        cx: &mut Context<Self>,
 2974        callback: F,
 2975    ) -> Task<Result<T>>
 2976    where
 2977        T: 'static,
 2978        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2979    {
 2980        if self.project.read(cx).is_local() {
 2981            Task::ready(Ok(callback(self, window, cx)))
 2982        } else {
 2983            let env = self.project.read(cx).cli_environment(cx);
 2984            let task = Self::new_local(
 2985                Vec::new(),
 2986                self.app_state.clone(),
 2987                None,
 2988                env,
 2989                None,
 2990                OpenMode::Activate,
 2991                cx,
 2992            );
 2993            cx.spawn_in(window, async move |_vh, cx| {
 2994                let OpenResult {
 2995                    window: multi_workspace_window,
 2996                    ..
 2997                } = task.await?;
 2998                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2999                    let workspace = multi_workspace.workspace().clone();
 3000                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 3001                })
 3002            })
 3003        }
 3004    }
 3005
 3006    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 3007    ///
 3008    /// If the given workspace has a local project, then it will be passed
 3009    /// to the callback. Otherwise, a new empty window will be created.
 3010    pub fn with_local_or_wsl_workspace<T, F>(
 3011        &mut self,
 3012        window: &mut Window,
 3013        cx: &mut Context<Self>,
 3014        callback: F,
 3015    ) -> Task<Result<T>>
 3016    where
 3017        T: 'static,
 3018        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 3019    {
 3020        let project = self.project.read(cx);
 3021        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 3022            Task::ready(Ok(callback(self, window, cx)))
 3023        } else {
 3024            let env = self.project.read(cx).cli_environment(cx);
 3025            let task = Self::new_local(
 3026                Vec::new(),
 3027                self.app_state.clone(),
 3028                None,
 3029                env,
 3030                None,
 3031                OpenMode::Activate,
 3032                cx,
 3033            );
 3034            cx.spawn_in(window, async move |_vh, cx| {
 3035                let OpenResult {
 3036                    window: multi_workspace_window,
 3037                    ..
 3038                } = task.await?;
 3039                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 3040                    let workspace = multi_workspace.workspace().clone();
 3041                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 3042                })
 3043            })
 3044        }
 3045    }
 3046
 3047    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3048        self.project.read(cx).worktrees(cx)
 3049    }
 3050
 3051    pub fn visible_worktrees<'a>(
 3052        &self,
 3053        cx: &'a App,
 3054    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3055        self.project.read(cx).visible_worktrees(cx)
 3056    }
 3057
 3058    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 3059        let futures = self
 3060            .worktrees(cx)
 3061            .filter_map(|worktree| worktree.read(cx).as_local())
 3062            .map(|worktree| worktree.scan_complete())
 3063            .collect::<Vec<_>>();
 3064        async move {
 3065            for future in futures {
 3066                future.await;
 3067            }
 3068        }
 3069    }
 3070
 3071    pub fn close_global(cx: &mut App) {
 3072        cx.defer(|cx| {
 3073            cx.windows().iter().find(|window| {
 3074                window
 3075                    .update(cx, |_, window, _| {
 3076                        if window.is_window_active() {
 3077                            //This can only get called when the window's project connection has been lost
 3078                            //so we don't need to prompt the user for anything and instead just close the window
 3079                            window.remove_window();
 3080                            true
 3081                        } else {
 3082                            false
 3083                        }
 3084                    })
 3085                    .unwrap_or(false)
 3086            });
 3087        });
 3088    }
 3089
 3090    pub fn move_focused_panel_to_next_position(
 3091        &mut self,
 3092        _: &MoveFocusedPanelToNextPosition,
 3093        window: &mut Window,
 3094        cx: &mut Context<Self>,
 3095    ) {
 3096        let docks = self.all_docks();
 3097        let active_dock = docks
 3098            .into_iter()
 3099            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 3100
 3101        if let Some(dock) = active_dock {
 3102            dock.update(cx, |dock, cx| {
 3103                let active_panel = dock
 3104                    .active_panel()
 3105                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 3106
 3107                if let Some(panel) = active_panel {
 3108                    panel.move_to_next_position(window, cx);
 3109                }
 3110            })
 3111        }
 3112    }
 3113
 3114    pub fn prepare_to_close(
 3115        &mut self,
 3116        close_intent: CloseIntent,
 3117        window: &mut Window,
 3118        cx: &mut Context<Self>,
 3119    ) -> Task<Result<bool>> {
 3120        let active_call = self.active_global_call();
 3121
 3122        cx.spawn_in(window, async move |this, cx| {
 3123            this.update(cx, |this, _| {
 3124                if close_intent == CloseIntent::CloseWindow {
 3125                    this.removing = true;
 3126                }
 3127            })?;
 3128
 3129            let workspace_count = cx.update(|_window, cx| {
 3130                cx.windows()
 3131                    .iter()
 3132                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 3133                    .count()
 3134            })?;
 3135
 3136            #[cfg(target_os = "macos")]
 3137            let save_last_workspace = false;
 3138
 3139            // On Linux and Windows, closing the last window should restore the last workspace.
 3140            #[cfg(not(target_os = "macos"))]
 3141            let save_last_workspace = {
 3142                let remaining_workspaces = cx.update(|_window, cx| {
 3143                    cx.windows()
 3144                        .iter()
 3145                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 3146                        .filter_map(|multi_workspace| {
 3147                            multi_workspace
 3148                                .update(cx, |multi_workspace, _, cx| {
 3149                                    multi_workspace.workspace().read(cx).removing
 3150                                })
 3151                                .ok()
 3152                        })
 3153                        .filter(|removing| !removing)
 3154                        .count()
 3155                })?;
 3156
 3157                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 3158            };
 3159
 3160            if let Some(active_call) = active_call
 3161                && workspace_count == 1
 3162                && cx
 3163                    .update(|_window, cx| active_call.0.is_in_room(cx))
 3164                    .unwrap_or(false)
 3165            {
 3166                if close_intent == CloseIntent::CloseWindow {
 3167                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3168                    let answer = cx.update(|window, cx| {
 3169                        window.prompt(
 3170                            PromptLevel::Warning,
 3171                            "Do you want to leave the current call?",
 3172                            None,
 3173                            &["Close window and hang up", "Cancel"],
 3174                            cx,
 3175                        )
 3176                    })?;
 3177
 3178                    if answer.await.log_err() == Some(1) {
 3179                        return anyhow::Ok(false);
 3180                    } else {
 3181                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 3182                            task.await.log_err();
 3183                        }
 3184                    }
 3185                }
 3186                if close_intent == CloseIntent::ReplaceWindow {
 3187                    _ = cx.update(|_window, cx| {
 3188                        let multi_workspace = cx
 3189                            .windows()
 3190                            .iter()
 3191                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 3192                            .next()
 3193                            .unwrap();
 3194                        let project = multi_workspace
 3195                            .read(cx)?
 3196                            .workspace()
 3197                            .read(cx)
 3198                            .project
 3199                            .clone();
 3200                        if project.read(cx).is_shared() {
 3201                            active_call.0.unshare_project(project, cx)?;
 3202                        }
 3203                        Ok::<_, anyhow::Error>(())
 3204                    });
 3205                }
 3206            }
 3207
 3208            let save_result = this
 3209                .update_in(cx, |this, window, cx| {
 3210                    this.save_all_internal(SaveIntent::Close, window, cx)
 3211                })?
 3212                .await;
 3213
 3214            // If we're not quitting, but closing, we remove the workspace from
 3215            // the current session.
 3216            if close_intent != CloseIntent::Quit
 3217                && !save_last_workspace
 3218                && save_result.as_ref().is_ok_and(|&res| res)
 3219            {
 3220                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 3221                    .await;
 3222            }
 3223
 3224            save_result
 3225        })
 3226    }
 3227
 3228    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 3229        self.save_all_internal(
 3230            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 3231            window,
 3232            cx,
 3233        )
 3234        .detach_and_log_err(cx);
 3235    }
 3236
 3237    fn send_keystrokes(
 3238        &mut self,
 3239        action: &SendKeystrokes,
 3240        window: &mut Window,
 3241        cx: &mut Context<Self>,
 3242    ) {
 3243        let keystrokes: Vec<Keystroke> = action
 3244            .0
 3245            .split(' ')
 3246            .flat_map(|k| Keystroke::parse(k).log_err())
 3247            .map(|k| {
 3248                cx.keyboard_mapper()
 3249                    .map_key_equivalent(k, false)
 3250                    .inner()
 3251                    .clone()
 3252            })
 3253            .collect();
 3254        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 3255    }
 3256
 3257    pub fn send_keystrokes_impl(
 3258        &mut self,
 3259        keystrokes: Vec<Keystroke>,
 3260        window: &mut Window,
 3261        cx: &mut Context<Self>,
 3262    ) -> Shared<Task<()>> {
 3263        let mut state = self.dispatching_keystrokes.borrow_mut();
 3264        if !state.dispatched.insert(keystrokes.clone()) {
 3265            cx.propagate();
 3266            return state.task.clone().unwrap();
 3267        }
 3268
 3269        state.queue.extend(keystrokes);
 3270
 3271        let keystrokes = self.dispatching_keystrokes.clone();
 3272        if state.task.is_none() {
 3273            state.task = Some(
 3274                window
 3275                    .spawn(cx, async move |cx| {
 3276                        // limit to 100 keystrokes to avoid infinite recursion.
 3277                        for _ in 0..100 {
 3278                            let keystroke = {
 3279                                let mut state = keystrokes.borrow_mut();
 3280                                let Some(keystroke) = state.queue.pop_front() else {
 3281                                    state.dispatched.clear();
 3282                                    state.task.take();
 3283                                    return;
 3284                                };
 3285                                keystroke
 3286                            };
 3287                            cx.update(|window, cx| {
 3288                                let focused = window.focused(cx);
 3289                                window.dispatch_keystroke(keystroke.clone(), cx);
 3290                                if window.focused(cx) != focused {
 3291                                    // dispatch_keystroke may cause the focus to change.
 3292                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3293                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 3294                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 3295                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3296                                    // )
 3297                                    window.draw(cx).clear();
 3298                                }
 3299                            })
 3300                            .ok();
 3301
 3302                            // Yield between synthetic keystrokes so deferred focus and
 3303                            // other effects can settle before dispatching the next key.
 3304                            yield_now().await;
 3305                        }
 3306
 3307                        *keystrokes.borrow_mut() = Default::default();
 3308                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3309                    })
 3310                    .shared(),
 3311            );
 3312        }
 3313        state.task.clone().unwrap()
 3314    }
 3315
 3316    /// Prompts the user to save or discard each dirty item, returning
 3317    /// `true` if they confirmed (saved/discarded everything) or `false`
 3318    /// if they cancelled. Used before removing worktree roots during
 3319    /// thread archival.
 3320    pub fn prompt_to_save_or_discard_dirty_items(
 3321        &mut self,
 3322        window: &mut Window,
 3323        cx: &mut Context<Self>,
 3324    ) -> Task<Result<bool>> {
 3325        self.save_all_internal(SaveIntent::Close, window, cx)
 3326    }
 3327
 3328    fn save_all_internal(
 3329        &mut self,
 3330        mut save_intent: SaveIntent,
 3331        window: &mut Window,
 3332        cx: &mut Context<Self>,
 3333    ) -> Task<Result<bool>> {
 3334        if self.project.read(cx).is_disconnected(cx) {
 3335            return Task::ready(Ok(true));
 3336        }
 3337        let dirty_items = self
 3338            .panes
 3339            .iter()
 3340            .flat_map(|pane| {
 3341                pane.read(cx).items().filter_map(|item| {
 3342                    if item.is_dirty(cx) {
 3343                        item.tab_content_text(0, cx);
 3344                        Some((pane.downgrade(), item.boxed_clone()))
 3345                    } else {
 3346                        None
 3347                    }
 3348                })
 3349            })
 3350            .collect::<Vec<_>>();
 3351
 3352        let project = self.project.clone();
 3353        cx.spawn_in(window, async move |workspace, cx| {
 3354            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3355                let (serialize_tasks, remaining_dirty_items) =
 3356                    workspace.update_in(cx, |workspace, window, cx| {
 3357                        let mut remaining_dirty_items = Vec::new();
 3358                        let mut serialize_tasks = Vec::new();
 3359                        for (pane, item) in dirty_items {
 3360                            if let Some(task) = item
 3361                                .to_serializable_item_handle(cx)
 3362                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3363                            {
 3364                                serialize_tasks.push(task);
 3365                            } else {
 3366                                remaining_dirty_items.push((pane, item));
 3367                            }
 3368                        }
 3369                        (serialize_tasks, remaining_dirty_items)
 3370                    })?;
 3371
 3372                futures::future::try_join_all(serialize_tasks).await?;
 3373
 3374                if !remaining_dirty_items.is_empty() {
 3375                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3376                }
 3377
 3378                if remaining_dirty_items.len() > 1 {
 3379                    let answer = workspace.update_in(cx, |_, window, cx| {
 3380                        cx.emit(Event::Activate);
 3381                        let detail = Pane::file_names_for_prompt(
 3382                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3383                            cx,
 3384                        );
 3385                        window.prompt(
 3386                            PromptLevel::Warning,
 3387                            "Do you want to save all changes in the following files?",
 3388                            Some(&detail),
 3389                            &["Save all", "Discard all", "Cancel"],
 3390                            cx,
 3391                        )
 3392                    })?;
 3393                    match answer.await.log_err() {
 3394                        Some(0) => save_intent = SaveIntent::SaveAll,
 3395                        Some(1) => save_intent = SaveIntent::Skip,
 3396                        Some(2) => return Ok(false),
 3397                        _ => {}
 3398                    }
 3399                }
 3400
 3401                remaining_dirty_items
 3402            } else {
 3403                dirty_items
 3404            };
 3405
 3406            for (pane, item) in dirty_items {
 3407                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3408                    (
 3409                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3410                        item.project_entry_ids(cx),
 3411                    )
 3412                })?;
 3413                if (singleton || !project_entry_ids.is_empty())
 3414                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3415                {
 3416                    return Ok(false);
 3417                }
 3418            }
 3419            Ok(true)
 3420        })
 3421    }
 3422
 3423    pub fn open_workspace_for_paths(
 3424        &mut self,
 3425        // replace_current_window: bool,
 3426        mut open_mode: OpenMode,
 3427        paths: Vec<PathBuf>,
 3428        window: &mut Window,
 3429        cx: &mut Context<Self>,
 3430    ) -> Task<Result<Entity<Workspace>>> {
 3431        let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
 3432        let is_remote = self.project.read(cx).is_via_collab();
 3433        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3434        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3435
 3436        let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
 3437        if workspace_is_empty {
 3438            open_mode = OpenMode::Activate;
 3439        }
 3440
 3441        let app_state = self.app_state.clone();
 3442
 3443        cx.spawn(async move |_, cx| {
 3444            let OpenResult { workspace, .. } = cx
 3445                .update(|cx| {
 3446                    open_paths(
 3447                        &paths,
 3448                        app_state,
 3449                        OpenOptions {
 3450                            requesting_window,
 3451                            open_mode,
 3452                            ..Default::default()
 3453                        },
 3454                        cx,
 3455                    )
 3456                })
 3457                .await?;
 3458            Ok(workspace)
 3459        })
 3460    }
 3461
 3462    #[allow(clippy::type_complexity)]
 3463    pub fn open_paths(
 3464        &mut self,
 3465        mut abs_paths: Vec<PathBuf>,
 3466        options: OpenOptions,
 3467        pane: Option<WeakEntity<Pane>>,
 3468        window: &mut Window,
 3469        cx: &mut Context<Self>,
 3470    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3471        let fs = self.app_state.fs.clone();
 3472
 3473        let caller_ordered_abs_paths = abs_paths.clone();
 3474
 3475        // Sort the paths to ensure we add worktrees for parents before their children.
 3476        abs_paths.sort_unstable();
 3477        cx.spawn_in(window, async move |this, cx| {
 3478            let mut tasks = Vec::with_capacity(abs_paths.len());
 3479
 3480            for abs_path in &abs_paths {
 3481                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3482                    OpenVisible::All => Some(true),
 3483                    OpenVisible::None => Some(false),
 3484                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3485                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3486                        Some(None) => Some(true),
 3487                        None => None,
 3488                    },
 3489                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3490                        Some(Some(metadata)) => Some(metadata.is_dir),
 3491                        Some(None) => Some(false),
 3492                        None => None,
 3493                    },
 3494                };
 3495                let project_path = match visible {
 3496                    Some(visible) => match this
 3497                        .update(cx, |this, cx| {
 3498                            Workspace::project_path_for_path(
 3499                                this.project.clone(),
 3500                                abs_path,
 3501                                visible,
 3502                                cx,
 3503                            )
 3504                        })
 3505                        .log_err()
 3506                    {
 3507                        Some(project_path) => project_path.await.log_err(),
 3508                        None => None,
 3509                    },
 3510                    None => None,
 3511                };
 3512
 3513                let this = this.clone();
 3514                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3515                let fs = fs.clone();
 3516                let pane = pane.clone();
 3517                let task = cx.spawn(async move |cx| {
 3518                    let (_worktree, project_path) = project_path?;
 3519                    if fs.is_dir(&abs_path).await {
 3520                        // Opening a directory should not race to update the active entry.
 3521                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3522                        None
 3523                    } else {
 3524                        Some(
 3525                            this.update_in(cx, |this, window, cx| {
 3526                                this.open_path(
 3527                                    project_path,
 3528                                    pane,
 3529                                    options.focus.unwrap_or(true),
 3530                                    window,
 3531                                    cx,
 3532                                )
 3533                            })
 3534                            .ok()?
 3535                            .await,
 3536                        )
 3537                    }
 3538                });
 3539                tasks.push(task);
 3540            }
 3541
 3542            let results = futures::future::join_all(tasks).await;
 3543
 3544            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3545            let mut winner: Option<(PathBuf, bool)> = None;
 3546            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3547                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3548                    if !metadata.is_dir {
 3549                        winner = Some((abs_path, false));
 3550                        break;
 3551                    }
 3552                    if winner.is_none() {
 3553                        winner = Some((abs_path, true));
 3554                    }
 3555                } else if winner.is_none() {
 3556                    winner = Some((abs_path, false));
 3557                }
 3558            }
 3559
 3560            // Compute the winner entry id on the foreground thread and emit once, after all
 3561            // paths finish opening. This avoids races between concurrently-opening paths
 3562            // (directories in particular) and makes the resulting project panel selection
 3563            // deterministic.
 3564            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3565                'emit_winner: {
 3566                    let winner_abs_path: Arc<Path> =
 3567                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3568
 3569                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3570                        OpenVisible::All => true,
 3571                        OpenVisible::None => false,
 3572                        OpenVisible::OnlyFiles => !winner_is_dir,
 3573                        OpenVisible::OnlyDirectories => winner_is_dir,
 3574                    };
 3575
 3576                    let Some(worktree_task) = this
 3577                        .update(cx, |workspace, cx| {
 3578                            workspace.project.update(cx, |project, cx| {
 3579                                project.find_or_create_worktree(
 3580                                    winner_abs_path.as_ref(),
 3581                                    visible,
 3582                                    cx,
 3583                                )
 3584                            })
 3585                        })
 3586                        .ok()
 3587                    else {
 3588                        break 'emit_winner;
 3589                    };
 3590
 3591                    let Ok((worktree, _)) = worktree_task.await else {
 3592                        break 'emit_winner;
 3593                    };
 3594
 3595                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3596                        let worktree = worktree.read(cx);
 3597                        let worktree_abs_path = worktree.abs_path();
 3598                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3599                            worktree.root_entry()
 3600                        } else {
 3601                            winner_abs_path
 3602                                .strip_prefix(worktree_abs_path.as_ref())
 3603                                .ok()
 3604                                .and_then(|relative_path| {
 3605                                    let relative_path =
 3606                                        RelPath::new(relative_path, PathStyle::local())
 3607                                            .log_err()?;
 3608                                    worktree.entry_for_path(&relative_path)
 3609                                })
 3610                        }?;
 3611                        Some(entry.id)
 3612                    }) else {
 3613                        break 'emit_winner;
 3614                    };
 3615
 3616                    this.update(cx, |workspace, cx| {
 3617                        workspace.project.update(cx, |_, cx| {
 3618                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3619                        });
 3620                    })
 3621                    .ok();
 3622                }
 3623            }
 3624
 3625            results
 3626        })
 3627    }
 3628
 3629    pub fn open_resolved_path(
 3630        &mut self,
 3631        path: ResolvedPath,
 3632        window: &mut Window,
 3633        cx: &mut Context<Self>,
 3634    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3635        match path {
 3636            ResolvedPath::ProjectPath { project_path, .. } => {
 3637                self.open_path(project_path, None, true, window, cx)
 3638            }
 3639            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3640                PathBuf::from(path),
 3641                OpenOptions {
 3642                    visible: Some(OpenVisible::None),
 3643                    ..Default::default()
 3644                },
 3645                window,
 3646                cx,
 3647            ),
 3648        }
 3649    }
 3650
 3651    pub fn absolute_path_of_worktree(
 3652        &self,
 3653        worktree_id: WorktreeId,
 3654        cx: &mut Context<Self>,
 3655    ) -> Option<PathBuf> {
 3656        self.project
 3657            .read(cx)
 3658            .worktree_for_id(worktree_id, cx)
 3659            // TODO: use `abs_path` or `root_dir`
 3660            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3661    }
 3662
 3663    pub fn add_folder_to_project(
 3664        &mut self,
 3665        _: &AddFolderToProject,
 3666        window: &mut Window,
 3667        cx: &mut Context<Self>,
 3668    ) {
 3669        let project = self.project.read(cx);
 3670        if project.is_via_collab() {
 3671            self.show_error(
 3672                &anyhow!("You cannot add folders to someone else's project"),
 3673                cx,
 3674            );
 3675            return;
 3676        }
 3677        let paths = self.prompt_for_open_path(
 3678            PathPromptOptions {
 3679                files: false,
 3680                directories: true,
 3681                multiple: true,
 3682                prompt: None,
 3683            },
 3684            DirectoryLister::Project(self.project.clone()),
 3685            window,
 3686            cx,
 3687        );
 3688        cx.spawn_in(window, async move |this, cx| {
 3689            if let Some(paths) = paths.await.log_err().flatten() {
 3690                let results = this
 3691                    .update_in(cx, |this, window, cx| {
 3692                        this.open_paths(
 3693                            paths,
 3694                            OpenOptions {
 3695                                visible: Some(OpenVisible::All),
 3696                                ..Default::default()
 3697                            },
 3698                            None,
 3699                            window,
 3700                            cx,
 3701                        )
 3702                    })?
 3703                    .await;
 3704                for result in results.into_iter().flatten() {
 3705                    result.log_err();
 3706                }
 3707            }
 3708            anyhow::Ok(())
 3709        })
 3710        .detach_and_log_err(cx);
 3711    }
 3712
 3713    pub fn project_path_for_path(
 3714        project: Entity<Project>,
 3715        abs_path: &Path,
 3716        visible: bool,
 3717        cx: &mut App,
 3718    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3719        let entry = project.update(cx, |project, cx| {
 3720            project.find_or_create_worktree(abs_path, visible, cx)
 3721        });
 3722        cx.spawn(async move |cx| {
 3723            let (worktree, path) = entry.await?;
 3724            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3725            Ok((worktree, ProjectPath { worktree_id, path }))
 3726        })
 3727    }
 3728
 3729    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3730        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3731    }
 3732
 3733    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3734        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3735    }
 3736
 3737    pub fn items_of_type<'a, T: Item>(
 3738        &'a self,
 3739        cx: &'a App,
 3740    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3741        self.panes
 3742            .iter()
 3743            .flat_map(|pane| pane.read(cx).items_of_type())
 3744    }
 3745
 3746    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3747        self.active_pane().read(cx).active_item()
 3748    }
 3749
 3750    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3751        let item = self.active_item(cx)?;
 3752        item.to_any_view().downcast::<I>().ok()
 3753    }
 3754
 3755    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3756        self.active_item(cx).and_then(|item| item.project_path(cx))
 3757    }
 3758
 3759    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3760        self.recent_navigation_history_iter(cx)
 3761            .filter_map(|(path, abs_path)| {
 3762                let worktree = self
 3763                    .project
 3764                    .read(cx)
 3765                    .worktree_for_id(path.worktree_id, cx)?;
 3766                if worktree.read(cx).is_visible() {
 3767                    abs_path
 3768                } else {
 3769                    None
 3770                }
 3771            })
 3772            .next()
 3773    }
 3774
 3775    pub fn save_active_item(
 3776        &mut self,
 3777        save_intent: SaveIntent,
 3778        window: &mut Window,
 3779        cx: &mut App,
 3780    ) -> Task<Result<()>> {
 3781        let project = self.project.clone();
 3782        let pane = self.active_pane();
 3783        let item = pane.read(cx).active_item();
 3784        let pane = pane.downgrade();
 3785
 3786        window.spawn(cx, async move |cx| {
 3787            if let Some(item) = item {
 3788                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3789                    .await
 3790                    .map(|_| ())
 3791            } else {
 3792                Ok(())
 3793            }
 3794        })
 3795    }
 3796
 3797    pub fn close_inactive_items_and_panes(
 3798        &mut self,
 3799        action: &CloseInactiveTabsAndPanes,
 3800        window: &mut Window,
 3801        cx: &mut Context<Self>,
 3802    ) {
 3803        if let Some(task) = self.close_all_internal(
 3804            true,
 3805            action.save_intent.unwrap_or(SaveIntent::Close),
 3806            window,
 3807            cx,
 3808        ) {
 3809            task.detach_and_log_err(cx)
 3810        }
 3811    }
 3812
 3813    pub fn close_all_items_and_panes(
 3814        &mut self,
 3815        action: &CloseAllItemsAndPanes,
 3816        window: &mut Window,
 3817        cx: &mut Context<Self>,
 3818    ) {
 3819        if let Some(task) = self.close_all_internal(
 3820            false,
 3821            action.save_intent.unwrap_or(SaveIntent::Close),
 3822            window,
 3823            cx,
 3824        ) {
 3825            task.detach_and_log_err(cx)
 3826        }
 3827    }
 3828
 3829    /// Closes the active item across all panes.
 3830    pub fn close_item_in_all_panes(
 3831        &mut self,
 3832        action: &CloseItemInAllPanes,
 3833        window: &mut Window,
 3834        cx: &mut Context<Self>,
 3835    ) {
 3836        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3837            return;
 3838        };
 3839
 3840        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3841        let close_pinned = action.close_pinned;
 3842
 3843        if let Some(project_path) = active_item.project_path(cx) {
 3844            self.close_items_with_project_path(
 3845                &project_path,
 3846                save_intent,
 3847                close_pinned,
 3848                window,
 3849                cx,
 3850            );
 3851        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3852            let item_id = active_item.item_id();
 3853            self.active_pane().update(cx, |pane, cx| {
 3854                pane.close_item_by_id(item_id, save_intent, window, cx)
 3855                    .detach_and_log_err(cx);
 3856            });
 3857        }
 3858    }
 3859
 3860    /// Closes all items with the given project path across all panes.
 3861    pub fn close_items_with_project_path(
 3862        &mut self,
 3863        project_path: &ProjectPath,
 3864        save_intent: SaveIntent,
 3865        close_pinned: bool,
 3866        window: &mut Window,
 3867        cx: &mut Context<Self>,
 3868    ) {
 3869        let panes = self.panes().to_vec();
 3870        for pane in panes {
 3871            pane.update(cx, |pane, cx| {
 3872                pane.close_items_for_project_path(
 3873                    project_path,
 3874                    save_intent,
 3875                    close_pinned,
 3876                    window,
 3877                    cx,
 3878                )
 3879                .detach_and_log_err(cx);
 3880            });
 3881        }
 3882    }
 3883
 3884    fn close_all_internal(
 3885        &mut self,
 3886        retain_active_pane: bool,
 3887        save_intent: SaveIntent,
 3888        window: &mut Window,
 3889        cx: &mut Context<Self>,
 3890    ) -> Option<Task<Result<()>>> {
 3891        let current_pane = self.active_pane();
 3892
 3893        let mut tasks = Vec::new();
 3894
 3895        if retain_active_pane {
 3896            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3897                pane.close_other_items(
 3898                    &CloseOtherItems {
 3899                        save_intent: None,
 3900                        close_pinned: false,
 3901                    },
 3902                    None,
 3903                    window,
 3904                    cx,
 3905                )
 3906            });
 3907
 3908            tasks.push(current_pane_close);
 3909        }
 3910
 3911        for pane in self.panes() {
 3912            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3913                continue;
 3914            }
 3915
 3916            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3917                pane.close_all_items(
 3918                    &CloseAllItems {
 3919                        save_intent: Some(save_intent),
 3920                        close_pinned: false,
 3921                    },
 3922                    window,
 3923                    cx,
 3924                )
 3925            });
 3926
 3927            tasks.push(close_pane_items)
 3928        }
 3929
 3930        if tasks.is_empty() {
 3931            None
 3932        } else {
 3933            Some(cx.spawn_in(window, async move |_, _| {
 3934                for task in tasks {
 3935                    task.await?
 3936                }
 3937                Ok(())
 3938            }))
 3939        }
 3940    }
 3941
 3942    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3943        self.dock_at_position(position).read(cx).is_open()
 3944    }
 3945
 3946    pub fn toggle_dock(
 3947        &mut self,
 3948        dock_side: DockPosition,
 3949        window: &mut Window,
 3950        cx: &mut Context<Self>,
 3951    ) {
 3952        let mut focus_center = false;
 3953        let mut reveal_dock = false;
 3954
 3955        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3956        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3957
 3958        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3959            telemetry::event!(
 3960                "Panel Button Clicked",
 3961                name = panel.persistent_name(),
 3962                toggle_state = !was_visible
 3963            );
 3964        }
 3965        if was_visible {
 3966            self.save_open_dock_positions(cx);
 3967        }
 3968
 3969        let dock = self.dock_at_position(dock_side);
 3970        dock.update(cx, |dock, cx| {
 3971            dock.set_open(!was_visible, window, cx);
 3972
 3973            if dock.active_panel().is_none() {
 3974                let Some(panel_ix) = dock
 3975                    .first_enabled_panel_idx(cx)
 3976                    .log_with_level(log::Level::Info)
 3977                else {
 3978                    return;
 3979                };
 3980                dock.activate_panel(panel_ix, window, cx);
 3981            }
 3982
 3983            if let Some(active_panel) = dock.active_panel() {
 3984                if was_visible {
 3985                    if active_panel
 3986                        .panel_focus_handle(cx)
 3987                        .contains_focused(window, cx)
 3988                    {
 3989                        focus_center = true;
 3990                    }
 3991                } else {
 3992                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3993                    window.focus(focus_handle, cx);
 3994                    reveal_dock = true;
 3995                }
 3996            }
 3997        });
 3998
 3999        if reveal_dock {
 4000            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 4001        }
 4002
 4003        if focus_center {
 4004            self.active_pane
 4005                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4006        }
 4007
 4008        cx.notify();
 4009        self.serialize_workspace(window, cx);
 4010    }
 4011
 4012    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 4013        self.all_docks().into_iter().find(|&dock| {
 4014            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 4015        })
 4016    }
 4017
 4018    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 4019        if let Some(dock) = self.active_dock(window, cx).cloned() {
 4020            self.save_open_dock_positions(cx);
 4021            dock.update(cx, |dock, cx| {
 4022                dock.set_open(false, window, cx);
 4023            });
 4024            return true;
 4025        }
 4026        false
 4027    }
 4028
 4029    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4030        self.save_open_dock_positions(cx);
 4031        for dock in self.all_docks() {
 4032            dock.update(cx, |dock, cx| {
 4033                dock.set_open(false, window, cx);
 4034            });
 4035        }
 4036
 4037        cx.focus_self(window);
 4038        cx.notify();
 4039        self.serialize_workspace(window, cx);
 4040    }
 4041
 4042    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 4043        self.all_docks()
 4044            .into_iter()
 4045            .filter_map(|dock| {
 4046                let dock_ref = dock.read(cx);
 4047                if dock_ref.is_open() {
 4048                    Some(dock_ref.position())
 4049                } else {
 4050                    None
 4051                }
 4052            })
 4053            .collect()
 4054    }
 4055
 4056    /// Saves the positions of currently open docks.
 4057    ///
 4058    /// Updates `last_open_dock_positions` with positions of all currently open
 4059    /// docks, to later be restored by the 'Toggle All Docks' action.
 4060    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 4061        let open_dock_positions = self.get_open_dock_positions(cx);
 4062        if !open_dock_positions.is_empty() {
 4063            self.last_open_dock_positions = open_dock_positions;
 4064        }
 4065    }
 4066
 4067    /// Toggles all docks between open and closed states.
 4068    ///
 4069    /// If any docks are open, closes all and remembers their positions. If all
 4070    /// docks are closed, restores the last remembered dock configuration.
 4071    fn toggle_all_docks(
 4072        &mut self,
 4073        _: &ToggleAllDocks,
 4074        window: &mut Window,
 4075        cx: &mut Context<Self>,
 4076    ) {
 4077        let open_dock_positions = self.get_open_dock_positions(cx);
 4078
 4079        if !open_dock_positions.is_empty() {
 4080            self.close_all_docks(window, cx);
 4081        } else if !self.last_open_dock_positions.is_empty() {
 4082            self.restore_last_open_docks(window, cx);
 4083        }
 4084    }
 4085
 4086    /// Reopens docks from the most recently remembered configuration.
 4087    ///
 4088    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 4089    /// and clears the stored positions.
 4090    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4091        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 4092
 4093        for position in positions_to_open {
 4094            let dock = self.dock_at_position(position);
 4095            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 4096        }
 4097
 4098        cx.focus_self(window);
 4099        cx.notify();
 4100        self.serialize_workspace(window, cx);
 4101    }
 4102
 4103    /// Transfer focus to the panel of the given type.
 4104    pub fn focus_panel<T: Panel>(
 4105        &mut self,
 4106        window: &mut Window,
 4107        cx: &mut Context<Self>,
 4108    ) -> Option<Entity<T>> {
 4109        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 4110        panel.to_any().downcast().ok()
 4111    }
 4112
 4113    /// Focus the panel of the given type if it isn't already focused. If it is
 4114    /// already focused, then transfer focus back to the workspace center.
 4115    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 4116    /// panel when transferring focus back to the center.
 4117    pub fn toggle_panel_focus<T: Panel>(
 4118        &mut self,
 4119        window: &mut Window,
 4120        cx: &mut Context<Self>,
 4121    ) -> bool {
 4122        let mut did_focus_panel = false;
 4123        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 4124            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 4125            did_focus_panel
 4126        });
 4127
 4128        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 4129            self.close_panel::<T>(window, cx);
 4130        }
 4131
 4132        telemetry::event!(
 4133            "Panel Button Clicked",
 4134            name = T::persistent_name(),
 4135            toggle_state = did_focus_panel
 4136        );
 4137
 4138        did_focus_panel
 4139    }
 4140
 4141    pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4142        if let Some(item) = self.active_item(cx) {
 4143            item.item_focus_handle(cx).focus(window, cx);
 4144        } else {
 4145            log::error!("Could not find a focus target when switching focus to the center panes",);
 4146        }
 4147    }
 4148
 4149    pub fn activate_panel_for_proto_id(
 4150        &mut self,
 4151        panel_id: PanelId,
 4152        window: &mut Window,
 4153        cx: &mut Context<Self>,
 4154    ) -> Option<Arc<dyn PanelHandle>> {
 4155        let mut panel = None;
 4156        for dock in self.all_docks() {
 4157            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 4158                panel = dock.update(cx, |dock, cx| {
 4159                    dock.activate_panel(panel_index, window, cx);
 4160                    dock.set_open(true, window, cx);
 4161                    dock.active_panel().cloned()
 4162                });
 4163                break;
 4164            }
 4165        }
 4166
 4167        if panel.is_some() {
 4168            cx.notify();
 4169            self.serialize_workspace(window, cx);
 4170        }
 4171
 4172        panel
 4173    }
 4174
 4175    /// Focus or unfocus the given panel type, depending on the given callback.
 4176    fn focus_or_unfocus_panel<T: Panel>(
 4177        &mut self,
 4178        window: &mut Window,
 4179        cx: &mut Context<Self>,
 4180        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 4181    ) -> Option<Arc<dyn PanelHandle>> {
 4182        let mut result_panel = None;
 4183        let mut serialize = false;
 4184        for dock in self.all_docks() {
 4185            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4186                let mut focus_center = false;
 4187                let panel = dock.update(cx, |dock, cx| {
 4188                    dock.activate_panel(panel_index, window, cx);
 4189
 4190                    let panel = dock.active_panel().cloned();
 4191                    if let Some(panel) = panel.as_ref() {
 4192                        if should_focus(&**panel, window, cx) {
 4193                            dock.set_open(true, window, cx);
 4194                            panel.panel_focus_handle(cx).focus(window, cx);
 4195                        } else {
 4196                            focus_center = true;
 4197                        }
 4198                    }
 4199                    panel
 4200                });
 4201
 4202                if focus_center {
 4203                    self.active_pane
 4204                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4205                }
 4206
 4207                result_panel = panel;
 4208                serialize = true;
 4209                break;
 4210            }
 4211        }
 4212
 4213        if serialize {
 4214            self.serialize_workspace(window, cx);
 4215        }
 4216
 4217        cx.notify();
 4218        result_panel
 4219    }
 4220
 4221    /// Open the panel of the given type
 4222    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4223        for dock in self.all_docks() {
 4224            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4225                dock.update(cx, |dock, cx| {
 4226                    dock.activate_panel(panel_index, window, cx);
 4227                    dock.set_open(true, window, cx);
 4228                });
 4229            }
 4230        }
 4231    }
 4232
 4233    /// Open the panel of the given type, dismissing any zoomed items that
 4234    /// would obscure it (e.g. a zoomed terminal).
 4235    pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4236        let dock_position = self.all_docks().iter().find_map(|dock| {
 4237            let dock = dock.read(cx);
 4238            dock.panel_index_for_type::<T>().map(|_| dock.position())
 4239        });
 4240        self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
 4241        self.open_panel::<T>(window, cx);
 4242    }
 4243
 4244    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 4245        for dock in self.all_docks().iter() {
 4246            dock.update(cx, |dock, cx| {
 4247                if dock.panel::<T>().is_some() {
 4248                    dock.set_open(false, window, cx)
 4249                }
 4250            })
 4251        }
 4252    }
 4253
 4254    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 4255        self.all_docks()
 4256            .iter()
 4257            .find_map(|dock| dock.read(cx).panel::<T>())
 4258    }
 4259
 4260    fn dismiss_zoomed_items_to_reveal(
 4261        &mut self,
 4262        dock_to_reveal: Option<DockPosition>,
 4263        window: &mut Window,
 4264        cx: &mut Context<Self>,
 4265    ) {
 4266        // If a center pane is zoomed, unzoom it.
 4267        for pane in &self.panes {
 4268            if pane != &self.active_pane || dock_to_reveal.is_some() {
 4269                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4270            }
 4271        }
 4272
 4273        // If another dock is zoomed, hide it.
 4274        let mut focus_center = false;
 4275        for dock in self.all_docks() {
 4276            dock.update(cx, |dock, cx| {
 4277                if Some(dock.position()) != dock_to_reveal
 4278                    && let Some(panel) = dock.active_panel()
 4279                    && panel.is_zoomed(window, cx)
 4280                {
 4281                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 4282                    dock.set_open(false, window, cx);
 4283                }
 4284            });
 4285        }
 4286
 4287        if focus_center {
 4288            self.active_pane
 4289                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4290        }
 4291
 4292        if self.zoomed_position != dock_to_reveal {
 4293            self.zoomed = None;
 4294            self.zoomed_position = None;
 4295            cx.emit(Event::ZoomChanged);
 4296        }
 4297
 4298        cx.notify();
 4299    }
 4300
 4301    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4302        let pane = cx.new(|cx| {
 4303            let mut pane = Pane::new(
 4304                self.weak_handle(),
 4305                self.project.clone(),
 4306                self.pane_history_timestamp.clone(),
 4307                None,
 4308                NewFile.boxed_clone(),
 4309                true,
 4310                window,
 4311                cx,
 4312            );
 4313            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4314            pane
 4315        });
 4316        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4317            .detach();
 4318        self.panes.push(pane.clone());
 4319
 4320        window.focus(&pane.focus_handle(cx), cx);
 4321
 4322        cx.emit(Event::PaneAdded(pane.clone()));
 4323        pane
 4324    }
 4325
 4326    pub fn add_item_to_center(
 4327        &mut self,
 4328        item: Box<dyn ItemHandle>,
 4329        window: &mut Window,
 4330        cx: &mut Context<Self>,
 4331    ) -> bool {
 4332        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4333            if let Some(center_pane) = center_pane.upgrade() {
 4334                center_pane.update(cx, |pane, cx| {
 4335                    pane.add_item(item, true, true, None, window, cx)
 4336                });
 4337                true
 4338            } else {
 4339                false
 4340            }
 4341        } else {
 4342            false
 4343        }
 4344    }
 4345
 4346    pub fn add_item_to_active_pane(
 4347        &mut self,
 4348        item: Box<dyn ItemHandle>,
 4349        destination_index: Option<usize>,
 4350        focus_item: bool,
 4351        window: &mut Window,
 4352        cx: &mut App,
 4353    ) {
 4354        self.add_item(
 4355            self.active_pane.clone(),
 4356            item,
 4357            destination_index,
 4358            false,
 4359            focus_item,
 4360            window,
 4361            cx,
 4362        )
 4363    }
 4364
 4365    pub fn add_item(
 4366        &mut self,
 4367        pane: Entity<Pane>,
 4368        item: Box<dyn ItemHandle>,
 4369        destination_index: Option<usize>,
 4370        activate_pane: bool,
 4371        focus_item: bool,
 4372        window: &mut Window,
 4373        cx: &mut App,
 4374    ) {
 4375        pane.update(cx, |pane, cx| {
 4376            pane.add_item(
 4377                item,
 4378                activate_pane,
 4379                focus_item,
 4380                destination_index,
 4381                window,
 4382                cx,
 4383            )
 4384        });
 4385    }
 4386
 4387    pub fn split_item(
 4388        &mut self,
 4389        split_direction: SplitDirection,
 4390        item: Box<dyn ItemHandle>,
 4391        window: &mut Window,
 4392        cx: &mut Context<Self>,
 4393    ) {
 4394        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4395        self.add_item(new_pane, item, None, true, true, window, cx);
 4396    }
 4397
 4398    pub fn open_abs_path(
 4399        &mut self,
 4400        abs_path: PathBuf,
 4401        options: OpenOptions,
 4402        window: &mut Window,
 4403        cx: &mut Context<Self>,
 4404    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4405        cx.spawn_in(window, async move |workspace, cx| {
 4406            let open_paths_task_result = workspace
 4407                .update_in(cx, |workspace, window, cx| {
 4408                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4409                })
 4410                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4411                .await;
 4412            anyhow::ensure!(
 4413                open_paths_task_result.len() == 1,
 4414                "open abs path {abs_path:?} task returned incorrect number of results"
 4415            );
 4416            match open_paths_task_result
 4417                .into_iter()
 4418                .next()
 4419                .expect("ensured single task result")
 4420            {
 4421                Some(open_result) => {
 4422                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4423                }
 4424                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4425            }
 4426        })
 4427    }
 4428
 4429    pub fn split_abs_path(
 4430        &mut self,
 4431        abs_path: PathBuf,
 4432        visible: bool,
 4433        window: &mut Window,
 4434        cx: &mut Context<Self>,
 4435    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4436        let project_path_task =
 4437            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4438        cx.spawn_in(window, async move |this, cx| {
 4439            let (_, path) = project_path_task.await?;
 4440            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4441                .await
 4442        })
 4443    }
 4444
 4445    pub fn open_path(
 4446        &mut self,
 4447        path: impl Into<ProjectPath>,
 4448        pane: Option<WeakEntity<Pane>>,
 4449        focus_item: bool,
 4450        window: &mut Window,
 4451        cx: &mut App,
 4452    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4453        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4454    }
 4455
 4456    pub fn open_path_preview(
 4457        &mut self,
 4458        path: impl Into<ProjectPath>,
 4459        pane: Option<WeakEntity<Pane>>,
 4460        focus_item: bool,
 4461        allow_preview: bool,
 4462        activate: bool,
 4463        window: &mut Window,
 4464        cx: &mut App,
 4465    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4466        let pane = pane.unwrap_or_else(|| {
 4467            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4468                self.panes
 4469                    .first()
 4470                    .expect("There must be an active pane")
 4471                    .downgrade()
 4472            })
 4473        });
 4474
 4475        let project_path = path.into();
 4476        let task = self.load_path(project_path.clone(), window, cx);
 4477        window.spawn(cx, async move |cx| {
 4478            let (project_entry_id, build_item) = task.await?;
 4479
 4480            pane.update_in(cx, |pane, window, cx| {
 4481                pane.open_item(
 4482                    project_entry_id,
 4483                    project_path,
 4484                    focus_item,
 4485                    allow_preview,
 4486                    activate,
 4487                    None,
 4488                    window,
 4489                    cx,
 4490                    build_item,
 4491                )
 4492            })
 4493        })
 4494    }
 4495
 4496    pub fn split_path(
 4497        &mut self,
 4498        path: impl Into<ProjectPath>,
 4499        window: &mut Window,
 4500        cx: &mut Context<Self>,
 4501    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4502        self.split_path_preview(path, false, None, window, cx)
 4503    }
 4504
 4505    pub fn split_path_preview(
 4506        &mut self,
 4507        path: impl Into<ProjectPath>,
 4508        allow_preview: bool,
 4509        split_direction: Option<SplitDirection>,
 4510        window: &mut Window,
 4511        cx: &mut Context<Self>,
 4512    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4513        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4514            self.panes
 4515                .first()
 4516                .expect("There must be an active pane")
 4517                .downgrade()
 4518        });
 4519
 4520        if let Member::Pane(center_pane) = &self.center.root
 4521            && center_pane.read(cx).items_len() == 0
 4522        {
 4523            return self.open_path(path, Some(pane), true, window, cx);
 4524        }
 4525
 4526        let project_path = path.into();
 4527        let task = self.load_path(project_path.clone(), window, cx);
 4528        cx.spawn_in(window, async move |this, cx| {
 4529            let (project_entry_id, build_item) = task.await?;
 4530            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4531                let pane = pane.upgrade()?;
 4532                let new_pane = this.split_pane(
 4533                    pane,
 4534                    split_direction.unwrap_or(SplitDirection::Right),
 4535                    window,
 4536                    cx,
 4537                );
 4538                new_pane.update(cx, |new_pane, cx| {
 4539                    Some(new_pane.open_item(
 4540                        project_entry_id,
 4541                        project_path,
 4542                        true,
 4543                        allow_preview,
 4544                        true,
 4545                        None,
 4546                        window,
 4547                        cx,
 4548                        build_item,
 4549                    ))
 4550                })
 4551            })
 4552            .map(|option| option.context("pane was dropped"))?
 4553        })
 4554    }
 4555
 4556    fn load_path(
 4557        &mut self,
 4558        path: ProjectPath,
 4559        window: &mut Window,
 4560        cx: &mut App,
 4561    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4562        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4563        registry.open_path(self.project(), &path, window, cx)
 4564    }
 4565
 4566    pub fn find_project_item<T>(
 4567        &self,
 4568        pane: &Entity<Pane>,
 4569        project_item: &Entity<T::Item>,
 4570        cx: &App,
 4571    ) -> Option<Entity<T>>
 4572    where
 4573        T: ProjectItem,
 4574    {
 4575        use project::ProjectItem as _;
 4576        let project_item = project_item.read(cx);
 4577        let entry_id = project_item.entry_id(cx);
 4578        let project_path = project_item.project_path(cx);
 4579
 4580        let mut item = None;
 4581        if let Some(entry_id) = entry_id {
 4582            item = pane.read(cx).item_for_entry(entry_id, cx);
 4583        }
 4584        if item.is_none()
 4585            && let Some(project_path) = project_path
 4586        {
 4587            item = pane.read(cx).item_for_path(project_path, cx);
 4588        }
 4589
 4590        item.and_then(|item| item.downcast::<T>())
 4591    }
 4592
 4593    pub fn is_project_item_open<T>(
 4594        &self,
 4595        pane: &Entity<Pane>,
 4596        project_item: &Entity<T::Item>,
 4597        cx: &App,
 4598    ) -> bool
 4599    where
 4600        T: ProjectItem,
 4601    {
 4602        self.find_project_item::<T>(pane, project_item, cx)
 4603            .is_some()
 4604    }
 4605
 4606    pub fn open_project_item<T>(
 4607        &mut self,
 4608        pane: Entity<Pane>,
 4609        project_item: Entity<T::Item>,
 4610        activate_pane: bool,
 4611        focus_item: bool,
 4612        keep_old_preview: bool,
 4613        allow_new_preview: bool,
 4614        window: &mut Window,
 4615        cx: &mut Context<Self>,
 4616    ) -> Entity<T>
 4617    where
 4618        T: ProjectItem,
 4619    {
 4620        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4621
 4622        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4623            if !keep_old_preview
 4624                && let Some(old_id) = old_item_id
 4625                && old_id != item.item_id()
 4626            {
 4627                // switching to a different item, so unpreview old active item
 4628                pane.update(cx, |pane, _| {
 4629                    pane.unpreview_item_if_preview(old_id);
 4630                });
 4631            }
 4632
 4633            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4634            if !allow_new_preview {
 4635                pane.update(cx, |pane, _| {
 4636                    pane.unpreview_item_if_preview(item.item_id());
 4637                });
 4638            }
 4639            return item;
 4640        }
 4641
 4642        let item = pane.update(cx, |pane, cx| {
 4643            cx.new(|cx| {
 4644                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4645            })
 4646        });
 4647        let mut destination_index = None;
 4648        pane.update(cx, |pane, cx| {
 4649            if !keep_old_preview && let Some(old_id) = old_item_id {
 4650                pane.unpreview_item_if_preview(old_id);
 4651            }
 4652            if allow_new_preview {
 4653                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4654            }
 4655        });
 4656
 4657        self.add_item(
 4658            pane,
 4659            Box::new(item.clone()),
 4660            destination_index,
 4661            activate_pane,
 4662            focus_item,
 4663            window,
 4664            cx,
 4665        );
 4666        item
 4667    }
 4668
 4669    pub fn open_shared_screen(
 4670        &mut self,
 4671        peer_id: PeerId,
 4672        window: &mut Window,
 4673        cx: &mut Context<Self>,
 4674    ) {
 4675        if let Some(shared_screen) =
 4676            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4677        {
 4678            self.active_pane.update(cx, |pane, cx| {
 4679                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4680            });
 4681        }
 4682    }
 4683
 4684    pub fn activate_item(
 4685        &mut self,
 4686        item: &dyn ItemHandle,
 4687        activate_pane: bool,
 4688        focus_item: bool,
 4689        window: &mut Window,
 4690        cx: &mut App,
 4691    ) -> bool {
 4692        let result = self.panes.iter().find_map(|pane| {
 4693            pane.read(cx)
 4694                .index_for_item(item)
 4695                .map(|ix| (pane.clone(), ix))
 4696        });
 4697        if let Some((pane, ix)) = result {
 4698            pane.update(cx, |pane, cx| {
 4699                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4700            });
 4701            true
 4702        } else {
 4703            false
 4704        }
 4705    }
 4706
 4707    fn activate_pane_at_index(
 4708        &mut self,
 4709        action: &ActivatePane,
 4710        window: &mut Window,
 4711        cx: &mut Context<Self>,
 4712    ) {
 4713        let panes = self.center.panes();
 4714        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4715            window.focus(&pane.focus_handle(cx), cx);
 4716        } else {
 4717            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4718                .detach();
 4719        }
 4720    }
 4721
 4722    fn move_item_to_pane_at_index(
 4723        &mut self,
 4724        action: &MoveItemToPane,
 4725        window: &mut Window,
 4726        cx: &mut Context<Self>,
 4727    ) {
 4728        let panes = self.center.panes();
 4729        let destination = match panes.get(action.destination) {
 4730            Some(&destination) => destination.clone(),
 4731            None => {
 4732                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4733                    return;
 4734                }
 4735                let direction = SplitDirection::Right;
 4736                let split_off_pane = self
 4737                    .find_pane_in_direction(direction, cx)
 4738                    .unwrap_or_else(|| self.active_pane.clone());
 4739                let new_pane = self.add_pane(window, cx);
 4740                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4741                new_pane
 4742            }
 4743        };
 4744
 4745        if action.clone {
 4746            if self
 4747                .active_pane
 4748                .read(cx)
 4749                .active_item()
 4750                .is_some_and(|item| item.can_split(cx))
 4751            {
 4752                clone_active_item(
 4753                    self.database_id(),
 4754                    &self.active_pane,
 4755                    &destination,
 4756                    action.focus,
 4757                    window,
 4758                    cx,
 4759                );
 4760                return;
 4761            }
 4762        }
 4763        move_active_item(
 4764            &self.active_pane,
 4765            &destination,
 4766            action.focus,
 4767            true,
 4768            window,
 4769            cx,
 4770        )
 4771    }
 4772
 4773    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4774        let panes = self.center.panes();
 4775        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4776            let next_ix = (ix + 1) % panes.len();
 4777            let next_pane = panes[next_ix].clone();
 4778            window.focus(&next_pane.focus_handle(cx), cx);
 4779        }
 4780    }
 4781
 4782    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4783        let panes = self.center.panes();
 4784        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4785            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4786            let prev_pane = panes[prev_ix].clone();
 4787            window.focus(&prev_pane.focus_handle(cx), cx);
 4788        }
 4789    }
 4790
 4791    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4792        let last_pane = self.center.last_pane();
 4793        window.focus(&last_pane.focus_handle(cx), cx);
 4794    }
 4795
 4796    pub fn activate_pane_in_direction(
 4797        &mut self,
 4798        direction: SplitDirection,
 4799        window: &mut Window,
 4800        cx: &mut App,
 4801    ) {
 4802        use ActivateInDirectionTarget as Target;
 4803        enum Origin {
 4804            Sidebar,
 4805            LeftDock,
 4806            RightDock,
 4807            BottomDock,
 4808            Center,
 4809        }
 4810
 4811        let origin: Origin = if self
 4812            .sidebar_focus_handle
 4813            .as_ref()
 4814            .is_some_and(|h| h.contains_focused(window, cx))
 4815        {
 4816            Origin::Sidebar
 4817        } else {
 4818            [
 4819                (&self.left_dock, Origin::LeftDock),
 4820                (&self.right_dock, Origin::RightDock),
 4821                (&self.bottom_dock, Origin::BottomDock),
 4822            ]
 4823            .into_iter()
 4824            .find_map(|(dock, origin)| {
 4825                if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4826                    Some(origin)
 4827                } else {
 4828                    None
 4829                }
 4830            })
 4831            .unwrap_or(Origin::Center)
 4832        };
 4833
 4834        let get_last_active_pane = || {
 4835            let pane = self
 4836                .last_active_center_pane
 4837                .clone()
 4838                .unwrap_or_else(|| {
 4839                    self.panes
 4840                        .first()
 4841                        .expect("There must be an active pane")
 4842                        .downgrade()
 4843                })
 4844                .upgrade()?;
 4845            (pane.read(cx).items_len() != 0).then_some(pane)
 4846        };
 4847
 4848        let try_dock =
 4849            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4850
 4851        let sidebar_target = self
 4852            .sidebar_focus_handle
 4853            .as_ref()
 4854            .map(|h| Target::Sidebar(h.clone()));
 4855
 4856        let sidebar_on_right = self
 4857            .multi_workspace
 4858            .as_ref()
 4859            .and_then(|mw| mw.upgrade())
 4860            .map_or(false, |mw| {
 4861                mw.read(cx).sidebar_side(cx) == SidebarSide::Right
 4862            });
 4863
 4864        let away_from_sidebar = if sidebar_on_right {
 4865            SplitDirection::Left
 4866        } else {
 4867            SplitDirection::Right
 4868        };
 4869
 4870        let (near_dock, far_dock) = if sidebar_on_right {
 4871            (&self.right_dock, &self.left_dock)
 4872        } else {
 4873            (&self.left_dock, &self.right_dock)
 4874        };
 4875
 4876        let target = match (origin, direction) {
 4877            (Origin::Sidebar, dir) if dir == away_from_sidebar => try_dock(near_dock)
 4878                .or_else(|| get_last_active_pane().map(Target::Pane))
 4879                .or_else(|| try_dock(&self.bottom_dock))
 4880                .or_else(|| try_dock(far_dock)),
 4881
 4882            (Origin::Sidebar, _) => None,
 4883
 4884            // We're in the center, so we first try to go to a different pane,
 4885            // otherwise try to go to a dock.
 4886            (Origin::Center, direction) => {
 4887                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4888                    Some(Target::Pane(pane))
 4889                } else {
 4890                    match direction {
 4891                        SplitDirection::Up => None,
 4892                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4893                        SplitDirection::Left => {
 4894                            let dock_target = try_dock(&self.left_dock);
 4895                            if sidebar_on_right {
 4896                                dock_target
 4897                            } else {
 4898                                dock_target.or(sidebar_target)
 4899                            }
 4900                        }
 4901                        SplitDirection::Right => {
 4902                            let dock_target = try_dock(&self.right_dock);
 4903                            if sidebar_on_right {
 4904                                dock_target.or(sidebar_target)
 4905                            } else {
 4906                                dock_target
 4907                            }
 4908                        }
 4909                    }
 4910                }
 4911            }
 4912
 4913            (Origin::LeftDock, SplitDirection::Right) => {
 4914                if let Some(last_active_pane) = get_last_active_pane() {
 4915                    Some(Target::Pane(last_active_pane))
 4916                } else {
 4917                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4918                }
 4919            }
 4920
 4921            (Origin::LeftDock, SplitDirection::Left) => {
 4922                if sidebar_on_right {
 4923                    None
 4924                } else {
 4925                    sidebar_target
 4926                }
 4927            }
 4928
 4929            (Origin::LeftDock, SplitDirection::Down)
 4930            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4931
 4932            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4933            (Origin::BottomDock, SplitDirection::Left) => {
 4934                let dock_target = try_dock(&self.left_dock);
 4935                if sidebar_on_right {
 4936                    dock_target
 4937                } else {
 4938                    dock_target.or(sidebar_target)
 4939                }
 4940            }
 4941            (Origin::BottomDock, SplitDirection::Right) => {
 4942                let dock_target = try_dock(&self.right_dock);
 4943                if sidebar_on_right {
 4944                    dock_target.or(sidebar_target)
 4945                } else {
 4946                    dock_target
 4947                }
 4948            }
 4949
 4950            (Origin::RightDock, SplitDirection::Left) => {
 4951                if let Some(last_active_pane) = get_last_active_pane() {
 4952                    Some(Target::Pane(last_active_pane))
 4953                } else {
 4954                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 4955                }
 4956            }
 4957
 4958            (Origin::RightDock, SplitDirection::Right) => {
 4959                if sidebar_on_right {
 4960                    sidebar_target
 4961                } else {
 4962                    None
 4963                }
 4964            }
 4965
 4966            _ => None,
 4967        };
 4968
 4969        match target {
 4970            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4971                let pane = pane.read(cx);
 4972                if let Some(item) = pane.active_item() {
 4973                    item.item_focus_handle(cx).focus(window, cx);
 4974                } else {
 4975                    log::error!(
 4976                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4977                    );
 4978                }
 4979            }
 4980            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4981                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4982                window.defer(cx, move |window, cx| {
 4983                    let dock = dock.read(cx);
 4984                    if let Some(panel) = dock.active_panel() {
 4985                        panel.panel_focus_handle(cx).focus(window, cx);
 4986                    } else {
 4987                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4988                    }
 4989                })
 4990            }
 4991            Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
 4992                focus_handle.focus(window, cx);
 4993            }
 4994            None => {}
 4995        }
 4996    }
 4997
 4998    pub fn move_item_to_pane_in_direction(
 4999        &mut self,
 5000        action: &MoveItemToPaneInDirection,
 5001        window: &mut Window,
 5002        cx: &mut Context<Self>,
 5003    ) {
 5004        let destination = match self.find_pane_in_direction(action.direction, cx) {
 5005            Some(destination) => destination,
 5006            None => {
 5007                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 5008                    return;
 5009                }
 5010                let new_pane = self.add_pane(window, cx);
 5011                self.center
 5012                    .split(&self.active_pane, &new_pane, action.direction, cx);
 5013                new_pane
 5014            }
 5015        };
 5016
 5017        if action.clone {
 5018            if self
 5019                .active_pane
 5020                .read(cx)
 5021                .active_item()
 5022                .is_some_and(|item| item.can_split(cx))
 5023            {
 5024                clone_active_item(
 5025                    self.database_id(),
 5026                    &self.active_pane,
 5027                    &destination,
 5028                    action.focus,
 5029                    window,
 5030                    cx,
 5031                );
 5032                return;
 5033            }
 5034        }
 5035        move_active_item(
 5036            &self.active_pane,
 5037            &destination,
 5038            action.focus,
 5039            true,
 5040            window,
 5041            cx,
 5042        );
 5043    }
 5044
 5045    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 5046        self.center.bounding_box_for_pane(pane)
 5047    }
 5048
 5049    pub fn find_pane_in_direction(
 5050        &mut self,
 5051        direction: SplitDirection,
 5052        cx: &App,
 5053    ) -> Option<Entity<Pane>> {
 5054        self.center
 5055            .find_pane_in_direction(&self.active_pane, direction, cx)
 5056            .cloned()
 5057    }
 5058
 5059    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 5060        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 5061            self.center.swap(&self.active_pane, &to, cx);
 5062            cx.notify();
 5063        }
 5064    }
 5065
 5066    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 5067        if self
 5068            .center
 5069            .move_to_border(&self.active_pane, direction, cx)
 5070            .unwrap()
 5071        {
 5072            cx.notify();
 5073        }
 5074    }
 5075
 5076    pub fn resize_pane(
 5077        &mut self,
 5078        axis: gpui::Axis,
 5079        amount: Pixels,
 5080        window: &mut Window,
 5081        cx: &mut Context<Self>,
 5082    ) {
 5083        let docks = self.all_docks();
 5084        let active_dock = docks
 5085            .into_iter()
 5086            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 5087
 5088        if let Some(dock_entity) = active_dock {
 5089            let dock = dock_entity.read(cx);
 5090            let Some(panel_size) = self.dock_size(&dock, window, cx) else {
 5091                return;
 5092            };
 5093            match dock.position() {
 5094                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 5095                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 5096                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 5097            }
 5098        } else {
 5099            self.center
 5100                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 5101        }
 5102        cx.notify();
 5103    }
 5104
 5105    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 5106        self.center.reset_pane_sizes(cx);
 5107        cx.notify();
 5108    }
 5109
 5110    fn handle_pane_focused(
 5111        &mut self,
 5112        pane: Entity<Pane>,
 5113        window: &mut Window,
 5114        cx: &mut Context<Self>,
 5115    ) {
 5116        // This is explicitly hoisted out of the following check for pane identity as
 5117        // terminal panel panes are not registered as a center panes.
 5118        self.status_bar.update(cx, |status_bar, cx| {
 5119            status_bar.set_active_pane(&pane, window, cx);
 5120        });
 5121        if self.active_pane != pane {
 5122            self.set_active_pane(&pane, window, cx);
 5123        }
 5124
 5125        if self.last_active_center_pane.is_none() {
 5126            self.last_active_center_pane = Some(pane.downgrade());
 5127        }
 5128
 5129        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 5130        // This prevents the dock from closing when focus events fire during window activation.
 5131        // We also preserve any dock whose active panel itself has focus — this covers
 5132        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 5133        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 5134            let dock_read = dock.read(cx);
 5135            if let Some(panel) = dock_read.active_panel() {
 5136                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 5137                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 5138                {
 5139                    return Some(dock_read.position());
 5140                }
 5141            }
 5142            None
 5143        });
 5144
 5145        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 5146        if pane.read(cx).is_zoomed() {
 5147            self.zoomed = Some(pane.downgrade().into());
 5148        } else {
 5149            self.zoomed = None;
 5150        }
 5151        self.zoomed_position = None;
 5152        cx.emit(Event::ZoomChanged);
 5153        self.update_active_view_for_followers(window, cx);
 5154        pane.update(cx, |pane, _| {
 5155            pane.track_alternate_file_items();
 5156        });
 5157
 5158        cx.notify();
 5159    }
 5160
 5161    fn set_active_pane(
 5162        &mut self,
 5163        pane: &Entity<Pane>,
 5164        window: &mut Window,
 5165        cx: &mut Context<Self>,
 5166    ) {
 5167        self.active_pane = pane.clone();
 5168        self.active_item_path_changed(true, window, cx);
 5169        self.last_active_center_pane = Some(pane.downgrade());
 5170    }
 5171
 5172    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5173        self.update_active_view_for_followers(window, cx);
 5174    }
 5175
 5176    fn handle_pane_event(
 5177        &mut self,
 5178        pane: &Entity<Pane>,
 5179        event: &pane::Event,
 5180        window: &mut Window,
 5181        cx: &mut Context<Self>,
 5182    ) {
 5183        let mut serialize_workspace = true;
 5184        match event {
 5185            pane::Event::AddItem { item } => {
 5186                item.added_to_pane(self, pane.clone(), window, cx);
 5187                cx.emit(Event::ItemAdded {
 5188                    item: item.boxed_clone(),
 5189                });
 5190            }
 5191            pane::Event::Split { direction, mode } => {
 5192                match mode {
 5193                    SplitMode::ClonePane => {
 5194                        self.split_and_clone(pane.clone(), *direction, window, cx)
 5195                            .detach();
 5196                    }
 5197                    SplitMode::EmptyPane => {
 5198                        self.split_pane(pane.clone(), *direction, window, cx);
 5199                    }
 5200                    SplitMode::MovePane => {
 5201                        self.split_and_move(pane.clone(), *direction, window, cx);
 5202                    }
 5203                };
 5204            }
 5205            pane::Event::JoinIntoNext => {
 5206                self.join_pane_into_next(pane.clone(), window, cx);
 5207            }
 5208            pane::Event::JoinAll => {
 5209                self.join_all_panes(window, cx);
 5210            }
 5211            pane::Event::Remove { focus_on_pane } => {
 5212                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 5213            }
 5214            pane::Event::ActivateItem {
 5215                local,
 5216                focus_changed,
 5217            } => {
 5218                window.invalidate_character_coordinates();
 5219
 5220                pane.update(cx, |pane, _| {
 5221                    pane.track_alternate_file_items();
 5222                });
 5223                if *local {
 5224                    self.unfollow_in_pane(pane, window, cx);
 5225                }
 5226                serialize_workspace = *focus_changed || pane != self.active_pane();
 5227                if pane == self.active_pane() {
 5228                    self.active_item_path_changed(*focus_changed, window, cx);
 5229                    self.update_active_view_for_followers(window, cx);
 5230                } else if *local {
 5231                    self.set_active_pane(pane, window, cx);
 5232                }
 5233            }
 5234            pane::Event::UserSavedItem { item, save_intent } => {
 5235                cx.emit(Event::UserSavedItem {
 5236                    pane: pane.downgrade(),
 5237                    item: item.boxed_clone(),
 5238                    save_intent: *save_intent,
 5239                });
 5240                serialize_workspace = false;
 5241            }
 5242            pane::Event::ChangeItemTitle => {
 5243                if *pane == self.active_pane {
 5244                    self.active_item_path_changed(false, window, cx);
 5245                }
 5246                serialize_workspace = false;
 5247            }
 5248            pane::Event::RemovedItem { item } => {
 5249                cx.emit(Event::ActiveItemChanged);
 5250                self.update_window_edited(window, cx);
 5251                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 5252                    && entry.get().entity_id() == pane.entity_id()
 5253                {
 5254                    entry.remove();
 5255                }
 5256                cx.emit(Event::ItemRemoved {
 5257                    item_id: item.item_id(),
 5258                });
 5259            }
 5260            pane::Event::Focus => {
 5261                window.invalidate_character_coordinates();
 5262                self.handle_pane_focused(pane.clone(), window, cx);
 5263            }
 5264            pane::Event::ZoomIn => {
 5265                if *pane == self.active_pane {
 5266                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 5267                    if pane.read(cx).has_focus(window, cx) {
 5268                        self.zoomed = Some(pane.downgrade().into());
 5269                        self.zoomed_position = None;
 5270                        cx.emit(Event::ZoomChanged);
 5271                    }
 5272                    cx.notify();
 5273                }
 5274            }
 5275            pane::Event::ZoomOut => {
 5276                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 5277                if self.zoomed_position.is_none() {
 5278                    self.zoomed = None;
 5279                    cx.emit(Event::ZoomChanged);
 5280                }
 5281                cx.notify();
 5282            }
 5283            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 5284        }
 5285
 5286        if serialize_workspace {
 5287            self.serialize_workspace(window, cx);
 5288        }
 5289    }
 5290
 5291    pub fn unfollow_in_pane(
 5292        &mut self,
 5293        pane: &Entity<Pane>,
 5294        window: &mut Window,
 5295        cx: &mut Context<Workspace>,
 5296    ) -> Option<CollaboratorId> {
 5297        let leader_id = self.leader_for_pane(pane)?;
 5298        self.unfollow(leader_id, window, cx);
 5299        Some(leader_id)
 5300    }
 5301
 5302    pub fn split_pane(
 5303        &mut self,
 5304        pane_to_split: Entity<Pane>,
 5305        split_direction: SplitDirection,
 5306        window: &mut Window,
 5307        cx: &mut Context<Self>,
 5308    ) -> Entity<Pane> {
 5309        let new_pane = self.add_pane(window, cx);
 5310        self.center
 5311            .split(&pane_to_split, &new_pane, split_direction, cx);
 5312        cx.notify();
 5313        new_pane
 5314    }
 5315
 5316    pub fn split_and_move(
 5317        &mut self,
 5318        pane: Entity<Pane>,
 5319        direction: SplitDirection,
 5320        window: &mut Window,
 5321        cx: &mut Context<Self>,
 5322    ) {
 5323        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 5324            return;
 5325        };
 5326        let new_pane = self.add_pane(window, cx);
 5327        new_pane.update(cx, |pane, cx| {
 5328            pane.add_item(item, true, true, None, window, cx)
 5329        });
 5330        self.center.split(&pane, &new_pane, direction, cx);
 5331        cx.notify();
 5332    }
 5333
 5334    pub fn split_and_clone(
 5335        &mut self,
 5336        pane: Entity<Pane>,
 5337        direction: SplitDirection,
 5338        window: &mut Window,
 5339        cx: &mut Context<Self>,
 5340    ) -> Task<Option<Entity<Pane>>> {
 5341        let Some(item) = pane.read(cx).active_item() else {
 5342            return Task::ready(None);
 5343        };
 5344        if !item.can_split(cx) {
 5345            return Task::ready(None);
 5346        }
 5347        let task = item.clone_on_split(self.database_id(), window, cx);
 5348        cx.spawn_in(window, async move |this, cx| {
 5349            if let Some(clone) = task.await {
 5350                this.update_in(cx, |this, window, cx| {
 5351                    let new_pane = this.add_pane(window, cx);
 5352                    let nav_history = pane.read(cx).fork_nav_history();
 5353                    new_pane.update(cx, |pane, cx| {
 5354                        pane.set_nav_history(nav_history, cx);
 5355                        pane.add_item(clone, true, true, None, window, cx)
 5356                    });
 5357                    this.center.split(&pane, &new_pane, direction, cx);
 5358                    cx.notify();
 5359                    new_pane
 5360                })
 5361                .ok()
 5362            } else {
 5363                None
 5364            }
 5365        })
 5366    }
 5367
 5368    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5369        let active_item = self.active_pane.read(cx).active_item();
 5370        for pane in &self.panes {
 5371            join_pane_into_active(&self.active_pane, pane, window, cx);
 5372        }
 5373        if let Some(active_item) = active_item {
 5374            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5375        }
 5376        cx.notify();
 5377    }
 5378
 5379    pub fn join_pane_into_next(
 5380        &mut self,
 5381        pane: Entity<Pane>,
 5382        window: &mut Window,
 5383        cx: &mut Context<Self>,
 5384    ) {
 5385        let next_pane = self
 5386            .find_pane_in_direction(SplitDirection::Right, cx)
 5387            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5388            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5389            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5390        let Some(next_pane) = next_pane else {
 5391            return;
 5392        };
 5393        move_all_items(&pane, &next_pane, window, cx);
 5394        cx.notify();
 5395    }
 5396
 5397    fn remove_pane(
 5398        &mut self,
 5399        pane: Entity<Pane>,
 5400        focus_on: Option<Entity<Pane>>,
 5401        window: &mut Window,
 5402        cx: &mut Context<Self>,
 5403    ) {
 5404        if self.center.remove(&pane, cx).unwrap() {
 5405            self.force_remove_pane(&pane, &focus_on, window, cx);
 5406            self.unfollow_in_pane(&pane, window, cx);
 5407            self.last_leaders_by_pane.remove(&pane.downgrade());
 5408            for removed_item in pane.read(cx).items() {
 5409                self.panes_by_item.remove(&removed_item.item_id());
 5410            }
 5411
 5412            cx.notify();
 5413        } else {
 5414            self.active_item_path_changed(true, window, cx);
 5415        }
 5416        cx.emit(Event::PaneRemoved);
 5417    }
 5418
 5419    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5420        &mut self.panes
 5421    }
 5422
 5423    pub fn panes(&self) -> &[Entity<Pane>] {
 5424        &self.panes
 5425    }
 5426
 5427    pub fn active_pane(&self) -> &Entity<Pane> {
 5428        &self.active_pane
 5429    }
 5430
 5431    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5432        for dock in self.all_docks() {
 5433            if dock.focus_handle(cx).contains_focused(window, cx)
 5434                && let Some(pane) = dock
 5435                    .read(cx)
 5436                    .active_panel()
 5437                    .and_then(|panel| panel.pane(cx))
 5438            {
 5439                return pane;
 5440            }
 5441        }
 5442        self.active_pane().clone()
 5443    }
 5444
 5445    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5446        self.find_pane_in_direction(SplitDirection::Right, cx)
 5447            .unwrap_or_else(|| {
 5448                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5449            })
 5450    }
 5451
 5452    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5453        self.pane_for_item_id(handle.item_id())
 5454    }
 5455
 5456    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5457        let weak_pane = self.panes_by_item.get(&item_id)?;
 5458        weak_pane.upgrade()
 5459    }
 5460
 5461    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5462        self.panes
 5463            .iter()
 5464            .find(|pane| pane.entity_id() == entity_id)
 5465            .cloned()
 5466    }
 5467
 5468    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5469        self.follower_states.retain(|leader_id, state| {
 5470            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5471                for item in state.items_by_leader_view_id.values() {
 5472                    item.view.set_leader_id(None, window, cx);
 5473                }
 5474                false
 5475            } else {
 5476                true
 5477            }
 5478        });
 5479        cx.notify();
 5480    }
 5481
 5482    pub fn start_following(
 5483        &mut self,
 5484        leader_id: impl Into<CollaboratorId>,
 5485        window: &mut Window,
 5486        cx: &mut Context<Self>,
 5487    ) -> Option<Task<Result<()>>> {
 5488        let leader_id = leader_id.into();
 5489        let pane = self.active_pane().clone();
 5490
 5491        self.last_leaders_by_pane
 5492            .insert(pane.downgrade(), leader_id);
 5493        self.unfollow(leader_id, window, cx);
 5494        self.unfollow_in_pane(&pane, window, cx);
 5495        self.follower_states.insert(
 5496            leader_id,
 5497            FollowerState {
 5498                center_pane: pane.clone(),
 5499                dock_pane: None,
 5500                active_view_id: None,
 5501                items_by_leader_view_id: Default::default(),
 5502            },
 5503        );
 5504        cx.notify();
 5505
 5506        match leader_id {
 5507            CollaboratorId::PeerId(leader_peer_id) => {
 5508                let room_id = self.active_call()?.room_id(cx)?;
 5509                let project_id = self.project.read(cx).remote_id();
 5510                let request = self.app_state.client.request(proto::Follow {
 5511                    room_id,
 5512                    project_id,
 5513                    leader_id: Some(leader_peer_id),
 5514                });
 5515
 5516                Some(cx.spawn_in(window, async move |this, cx| {
 5517                    let response = request.await?;
 5518                    this.update(cx, |this, _| {
 5519                        let state = this
 5520                            .follower_states
 5521                            .get_mut(&leader_id)
 5522                            .context("following interrupted")?;
 5523                        state.active_view_id = response
 5524                            .active_view
 5525                            .as_ref()
 5526                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5527                        anyhow::Ok(())
 5528                    })??;
 5529                    if let Some(view) = response.active_view {
 5530                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5531                    }
 5532                    this.update_in(cx, |this, window, cx| {
 5533                        this.leader_updated(leader_id, window, cx)
 5534                    })?;
 5535                    Ok(())
 5536                }))
 5537            }
 5538            CollaboratorId::Agent => {
 5539                self.leader_updated(leader_id, window, cx)?;
 5540                Some(Task::ready(Ok(())))
 5541            }
 5542        }
 5543    }
 5544
 5545    pub fn follow_next_collaborator(
 5546        &mut self,
 5547        _: &FollowNextCollaborator,
 5548        window: &mut Window,
 5549        cx: &mut Context<Self>,
 5550    ) {
 5551        let collaborators = self.project.read(cx).collaborators();
 5552        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5553            let mut collaborators = collaborators.keys().copied();
 5554            for peer_id in collaborators.by_ref() {
 5555                if CollaboratorId::PeerId(peer_id) == leader_id {
 5556                    break;
 5557                }
 5558            }
 5559            collaborators.next().map(CollaboratorId::PeerId)
 5560        } else if let Some(last_leader_id) =
 5561            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5562        {
 5563            match last_leader_id {
 5564                CollaboratorId::PeerId(peer_id) => {
 5565                    if collaborators.contains_key(peer_id) {
 5566                        Some(*last_leader_id)
 5567                    } else {
 5568                        None
 5569                    }
 5570                }
 5571                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5572            }
 5573        } else {
 5574            None
 5575        };
 5576
 5577        let pane = self.active_pane.clone();
 5578        let Some(leader_id) = next_leader_id.or_else(|| {
 5579            Some(CollaboratorId::PeerId(
 5580                collaborators.keys().copied().next()?,
 5581            ))
 5582        }) else {
 5583            return;
 5584        };
 5585        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5586            return;
 5587        }
 5588        if let Some(task) = self.start_following(leader_id, window, cx) {
 5589            task.detach_and_log_err(cx)
 5590        }
 5591    }
 5592
 5593    pub fn follow(
 5594        &mut self,
 5595        leader_id: impl Into<CollaboratorId>,
 5596        window: &mut Window,
 5597        cx: &mut Context<Self>,
 5598    ) {
 5599        let leader_id = leader_id.into();
 5600
 5601        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5602            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5603                return;
 5604            };
 5605            let Some(remote_participant) =
 5606                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5607            else {
 5608                return;
 5609            };
 5610
 5611            let project = self.project.read(cx);
 5612
 5613            let other_project_id = match remote_participant.location {
 5614                ParticipantLocation::External => None,
 5615                ParticipantLocation::UnsharedProject => None,
 5616                ParticipantLocation::SharedProject { project_id } => {
 5617                    if Some(project_id) == project.remote_id() {
 5618                        None
 5619                    } else {
 5620                        Some(project_id)
 5621                    }
 5622                }
 5623            };
 5624
 5625            // if they are active in another project, follow there.
 5626            if let Some(project_id) = other_project_id {
 5627                let app_state = self.app_state.clone();
 5628                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5629                    .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
 5630                        Some(format!("{error:#}"))
 5631                    });
 5632            }
 5633        }
 5634
 5635        // if you're already following, find the right pane and focus it.
 5636        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5637            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5638
 5639            return;
 5640        }
 5641
 5642        // Otherwise, follow.
 5643        if let Some(task) = self.start_following(leader_id, window, cx) {
 5644            task.detach_and_log_err(cx)
 5645        }
 5646    }
 5647
 5648    pub fn unfollow(
 5649        &mut self,
 5650        leader_id: impl Into<CollaboratorId>,
 5651        window: &mut Window,
 5652        cx: &mut Context<Self>,
 5653    ) -> Option<()> {
 5654        cx.notify();
 5655
 5656        let leader_id = leader_id.into();
 5657        let state = self.follower_states.remove(&leader_id)?;
 5658        for (_, item) in state.items_by_leader_view_id {
 5659            item.view.set_leader_id(None, window, cx);
 5660        }
 5661
 5662        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5663            let project_id = self.project.read(cx).remote_id();
 5664            let room_id = self.active_call()?.room_id(cx)?;
 5665            self.app_state
 5666                .client
 5667                .send(proto::Unfollow {
 5668                    room_id,
 5669                    project_id,
 5670                    leader_id: Some(leader_peer_id),
 5671                })
 5672                .log_err();
 5673        }
 5674
 5675        Some(())
 5676    }
 5677
 5678    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5679        self.follower_states.contains_key(&id.into())
 5680    }
 5681
 5682    fn active_item_path_changed(
 5683        &mut self,
 5684        focus_changed: bool,
 5685        window: &mut Window,
 5686        cx: &mut Context<Self>,
 5687    ) {
 5688        cx.emit(Event::ActiveItemChanged);
 5689        let active_entry = self.active_project_path(cx);
 5690        self.project.update(cx, |project, cx| {
 5691            project.set_active_path(active_entry.clone(), cx)
 5692        });
 5693
 5694        if focus_changed && let Some(project_path) = &active_entry {
 5695            let git_store_entity = self.project.read(cx).git_store().clone();
 5696            git_store_entity.update(cx, |git_store, cx| {
 5697                git_store.set_active_repo_for_path(project_path, cx);
 5698            });
 5699        }
 5700
 5701        self.update_window_title(window, cx);
 5702    }
 5703
 5704    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5705        let project = self.project().read(cx);
 5706        let mut title = String::new();
 5707
 5708        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5709            let name = {
 5710                let settings_location = SettingsLocation {
 5711                    worktree_id: worktree.read(cx).id(),
 5712                    path: RelPath::empty(),
 5713                };
 5714
 5715                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5716                match &settings.project_name {
 5717                    Some(name) => name.as_str(),
 5718                    None => worktree.read(cx).root_name_str(),
 5719                }
 5720            };
 5721            if i > 0 {
 5722                title.push_str(", ");
 5723            }
 5724            title.push_str(name);
 5725        }
 5726
 5727        if title.is_empty() {
 5728            title = "empty project".to_string();
 5729        }
 5730
 5731        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5732            let filename = path.path.file_name().or_else(|| {
 5733                Some(
 5734                    project
 5735                        .worktree_for_id(path.worktree_id, cx)?
 5736                        .read(cx)
 5737                        .root_name_str(),
 5738                )
 5739            });
 5740
 5741            if let Some(filename) = filename {
 5742                title.push_str("");
 5743                title.push_str(filename.as_ref());
 5744            }
 5745        }
 5746
 5747        if project.is_via_collab() {
 5748            title.push_str("");
 5749        } else if project.is_shared() {
 5750            title.push_str("");
 5751        }
 5752
 5753        if let Some(last_title) = self.last_window_title.as_ref()
 5754            && &title == last_title
 5755        {
 5756            return;
 5757        }
 5758        window.set_window_title(&title);
 5759        SystemWindowTabController::update_tab_title(
 5760            cx,
 5761            window.window_handle().window_id(),
 5762            SharedString::from(&title),
 5763        );
 5764        self.last_window_title = Some(title);
 5765    }
 5766
 5767    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5768        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5769        if is_edited != self.window_edited {
 5770            self.window_edited = is_edited;
 5771            window.set_window_edited(self.window_edited)
 5772        }
 5773    }
 5774
 5775    fn update_item_dirty_state(
 5776        &mut self,
 5777        item: &dyn ItemHandle,
 5778        window: &mut Window,
 5779        cx: &mut App,
 5780    ) {
 5781        let is_dirty = item.is_dirty(cx);
 5782        let item_id = item.item_id();
 5783        let was_dirty = self.dirty_items.contains_key(&item_id);
 5784        if is_dirty == was_dirty {
 5785            return;
 5786        }
 5787        if was_dirty {
 5788            self.dirty_items.remove(&item_id);
 5789            self.update_window_edited(window, cx);
 5790            return;
 5791        }
 5792
 5793        let workspace = self.weak_handle();
 5794        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5795            return;
 5796        };
 5797        let on_release_callback = Box::new(move |cx: &mut App| {
 5798            window_handle
 5799                .update(cx, |_, window, cx| {
 5800                    workspace
 5801                        .update(cx, |workspace, cx| {
 5802                            workspace.dirty_items.remove(&item_id);
 5803                            workspace.update_window_edited(window, cx)
 5804                        })
 5805                        .ok();
 5806                })
 5807                .ok();
 5808        });
 5809
 5810        let s = item.on_release(cx, on_release_callback);
 5811        self.dirty_items.insert(item_id, s);
 5812        self.update_window_edited(window, cx);
 5813    }
 5814
 5815    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5816        if self.notifications.is_empty() {
 5817            None
 5818        } else {
 5819            Some(
 5820                div()
 5821                    .absolute()
 5822                    .right_3()
 5823                    .bottom_3()
 5824                    .w_112()
 5825                    .h_full()
 5826                    .flex()
 5827                    .flex_col()
 5828                    .justify_end()
 5829                    .gap_2()
 5830                    .children(
 5831                        self.notifications
 5832                            .iter()
 5833                            .map(|(_, notification)| notification.clone().into_any()),
 5834                    ),
 5835            )
 5836        }
 5837    }
 5838
 5839    // RPC handlers
 5840
 5841    fn active_view_for_follower(
 5842        &self,
 5843        follower_project_id: Option<u64>,
 5844        window: &mut Window,
 5845        cx: &mut Context<Self>,
 5846    ) -> Option<proto::View> {
 5847        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5848        let item = item?;
 5849        let leader_id = self
 5850            .pane_for(&*item)
 5851            .and_then(|pane| self.leader_for_pane(&pane));
 5852        let leader_peer_id = match leader_id {
 5853            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5854            Some(CollaboratorId::Agent) | None => None,
 5855        };
 5856
 5857        let item_handle = item.to_followable_item_handle(cx)?;
 5858        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5859        let variant = item_handle.to_state_proto(window, cx)?;
 5860
 5861        if item_handle.is_project_item(window, cx)
 5862            && (follower_project_id.is_none()
 5863                || follower_project_id != self.project.read(cx).remote_id())
 5864        {
 5865            return None;
 5866        }
 5867
 5868        Some(proto::View {
 5869            id: id.to_proto(),
 5870            leader_id: leader_peer_id,
 5871            variant: Some(variant),
 5872            panel_id: panel_id.map(|id| id as i32),
 5873        })
 5874    }
 5875
 5876    fn handle_follow(
 5877        &mut self,
 5878        follower_project_id: Option<u64>,
 5879        window: &mut Window,
 5880        cx: &mut Context<Self>,
 5881    ) -> proto::FollowResponse {
 5882        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5883
 5884        cx.notify();
 5885        proto::FollowResponse {
 5886            views: active_view.iter().cloned().collect(),
 5887            active_view,
 5888        }
 5889    }
 5890
 5891    fn handle_update_followers(
 5892        &mut self,
 5893        leader_id: PeerId,
 5894        message: proto::UpdateFollowers,
 5895        _window: &mut Window,
 5896        _cx: &mut Context<Self>,
 5897    ) {
 5898        self.leader_updates_tx
 5899            .unbounded_send((leader_id, message))
 5900            .ok();
 5901    }
 5902
 5903    async fn process_leader_update(
 5904        this: &WeakEntity<Self>,
 5905        leader_id: PeerId,
 5906        update: proto::UpdateFollowers,
 5907        cx: &mut AsyncWindowContext,
 5908    ) -> Result<()> {
 5909        match update.variant.context("invalid update")? {
 5910            proto::update_followers::Variant::CreateView(view) => {
 5911                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5912                let should_add_view = this.update(cx, |this, _| {
 5913                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5914                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5915                    } else {
 5916                        anyhow::Ok(false)
 5917                    }
 5918                })??;
 5919
 5920                if should_add_view {
 5921                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5922                }
 5923            }
 5924            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5925                let should_add_view = this.update(cx, |this, _| {
 5926                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5927                        state.active_view_id = update_active_view
 5928                            .view
 5929                            .as_ref()
 5930                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5931
 5932                        if state.active_view_id.is_some_and(|view_id| {
 5933                            !state.items_by_leader_view_id.contains_key(&view_id)
 5934                        }) {
 5935                            anyhow::Ok(true)
 5936                        } else {
 5937                            anyhow::Ok(false)
 5938                        }
 5939                    } else {
 5940                        anyhow::Ok(false)
 5941                    }
 5942                })??;
 5943
 5944                if should_add_view && let Some(view) = update_active_view.view {
 5945                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5946                }
 5947            }
 5948            proto::update_followers::Variant::UpdateView(update_view) => {
 5949                let variant = update_view.variant.context("missing update view variant")?;
 5950                let id = update_view.id.context("missing update view id")?;
 5951                let mut tasks = Vec::new();
 5952                this.update_in(cx, |this, window, cx| {
 5953                    let project = this.project.clone();
 5954                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5955                        let view_id = ViewId::from_proto(id.clone())?;
 5956                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5957                            tasks.push(item.view.apply_update_proto(
 5958                                &project,
 5959                                variant.clone(),
 5960                                window,
 5961                                cx,
 5962                            ));
 5963                        }
 5964                    }
 5965                    anyhow::Ok(())
 5966                })??;
 5967                try_join_all(tasks).await.log_err();
 5968            }
 5969        }
 5970        this.update_in(cx, |this, window, cx| {
 5971            this.leader_updated(leader_id, window, cx)
 5972        })?;
 5973        Ok(())
 5974    }
 5975
 5976    async fn add_view_from_leader(
 5977        this: WeakEntity<Self>,
 5978        leader_id: PeerId,
 5979        view: &proto::View,
 5980        cx: &mut AsyncWindowContext,
 5981    ) -> Result<()> {
 5982        let this = this.upgrade().context("workspace dropped")?;
 5983
 5984        let Some(id) = view.id.clone() else {
 5985            anyhow::bail!("no id for view");
 5986        };
 5987        let id = ViewId::from_proto(id)?;
 5988        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5989
 5990        let pane = this.update(cx, |this, _cx| {
 5991            let state = this
 5992                .follower_states
 5993                .get(&leader_id.into())
 5994                .context("stopped following")?;
 5995            anyhow::Ok(state.pane().clone())
 5996        })?;
 5997        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5998            let client = this.read(cx).client().clone();
 5999            pane.items().find_map(|item| {
 6000                let item = item.to_followable_item_handle(cx)?;
 6001                if item.remote_id(&client, window, cx) == Some(id) {
 6002                    Some(item)
 6003                } else {
 6004                    None
 6005                }
 6006            })
 6007        })?;
 6008        let item = if let Some(existing_item) = existing_item {
 6009            existing_item
 6010        } else {
 6011            let variant = view.variant.clone();
 6012            anyhow::ensure!(variant.is_some(), "missing view variant");
 6013
 6014            let task = cx.update(|window, cx| {
 6015                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 6016            })?;
 6017
 6018            let Some(task) = task else {
 6019                anyhow::bail!(
 6020                    "failed to construct view from leader (maybe from a different version of zed?)"
 6021                );
 6022            };
 6023
 6024            let mut new_item = task.await?;
 6025            pane.update_in(cx, |pane, window, cx| {
 6026                let mut item_to_remove = None;
 6027                for (ix, item) in pane.items().enumerate() {
 6028                    if let Some(item) = item.to_followable_item_handle(cx) {
 6029                        match new_item.dedup(item.as_ref(), window, cx) {
 6030                            Some(item::Dedup::KeepExisting) => {
 6031                                new_item =
 6032                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 6033                                break;
 6034                            }
 6035                            Some(item::Dedup::ReplaceExisting) => {
 6036                                item_to_remove = Some((ix, item.item_id()));
 6037                                break;
 6038                            }
 6039                            None => {}
 6040                        }
 6041                    }
 6042                }
 6043
 6044                if let Some((ix, id)) = item_to_remove {
 6045                    pane.remove_item(id, false, false, window, cx);
 6046                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 6047                }
 6048            })?;
 6049
 6050            new_item
 6051        };
 6052
 6053        this.update_in(cx, |this, window, cx| {
 6054            let state = this.follower_states.get_mut(&leader_id.into())?;
 6055            item.set_leader_id(Some(leader_id.into()), window, cx);
 6056            state.items_by_leader_view_id.insert(
 6057                id,
 6058                FollowerView {
 6059                    view: item,
 6060                    location: panel_id,
 6061                },
 6062            );
 6063
 6064            Some(())
 6065        })
 6066        .context("no follower state")?;
 6067
 6068        Ok(())
 6069    }
 6070
 6071    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6072        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 6073            return;
 6074        };
 6075
 6076        if let Some(agent_location) = self.project.read(cx).agent_location() {
 6077            let buffer_entity_id = agent_location.buffer.entity_id();
 6078            let view_id = ViewId {
 6079                creator: CollaboratorId::Agent,
 6080                id: buffer_entity_id.as_u64(),
 6081            };
 6082            follower_state.active_view_id = Some(view_id);
 6083
 6084            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 6085                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 6086                hash_map::Entry::Vacant(entry) => {
 6087                    let existing_view =
 6088                        follower_state
 6089                            .center_pane
 6090                            .read(cx)
 6091                            .items()
 6092                            .find_map(|item| {
 6093                                let item = item.to_followable_item_handle(cx)?;
 6094                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 6095                                    && item.project_item_model_ids(cx).as_slice()
 6096                                        == [buffer_entity_id]
 6097                                {
 6098                                    Some(item)
 6099                                } else {
 6100                                    None
 6101                                }
 6102                            });
 6103                    let view = existing_view.or_else(|| {
 6104                        agent_location.buffer.upgrade().and_then(|buffer| {
 6105                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 6106                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 6107                            })?
 6108                            .to_followable_item_handle(cx)
 6109                        })
 6110                    });
 6111
 6112                    view.map(|view| {
 6113                        entry.insert(FollowerView {
 6114                            view,
 6115                            location: None,
 6116                        })
 6117                    })
 6118                }
 6119            };
 6120
 6121            if let Some(item) = item {
 6122                item.view
 6123                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 6124                item.view
 6125                    .update_agent_location(agent_location.position, window, cx);
 6126            }
 6127        } else {
 6128            follower_state.active_view_id = None;
 6129        }
 6130
 6131        self.leader_updated(CollaboratorId::Agent, window, cx);
 6132    }
 6133
 6134    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 6135        let mut is_project_item = true;
 6136        let mut update = proto::UpdateActiveView::default();
 6137        if window.is_window_active() {
 6138            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 6139
 6140            if let Some(item) = active_item
 6141                && item.item_focus_handle(cx).contains_focused(window, cx)
 6142            {
 6143                let leader_id = self
 6144                    .pane_for(&*item)
 6145                    .and_then(|pane| self.leader_for_pane(&pane));
 6146                let leader_peer_id = match leader_id {
 6147                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 6148                    Some(CollaboratorId::Agent) | None => None,
 6149                };
 6150
 6151                if let Some(item) = item.to_followable_item_handle(cx) {
 6152                    let id = item
 6153                        .remote_id(&self.app_state.client, window, cx)
 6154                        .map(|id| id.to_proto());
 6155
 6156                    if let Some(id) = id
 6157                        && let Some(variant) = item.to_state_proto(window, cx)
 6158                    {
 6159                        let view = Some(proto::View {
 6160                            id,
 6161                            leader_id: leader_peer_id,
 6162                            variant: Some(variant),
 6163                            panel_id: panel_id.map(|id| id as i32),
 6164                        });
 6165
 6166                        is_project_item = item.is_project_item(window, cx);
 6167                        update = proto::UpdateActiveView { view };
 6168                    };
 6169                }
 6170            }
 6171        }
 6172
 6173        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 6174        if active_view_id != self.last_active_view_id.as_ref() {
 6175            self.last_active_view_id = active_view_id.cloned();
 6176            self.update_followers(
 6177                is_project_item,
 6178                proto::update_followers::Variant::UpdateActiveView(update),
 6179                window,
 6180                cx,
 6181            );
 6182        }
 6183    }
 6184
 6185    fn active_item_for_followers(
 6186        &self,
 6187        window: &mut Window,
 6188        cx: &mut App,
 6189    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 6190        let mut active_item = None;
 6191        let mut panel_id = None;
 6192        for dock in self.all_docks() {
 6193            if dock.focus_handle(cx).contains_focused(window, cx)
 6194                && let Some(panel) = dock.read(cx).active_panel()
 6195                && let Some(pane) = panel.pane(cx)
 6196                && let Some(item) = pane.read(cx).active_item()
 6197            {
 6198                active_item = Some(item);
 6199                panel_id = panel.remote_id();
 6200                break;
 6201            }
 6202        }
 6203
 6204        if active_item.is_none() {
 6205            active_item = self.active_pane().read(cx).active_item();
 6206        }
 6207        (active_item, panel_id)
 6208    }
 6209
 6210    fn update_followers(
 6211        &self,
 6212        project_only: bool,
 6213        update: proto::update_followers::Variant,
 6214        _: &mut Window,
 6215        cx: &mut App,
 6216    ) -> Option<()> {
 6217        // If this update only applies to for followers in the current project,
 6218        // then skip it unless this project is shared. If it applies to all
 6219        // followers, regardless of project, then set `project_id` to none,
 6220        // indicating that it goes to all followers.
 6221        let project_id = if project_only {
 6222            Some(self.project.read(cx).remote_id()?)
 6223        } else {
 6224            None
 6225        };
 6226        self.app_state().workspace_store.update(cx, |store, cx| {
 6227            store.update_followers(project_id, update, cx)
 6228        })
 6229    }
 6230
 6231    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 6232        self.follower_states.iter().find_map(|(leader_id, state)| {
 6233            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 6234                Some(*leader_id)
 6235            } else {
 6236                None
 6237            }
 6238        })
 6239    }
 6240
 6241    fn leader_updated(
 6242        &mut self,
 6243        leader_id: impl Into<CollaboratorId>,
 6244        window: &mut Window,
 6245        cx: &mut Context<Self>,
 6246    ) -> Option<Box<dyn ItemHandle>> {
 6247        cx.notify();
 6248
 6249        let leader_id = leader_id.into();
 6250        let (panel_id, item) = match leader_id {
 6251            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 6252            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 6253        };
 6254
 6255        let state = self.follower_states.get(&leader_id)?;
 6256        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 6257        let pane;
 6258        if let Some(panel_id) = panel_id {
 6259            pane = self
 6260                .activate_panel_for_proto_id(panel_id, window, cx)?
 6261                .pane(cx)?;
 6262            let state = self.follower_states.get_mut(&leader_id)?;
 6263            state.dock_pane = Some(pane.clone());
 6264        } else {
 6265            pane = state.center_pane.clone();
 6266            let state = self.follower_states.get_mut(&leader_id)?;
 6267            if let Some(dock_pane) = state.dock_pane.take() {
 6268                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 6269            }
 6270        }
 6271
 6272        pane.update(cx, |pane, cx| {
 6273            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 6274            if let Some(index) = pane.index_for_item(item.as_ref()) {
 6275                pane.activate_item(index, false, false, window, cx);
 6276            } else {
 6277                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 6278            }
 6279
 6280            if focus_active_item {
 6281                pane.focus_active_item(window, cx)
 6282            }
 6283        });
 6284
 6285        Some(item)
 6286    }
 6287
 6288    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 6289        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 6290        let active_view_id = state.active_view_id?;
 6291        Some(
 6292            state
 6293                .items_by_leader_view_id
 6294                .get(&active_view_id)?
 6295                .view
 6296                .boxed_clone(),
 6297        )
 6298    }
 6299
 6300    fn active_item_for_peer(
 6301        &self,
 6302        peer_id: PeerId,
 6303        window: &mut Window,
 6304        cx: &mut Context<Self>,
 6305    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 6306        let call = self.active_call()?;
 6307        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 6308        let leader_in_this_app;
 6309        let leader_in_this_project;
 6310        match participant.location {
 6311            ParticipantLocation::SharedProject { project_id } => {
 6312                leader_in_this_app = true;
 6313                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 6314            }
 6315            ParticipantLocation::UnsharedProject => {
 6316                leader_in_this_app = true;
 6317                leader_in_this_project = false;
 6318            }
 6319            ParticipantLocation::External => {
 6320                leader_in_this_app = false;
 6321                leader_in_this_project = false;
 6322            }
 6323        };
 6324        let state = self.follower_states.get(&peer_id.into())?;
 6325        let mut item_to_activate = None;
 6326        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 6327            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 6328                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 6329            {
 6330                item_to_activate = Some((item.location, item.view.boxed_clone()));
 6331            }
 6332        } else if let Some(shared_screen) =
 6333            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 6334        {
 6335            item_to_activate = Some((None, Box::new(shared_screen)));
 6336        }
 6337        item_to_activate
 6338    }
 6339
 6340    fn shared_screen_for_peer(
 6341        &self,
 6342        peer_id: PeerId,
 6343        pane: &Entity<Pane>,
 6344        window: &mut Window,
 6345        cx: &mut App,
 6346    ) -> Option<Entity<SharedScreen>> {
 6347        self.active_call()?
 6348            .create_shared_screen(peer_id, pane, window, cx)
 6349    }
 6350
 6351    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6352        if window.is_window_active() {
 6353            self.update_active_view_for_followers(window, cx);
 6354
 6355            if let Some(database_id) = self.database_id {
 6356                let db = WorkspaceDb::global(cx);
 6357                cx.background_spawn(async move { db.update_timestamp(database_id).await })
 6358                    .detach();
 6359            }
 6360        } else {
 6361            for pane in &self.panes {
 6362                pane.update(cx, |pane, cx| {
 6363                    if let Some(item) = pane.active_item() {
 6364                        item.workspace_deactivated(window, cx);
 6365                    }
 6366                    for item in pane.items() {
 6367                        if matches!(
 6368                            item.workspace_settings(cx).autosave,
 6369                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6370                        ) {
 6371                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6372                                .detach_and_log_err(cx);
 6373                        }
 6374                    }
 6375                });
 6376            }
 6377        }
 6378    }
 6379
 6380    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6381        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6382    }
 6383
 6384    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6385        self.active_call.as_ref().map(|(call, _)| call.clone())
 6386    }
 6387
 6388    fn on_active_call_event(
 6389        &mut self,
 6390        event: &ActiveCallEvent,
 6391        window: &mut Window,
 6392        cx: &mut Context<Self>,
 6393    ) {
 6394        match event {
 6395            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6396            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6397                self.leader_updated(participant_id, window, cx);
 6398            }
 6399        }
 6400    }
 6401
 6402    pub fn database_id(&self) -> Option<WorkspaceId> {
 6403        self.database_id
 6404    }
 6405
 6406    #[cfg(any(test, feature = "test-support"))]
 6407    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6408        self.database_id = Some(id);
 6409    }
 6410
 6411    pub fn session_id(&self) -> Option<String> {
 6412        self.session_id.clone()
 6413    }
 6414
 6415    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6416        let Some(display) = window.display(cx) else {
 6417            return Task::ready(());
 6418        };
 6419        let Ok(display_uuid) = display.uuid() else {
 6420            return Task::ready(());
 6421        };
 6422
 6423        let window_bounds = window.inner_window_bounds();
 6424        let database_id = self.database_id;
 6425        let has_paths = !self.root_paths(cx).is_empty();
 6426        let db = WorkspaceDb::global(cx);
 6427        let kvp = db::kvp::KeyValueStore::global(cx);
 6428
 6429        cx.background_executor().spawn(async move {
 6430            if !has_paths {
 6431                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6432                    .await
 6433                    .log_err();
 6434            }
 6435            if let Some(database_id) = database_id {
 6436                db.set_window_open_status(
 6437                    database_id,
 6438                    SerializedWindowBounds(window_bounds),
 6439                    display_uuid,
 6440                )
 6441                .await
 6442                .log_err();
 6443            } else {
 6444                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6445                    .await
 6446                    .log_err();
 6447            }
 6448        })
 6449    }
 6450
 6451    /// Bypass the 200ms serialization throttle and write workspace state to
 6452    /// the DB immediately. Returns a task the caller can await to ensure the
 6453    /// write completes. Used by the quit handler so the most recent state
 6454    /// isn't lost to a pending throttle timer when the process exits.
 6455    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6456        self._schedule_serialize_workspace.take();
 6457        self._serialize_workspace_task.take();
 6458        self.bounds_save_task_queued.take();
 6459
 6460        let bounds_task = self.save_window_bounds(window, cx);
 6461        let serialize_task = self.serialize_workspace_internal(window, cx);
 6462        cx.spawn(async move |_| {
 6463            bounds_task.await;
 6464            serialize_task.await;
 6465        })
 6466    }
 6467
 6468    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6469        let project = self.project().read(cx);
 6470        project
 6471            .visible_worktrees(cx)
 6472            .map(|worktree| worktree.read(cx).abs_path())
 6473            .collect::<Vec<_>>()
 6474    }
 6475
 6476    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6477        match member {
 6478            Member::Axis(PaneAxis { members, .. }) => {
 6479                for child in members.iter() {
 6480                    self.remove_panes(child.clone(), window, cx)
 6481                }
 6482            }
 6483            Member::Pane(pane) => {
 6484                self.force_remove_pane(&pane, &None, window, cx);
 6485            }
 6486        }
 6487    }
 6488
 6489    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6490        self.session_id.take();
 6491        self.serialize_workspace_internal(window, cx)
 6492    }
 6493
 6494    fn force_remove_pane(
 6495        &mut self,
 6496        pane: &Entity<Pane>,
 6497        focus_on: &Option<Entity<Pane>>,
 6498        window: &mut Window,
 6499        cx: &mut Context<Workspace>,
 6500    ) {
 6501        self.panes.retain(|p| p != pane);
 6502        if let Some(focus_on) = focus_on {
 6503            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6504        } else if self.active_pane() == pane {
 6505            let fallback_pane = self.panes.last().unwrap().clone();
 6506            if self.has_active_modal(window, cx) {
 6507                self.set_active_pane(&fallback_pane, window, cx);
 6508            } else {
 6509                fallback_pane.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6510            }
 6511        }
 6512        if self.last_active_center_pane == Some(pane.downgrade()) {
 6513            self.last_active_center_pane = None;
 6514        }
 6515        cx.notify();
 6516    }
 6517
 6518    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6519        if self._schedule_serialize_workspace.is_none() {
 6520            self._schedule_serialize_workspace =
 6521                Some(cx.spawn_in(window, async move |this, cx| {
 6522                    cx.background_executor()
 6523                        .timer(SERIALIZATION_THROTTLE_TIME)
 6524                        .await;
 6525                    this.update_in(cx, |this, window, cx| {
 6526                        this._serialize_workspace_task =
 6527                            Some(this.serialize_workspace_internal(window, cx));
 6528                        this._schedule_serialize_workspace.take();
 6529                    })
 6530                    .log_err();
 6531                }));
 6532        }
 6533    }
 6534
 6535    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6536        let Some(database_id) = self.database_id() else {
 6537            return Task::ready(());
 6538        };
 6539
 6540        fn serialize_pane_handle(
 6541            pane_handle: &Entity<Pane>,
 6542            window: &mut Window,
 6543            cx: &mut App,
 6544        ) -> SerializedPane {
 6545            let (items, active, pinned_count) = {
 6546                let pane = pane_handle.read(cx);
 6547                let active_item_id = pane.active_item().map(|item| item.item_id());
 6548                (
 6549                    pane.items()
 6550                        .filter_map(|handle| {
 6551                            let handle = handle.to_serializable_item_handle(cx)?;
 6552
 6553                            Some(SerializedItem {
 6554                                kind: Arc::from(handle.serialized_item_kind()),
 6555                                item_id: handle.item_id().as_u64(),
 6556                                active: Some(handle.item_id()) == active_item_id,
 6557                                preview: pane.is_active_preview_item(handle.item_id()),
 6558                            })
 6559                        })
 6560                        .collect::<Vec<_>>(),
 6561                    pane.has_focus(window, cx),
 6562                    pane.pinned_count(),
 6563                )
 6564            };
 6565
 6566            SerializedPane::new(items, active, pinned_count)
 6567        }
 6568
 6569        fn build_serialized_pane_group(
 6570            pane_group: &Member,
 6571            window: &mut Window,
 6572            cx: &mut App,
 6573        ) -> SerializedPaneGroup {
 6574            match pane_group {
 6575                Member::Axis(PaneAxis {
 6576                    axis,
 6577                    members,
 6578                    flexes,
 6579                    bounding_boxes: _,
 6580                }) => SerializedPaneGroup::Group {
 6581                    axis: SerializedAxis(*axis),
 6582                    children: members
 6583                        .iter()
 6584                        .map(|member| build_serialized_pane_group(member, window, cx))
 6585                        .collect::<Vec<_>>(),
 6586                    flexes: Some(flexes.lock().clone()),
 6587                },
 6588                Member::Pane(pane_handle) => {
 6589                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6590                }
 6591            }
 6592        }
 6593
 6594        fn build_serialized_docks(
 6595            this: &Workspace,
 6596            window: &mut Window,
 6597            cx: &mut App,
 6598        ) -> DockStructure {
 6599            this.capture_dock_state(window, cx)
 6600        }
 6601
 6602        match self.workspace_location(cx) {
 6603            WorkspaceLocation::Location(location, paths) => {
 6604                let breakpoints = self.project.update(cx, |project, cx| {
 6605                    project
 6606                        .breakpoint_store()
 6607                        .read(cx)
 6608                        .all_source_breakpoints(cx)
 6609                });
 6610                let user_toolchains = self
 6611                    .project
 6612                    .read(cx)
 6613                    .user_toolchains(cx)
 6614                    .unwrap_or_default();
 6615
 6616                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6617                let docks = build_serialized_docks(self, window, cx);
 6618                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6619
 6620                let serialized_workspace = SerializedWorkspace {
 6621                    id: database_id,
 6622                    location,
 6623                    paths,
 6624                    center_group,
 6625                    window_bounds,
 6626                    display: Default::default(),
 6627                    docks,
 6628                    centered_layout: self.centered_layout,
 6629                    session_id: self.session_id.clone(),
 6630                    breakpoints,
 6631                    window_id: Some(window.window_handle().window_id().as_u64()),
 6632                    user_toolchains,
 6633                };
 6634
 6635                let db = WorkspaceDb::global(cx);
 6636                window.spawn(cx, async move |_| {
 6637                    db.save_workspace(serialized_workspace).await;
 6638                })
 6639            }
 6640            WorkspaceLocation::DetachFromSession => {
 6641                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6642                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6643                // Save dock state for empty local workspaces
 6644                let docks = build_serialized_docks(self, window, cx);
 6645                let db = WorkspaceDb::global(cx);
 6646                let kvp = db::kvp::KeyValueStore::global(cx);
 6647                window.spawn(cx, async move |_| {
 6648                    db.set_window_open_status(
 6649                        database_id,
 6650                        window_bounds,
 6651                        display.unwrap_or_default(),
 6652                    )
 6653                    .await
 6654                    .log_err();
 6655                    db.set_session_id(database_id, None).await.log_err();
 6656                    persistence::write_default_dock_state(&kvp, docks)
 6657                        .await
 6658                        .log_err();
 6659                })
 6660            }
 6661            WorkspaceLocation::None => {
 6662                // Save dock state for empty non-local workspaces
 6663                let docks = build_serialized_docks(self, window, cx);
 6664                let kvp = db::kvp::KeyValueStore::global(cx);
 6665                window.spawn(cx, async move |_| {
 6666                    persistence::write_default_dock_state(&kvp, docks)
 6667                        .await
 6668                        .log_err();
 6669                })
 6670            }
 6671        }
 6672    }
 6673
 6674    fn has_any_items_open(&self, cx: &App) -> bool {
 6675        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6676    }
 6677
 6678    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6679        let paths = PathList::new(&self.root_paths(cx));
 6680        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6681            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6682        } else if self.project.read(cx).is_local() {
 6683            if !paths.is_empty() || self.has_any_items_open(cx) {
 6684                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6685            } else {
 6686                WorkspaceLocation::DetachFromSession
 6687            }
 6688        } else {
 6689            WorkspaceLocation::None
 6690        }
 6691    }
 6692
 6693    fn update_history(&self, cx: &mut App) {
 6694        let Some(id) = self.database_id() else {
 6695            return;
 6696        };
 6697        if !self.project.read(cx).is_local() {
 6698            return;
 6699        }
 6700        if let Some(manager) = HistoryManager::global(cx) {
 6701            let paths = PathList::new(&self.root_paths(cx));
 6702            manager.update(cx, |this, cx| {
 6703                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6704            });
 6705        }
 6706    }
 6707
 6708    async fn serialize_items(
 6709        this: &WeakEntity<Self>,
 6710        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6711        cx: &mut AsyncWindowContext,
 6712    ) -> Result<()> {
 6713        const CHUNK_SIZE: usize = 200;
 6714
 6715        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6716
 6717        while let Some(items_received) = serializable_items.next().await {
 6718            let unique_items =
 6719                items_received
 6720                    .into_iter()
 6721                    .fold(HashMap::default(), |mut acc, item| {
 6722                        acc.entry(item.item_id()).or_insert(item);
 6723                        acc
 6724                    });
 6725
 6726            // We use into_iter() here so that the references to the items are moved into
 6727            // the tasks and not kept alive while we're sleeping.
 6728            for (_, item) in unique_items.into_iter() {
 6729                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6730                    item.serialize(workspace, false, window, cx)
 6731                }) {
 6732                    cx.background_spawn(async move { task.await.log_err() })
 6733                        .detach();
 6734                }
 6735            }
 6736
 6737            cx.background_executor()
 6738                .timer(SERIALIZATION_THROTTLE_TIME)
 6739                .await;
 6740        }
 6741
 6742        Ok(())
 6743    }
 6744
 6745    pub(crate) fn enqueue_item_serialization(
 6746        &mut self,
 6747        item: Box<dyn SerializableItemHandle>,
 6748    ) -> Result<()> {
 6749        self.serializable_items_tx
 6750            .unbounded_send(item)
 6751            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6752    }
 6753
 6754    pub(crate) fn load_workspace(
 6755        serialized_workspace: SerializedWorkspace,
 6756        paths_to_open: Vec<Option<ProjectPath>>,
 6757        window: &mut Window,
 6758        cx: &mut Context<Workspace>,
 6759    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6760        cx.spawn_in(window, async move |workspace, cx| {
 6761            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6762
 6763            let mut center_group = None;
 6764            let mut center_items = None;
 6765
 6766            // Traverse the splits tree and add to things
 6767            if let Some((group, active_pane, items)) = serialized_workspace
 6768                .center_group
 6769                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6770                .await
 6771            {
 6772                center_items = Some(items);
 6773                center_group = Some((group, active_pane))
 6774            }
 6775
 6776            let mut items_by_project_path = HashMap::default();
 6777            let mut item_ids_by_kind = HashMap::default();
 6778            let mut all_deserialized_items = Vec::default();
 6779            cx.update(|_, cx| {
 6780                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6781                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6782                        item_ids_by_kind
 6783                            .entry(serializable_item_handle.serialized_item_kind())
 6784                            .or_insert(Vec::new())
 6785                            .push(item.item_id().as_u64() as ItemId);
 6786                    }
 6787
 6788                    if let Some(project_path) = item.project_path(cx) {
 6789                        items_by_project_path.insert(project_path, item.clone());
 6790                    }
 6791                    all_deserialized_items.push(item);
 6792                }
 6793            })?;
 6794
 6795            let opened_items = paths_to_open
 6796                .into_iter()
 6797                .map(|path_to_open| {
 6798                    path_to_open
 6799                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6800                })
 6801                .collect::<Vec<_>>();
 6802
 6803            // Remove old panes from workspace panes list
 6804            workspace.update_in(cx, |workspace, window, cx| {
 6805                if let Some((center_group, active_pane)) = center_group {
 6806                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6807
 6808                    // Swap workspace center group
 6809                    workspace.center = PaneGroup::with_root(center_group);
 6810                    workspace.center.set_is_center(true);
 6811                    workspace.center.mark_positions(cx);
 6812
 6813                    if let Some(active_pane) = active_pane {
 6814                        workspace.set_active_pane(&active_pane, window, cx);
 6815                        cx.focus_self(window);
 6816                    } else {
 6817                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6818                    }
 6819                }
 6820
 6821                let docks = serialized_workspace.docks;
 6822
 6823                for (dock, serialized_dock) in [
 6824                    (&mut workspace.right_dock, docks.right),
 6825                    (&mut workspace.left_dock, docks.left),
 6826                    (&mut workspace.bottom_dock, docks.bottom),
 6827                ]
 6828                .iter_mut()
 6829                {
 6830                    dock.update(cx, |dock, cx| {
 6831                        dock.serialized_dock = Some(serialized_dock.clone());
 6832                        dock.restore_state(window, cx);
 6833                    });
 6834                }
 6835
 6836                cx.notify();
 6837            })?;
 6838
 6839            let _ = project
 6840                .update(cx, |project, cx| {
 6841                    project
 6842                        .breakpoint_store()
 6843                        .update(cx, |breakpoint_store, cx| {
 6844                            breakpoint_store
 6845                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6846                        })
 6847                })
 6848                .await;
 6849
 6850            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6851            // after loading the items, we might have different items and in order to avoid
 6852            // the database filling up, we delete items that haven't been loaded now.
 6853            //
 6854            // The items that have been loaded, have been saved after they've been added to the workspace.
 6855            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6856                item_ids_by_kind
 6857                    .into_iter()
 6858                    .map(|(item_kind, loaded_items)| {
 6859                        SerializableItemRegistry::cleanup(
 6860                            item_kind,
 6861                            serialized_workspace.id,
 6862                            loaded_items,
 6863                            window,
 6864                            cx,
 6865                        )
 6866                        .log_err()
 6867                    })
 6868                    .collect::<Vec<_>>()
 6869            })?;
 6870
 6871            futures::future::join_all(clean_up_tasks).await;
 6872
 6873            workspace
 6874                .update_in(cx, |workspace, window, cx| {
 6875                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6876                    workspace.serialize_workspace_internal(window, cx).detach();
 6877
 6878                    // Ensure that we mark the window as edited if we did load dirty items
 6879                    workspace.update_window_edited(window, cx);
 6880                })
 6881                .ok();
 6882
 6883            Ok(opened_items)
 6884        })
 6885    }
 6886
 6887    pub fn key_context(&self, cx: &App) -> KeyContext {
 6888        let mut context = KeyContext::new_with_defaults();
 6889        context.add("Workspace");
 6890        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6891        if let Some(status) = self
 6892            .debugger_provider
 6893            .as_ref()
 6894            .and_then(|provider| provider.active_thread_state(cx))
 6895        {
 6896            match status {
 6897                ThreadStatus::Running | ThreadStatus::Stepping => {
 6898                    context.add("debugger_running");
 6899                }
 6900                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6901                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6902            }
 6903        }
 6904
 6905        if self.left_dock.read(cx).is_open() {
 6906            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6907                context.set("left_dock", active_panel.panel_key());
 6908            }
 6909        }
 6910
 6911        if self.right_dock.read(cx).is_open() {
 6912            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6913                context.set("right_dock", active_panel.panel_key());
 6914            }
 6915        }
 6916
 6917        if self.bottom_dock.read(cx).is_open() {
 6918            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6919                context.set("bottom_dock", active_panel.panel_key());
 6920            }
 6921        }
 6922
 6923        context
 6924    }
 6925
 6926    /// Multiworkspace uses this to add workspace action handling to itself
 6927    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6928        self.add_workspace_actions_listeners(div, window, cx)
 6929            .on_action(cx.listener(
 6930                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6931                    for action in &action_sequence.0 {
 6932                        window.dispatch_action(action.boxed_clone(), cx);
 6933                    }
 6934                },
 6935            ))
 6936            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6937            .on_action(cx.listener(Self::close_all_items_and_panes))
 6938            .on_action(cx.listener(Self::close_item_in_all_panes))
 6939            .on_action(cx.listener(Self::save_all))
 6940            .on_action(cx.listener(Self::send_keystrokes))
 6941            .on_action(cx.listener(Self::add_folder_to_project))
 6942            .on_action(cx.listener(Self::follow_next_collaborator))
 6943            .on_action(cx.listener(Self::activate_pane_at_index))
 6944            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6945            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6946            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6947            .on_action(cx.listener(Self::toggle_theme_mode))
 6948            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6949                let pane = workspace.active_pane().clone();
 6950                workspace.unfollow_in_pane(&pane, window, cx);
 6951            }))
 6952            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6953                workspace
 6954                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6955                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6956            }))
 6957            .on_action(cx.listener(|workspace, _: &FormatAndSave, window, cx| {
 6958                workspace
 6959                    .save_active_item(SaveIntent::FormatAndSave, window, cx)
 6960                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6961            }))
 6962            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6963                workspace
 6964                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6965                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6966            }))
 6967            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6968                workspace
 6969                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6970                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6971            }))
 6972            .on_action(
 6973                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6974                    workspace.activate_previous_pane(window, cx)
 6975                }),
 6976            )
 6977            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6978                workspace.activate_next_pane(window, cx)
 6979            }))
 6980            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6981                workspace.activate_last_pane(window, cx)
 6982            }))
 6983            .on_action(
 6984                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6985                    workspace.activate_next_window(cx)
 6986                }),
 6987            )
 6988            .on_action(
 6989                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6990                    workspace.activate_previous_window(cx)
 6991                }),
 6992            )
 6993            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6994                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6995            }))
 6996            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6997                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6998            }))
 6999            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 7000                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 7001            }))
 7002            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 7003                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 7004            }))
 7005            .on_action(cx.listener(
 7006                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 7007                    workspace.move_item_to_pane_in_direction(action, window, cx)
 7008                },
 7009            ))
 7010            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 7011                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 7012            }))
 7013            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 7014                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 7015            }))
 7016            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 7017                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 7018            }))
 7019            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 7020                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 7021            }))
 7022            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 7023                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 7024                    SplitDirection::Down,
 7025                    SplitDirection::Up,
 7026                    SplitDirection::Right,
 7027                    SplitDirection::Left,
 7028                ];
 7029                for dir in DIRECTION_PRIORITY {
 7030                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 7031                        workspace.swap_pane_in_direction(dir, cx);
 7032                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 7033                        break;
 7034                    }
 7035                }
 7036            }))
 7037            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 7038                workspace.move_pane_to_border(SplitDirection::Left, cx)
 7039            }))
 7040            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 7041                workspace.move_pane_to_border(SplitDirection::Right, cx)
 7042            }))
 7043            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 7044                workspace.move_pane_to_border(SplitDirection::Up, cx)
 7045            }))
 7046            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 7047                workspace.move_pane_to_border(SplitDirection::Down, cx)
 7048            }))
 7049            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 7050                this.toggle_dock(DockPosition::Left, window, cx);
 7051            }))
 7052            .on_action(cx.listener(
 7053                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 7054                    workspace.toggle_dock(DockPosition::Right, window, cx);
 7055                },
 7056            ))
 7057            .on_action(cx.listener(
 7058                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 7059                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 7060                },
 7061            ))
 7062            .on_action(cx.listener(
 7063                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 7064                    if !workspace.close_active_dock(window, cx) {
 7065                        cx.propagate();
 7066                    }
 7067                },
 7068            ))
 7069            .on_action(
 7070                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 7071                    workspace.close_all_docks(window, cx);
 7072                }),
 7073            )
 7074            .on_action(cx.listener(Self::toggle_all_docks))
 7075            .on_action(cx.listener(
 7076                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 7077                    workspace.clear_all_notifications(cx);
 7078                },
 7079            ))
 7080            .on_action(cx.listener(
 7081                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 7082                    workspace.clear_navigation_history(window, cx);
 7083                },
 7084            ))
 7085            .on_action(cx.listener(
 7086                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 7087                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 7088                        workspace.suppress_notification(&notification_id, cx);
 7089                    }
 7090                },
 7091            ))
 7092            .on_action(cx.listener(
 7093                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 7094                    workspace.show_worktree_trust_security_modal(true, window, cx);
 7095                },
 7096            ))
 7097            .on_action(
 7098                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 7099                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 7100                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 7101                            trusted_worktrees.clear_trusted_paths()
 7102                        });
 7103                        let db = WorkspaceDb::global(cx);
 7104                        cx.spawn(async move |_, cx| {
 7105                            if db.clear_trusted_worktrees().await.log_err().is_some() {
 7106                                cx.update(|cx| reload(cx));
 7107                            }
 7108                        })
 7109                        .detach();
 7110                    }
 7111                }),
 7112            )
 7113            .on_action(cx.listener(
 7114                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 7115                    workspace.reopen_closed_item(window, cx).detach();
 7116                },
 7117            ))
 7118            .on_action(cx.listener(
 7119                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 7120                    for dock in workspace.all_docks() {
 7121                        if dock.focus_handle(cx).contains_focused(window, cx) {
 7122                            let panel = dock.read(cx).active_panel().cloned();
 7123                            if let Some(panel) = panel {
 7124                                dock.update(cx, |dock, cx| {
 7125                                    dock.set_panel_size_state(
 7126                                        panel.as_ref(),
 7127                                        dock::PanelSizeState::default(),
 7128                                        cx,
 7129                                    );
 7130                                });
 7131                            }
 7132                            return;
 7133                        }
 7134                    }
 7135                },
 7136            ))
 7137            .on_action(cx.listener(
 7138                |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
 7139                    for dock in workspace.all_docks() {
 7140                        let panel = dock.read(cx).visible_panel().cloned();
 7141                        if let Some(panel) = panel {
 7142                            dock.update(cx, |dock, cx| {
 7143                                dock.set_panel_size_state(
 7144                                    panel.as_ref(),
 7145                                    dock::PanelSizeState::default(),
 7146                                    cx,
 7147                                );
 7148                            });
 7149                        }
 7150                    }
 7151                },
 7152            ))
 7153            .on_action(cx.listener(
 7154                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 7155                    adjust_active_dock_size_by_px(
 7156                        px_with_ui_font_fallback(act.px, cx),
 7157                        workspace,
 7158                        window,
 7159                        cx,
 7160                    );
 7161                },
 7162            ))
 7163            .on_action(cx.listener(
 7164                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 7165                    adjust_active_dock_size_by_px(
 7166                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7167                        workspace,
 7168                        window,
 7169                        cx,
 7170                    );
 7171                },
 7172            ))
 7173            .on_action(cx.listener(
 7174                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 7175                    adjust_open_docks_size_by_px(
 7176                        px_with_ui_font_fallback(act.px, cx),
 7177                        workspace,
 7178                        window,
 7179                        cx,
 7180                    );
 7181                },
 7182            ))
 7183            .on_action(cx.listener(
 7184                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 7185                    adjust_open_docks_size_by_px(
 7186                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7187                        workspace,
 7188                        window,
 7189                        cx,
 7190                    );
 7191                },
 7192            ))
 7193            .on_action(cx.listener(Workspace::toggle_centered_layout))
 7194            .on_action(cx.listener(
 7195                |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
 7196                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7197                        let dock = active_dock.read(cx);
 7198                        if let Some(active_panel) = dock.active_panel() {
 7199                            if active_panel.pane(cx).is_none() {
 7200                                let mut recent_pane: Option<Entity<Pane>> = None;
 7201                                let mut recent_timestamp = 0;
 7202                                for pane_handle in workspace.panes() {
 7203                                    let pane = pane_handle.read(cx);
 7204                                    for entry in pane.activation_history() {
 7205                                        if entry.timestamp > recent_timestamp {
 7206                                            recent_timestamp = entry.timestamp;
 7207                                            recent_pane = Some(pane_handle.clone());
 7208                                        }
 7209                                    }
 7210                                }
 7211
 7212                                if let Some(pane) = recent_pane {
 7213                                    let wrap_around = action.wrap_around;
 7214                                    pane.update(cx, |pane, cx| {
 7215                                        let current_index = pane.active_item_index();
 7216                                        let items_len = pane.items_len();
 7217                                        if items_len > 0 {
 7218                                            let next_index = if current_index + 1 < items_len {
 7219                                                current_index + 1
 7220                                            } else if wrap_around {
 7221                                                0
 7222                                            } else {
 7223                                                return;
 7224                                            };
 7225                                            pane.activate_item(
 7226                                                next_index, false, false, window, cx,
 7227                                            );
 7228                                        }
 7229                                    });
 7230                                    return;
 7231                                }
 7232                            }
 7233                        }
 7234                    }
 7235                    cx.propagate();
 7236                },
 7237            ))
 7238            .on_action(cx.listener(
 7239                |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
 7240                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7241                        let dock = active_dock.read(cx);
 7242                        if let Some(active_panel) = dock.active_panel() {
 7243                            if active_panel.pane(cx).is_none() {
 7244                                let mut recent_pane: Option<Entity<Pane>> = None;
 7245                                let mut recent_timestamp = 0;
 7246                                for pane_handle in workspace.panes() {
 7247                                    let pane = pane_handle.read(cx);
 7248                                    for entry in pane.activation_history() {
 7249                                        if entry.timestamp > recent_timestamp {
 7250                                            recent_timestamp = entry.timestamp;
 7251                                            recent_pane = Some(pane_handle.clone());
 7252                                        }
 7253                                    }
 7254                                }
 7255
 7256                                if let Some(pane) = recent_pane {
 7257                                    let wrap_around = action.wrap_around;
 7258                                    pane.update(cx, |pane, cx| {
 7259                                        let current_index = pane.active_item_index();
 7260                                        let items_len = pane.items_len();
 7261                                        if items_len > 0 {
 7262                                            let prev_index = if current_index > 0 {
 7263                                                current_index - 1
 7264                                            } else if wrap_around {
 7265                                                items_len.saturating_sub(1)
 7266                                            } else {
 7267                                                return;
 7268                                            };
 7269                                            pane.activate_item(
 7270                                                prev_index, false, false, window, cx,
 7271                                            );
 7272                                        }
 7273                                    });
 7274                                    return;
 7275                                }
 7276                            }
 7277                        }
 7278                    }
 7279                    cx.propagate();
 7280                },
 7281            ))
 7282            .on_action(cx.listener(
 7283                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 7284                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7285                        let dock = active_dock.read(cx);
 7286                        if let Some(active_panel) = dock.active_panel() {
 7287                            if active_panel.pane(cx).is_none() {
 7288                                let active_pane = workspace.active_pane().clone();
 7289                                active_pane.update(cx, |pane, cx| {
 7290                                    pane.close_active_item(action, window, cx)
 7291                                        .detach_and_log_err(cx);
 7292                                });
 7293                                return;
 7294                            }
 7295                        }
 7296                    }
 7297                    cx.propagate();
 7298                },
 7299            ))
 7300            .on_action(
 7301                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 7302                    let pane = workspace.active_pane().clone();
 7303                    if let Some(item) = pane.read(cx).active_item() {
 7304                        item.toggle_read_only(window, cx);
 7305                    }
 7306                }),
 7307            )
 7308            .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
 7309                workspace.focus_center_pane(window, cx);
 7310            }))
 7311            .on_action(cx.listener(Workspace::cancel))
 7312    }
 7313
 7314    #[cfg(any(test, feature = "test-support"))]
 7315    pub fn set_random_database_id(&mut self) {
 7316        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 7317    }
 7318
 7319    #[cfg(any(test, feature = "test-support"))]
 7320    pub(crate) fn test_new(
 7321        project: Entity<Project>,
 7322        window: &mut Window,
 7323        cx: &mut Context<Self>,
 7324    ) -> Self {
 7325        use node_runtime::NodeRuntime;
 7326        use session::Session;
 7327
 7328        let client = project.read(cx).client();
 7329        let user_store = project.read(cx).user_store();
 7330        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 7331        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 7332        window.activate_window();
 7333        let app_state = Arc::new(AppState {
 7334            languages: project.read(cx).languages().clone(),
 7335            workspace_store,
 7336            client,
 7337            user_store,
 7338            fs: project.read(cx).fs().clone(),
 7339            build_window_options: |_, _| Default::default(),
 7340            node_runtime: NodeRuntime::unavailable(),
 7341            session,
 7342        });
 7343        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 7344        workspace
 7345            .active_pane
 7346            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 7347        workspace
 7348    }
 7349
 7350    pub fn register_action<A: Action>(
 7351        &mut self,
 7352        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 7353    ) -> &mut Self {
 7354        let callback = Arc::new(callback);
 7355
 7356        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 7357            let callback = callback.clone();
 7358            div.on_action(cx.listener(move |workspace, event, window, cx| {
 7359                (callback)(workspace, event, window, cx)
 7360            }))
 7361        }));
 7362        self
 7363    }
 7364    pub fn register_action_renderer(
 7365        &mut self,
 7366        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 7367    ) -> &mut Self {
 7368        self.workspace_actions.push(Box::new(callback));
 7369        self
 7370    }
 7371
 7372    fn add_workspace_actions_listeners(
 7373        &self,
 7374        mut div: Div,
 7375        window: &mut Window,
 7376        cx: &mut Context<Self>,
 7377    ) -> Div {
 7378        for action in self.workspace_actions.iter() {
 7379            div = (action)(div, self, window, cx)
 7380        }
 7381        div
 7382    }
 7383
 7384    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 7385        self.modal_layer.read(cx).has_active_modal()
 7386    }
 7387
 7388    pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
 7389        self.modal_layer
 7390            .read(cx)
 7391            .is_active_modal_command_palette(cx)
 7392    }
 7393
 7394    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7395        self.modal_layer.read(cx).active_modal()
 7396    }
 7397
 7398    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7399    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7400    /// If no modal is active, the new modal will be shown.
 7401    ///
 7402    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7403    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7404    /// will not be shown.
 7405    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7406    where
 7407        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7408    {
 7409        self.modal_layer.update(cx, |modal_layer, cx| {
 7410            modal_layer.toggle_modal(window, cx, build)
 7411        })
 7412    }
 7413
 7414    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7415        self.modal_layer
 7416            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7417    }
 7418
 7419    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7420        self.toast_layer
 7421            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7422    }
 7423
 7424    pub fn toggle_centered_layout(
 7425        &mut self,
 7426        _: &ToggleCenteredLayout,
 7427        _: &mut Window,
 7428        cx: &mut Context<Self>,
 7429    ) {
 7430        self.centered_layout = !self.centered_layout;
 7431        if let Some(database_id) = self.database_id() {
 7432            let db = WorkspaceDb::global(cx);
 7433            let centered_layout = self.centered_layout;
 7434            cx.background_spawn(async move {
 7435                db.set_centered_layout(database_id, centered_layout).await
 7436            })
 7437            .detach_and_log_err(cx);
 7438        }
 7439        cx.notify();
 7440    }
 7441
 7442    fn adjust_padding(padding: Option<f32>) -> f32 {
 7443        padding
 7444            .unwrap_or(CenteredPaddingSettings::default().0)
 7445            .clamp(
 7446                CenteredPaddingSettings::MIN_PADDING,
 7447                CenteredPaddingSettings::MAX_PADDING,
 7448            )
 7449    }
 7450
 7451    fn render_dock(
 7452        &self,
 7453        position: DockPosition,
 7454        dock: &Entity<Dock>,
 7455        window: &mut Window,
 7456        cx: &mut App,
 7457    ) -> Option<Div> {
 7458        if self.zoomed_position == Some(position) {
 7459            return None;
 7460        }
 7461
 7462        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7463            let pane = panel.pane(cx)?;
 7464            let follower_states = &self.follower_states;
 7465            leader_border_for_pane(follower_states, &pane, window, cx)
 7466        });
 7467
 7468        let mut container = div()
 7469            .flex()
 7470            .overflow_hidden()
 7471            .flex_none()
 7472            .child(dock.clone())
 7473            .children(leader_border);
 7474
 7475        // Apply sizing only when the dock is open. When closed the dock is still
 7476        // included in the element tree so its focus handle remains mounted — without
 7477        // this, toggle_panel_focus cannot focus the panel when the dock is closed.
 7478        let dock = dock.read(cx);
 7479        if let Some(panel) = dock.visible_panel() {
 7480            let size_state = dock.stored_panel_size_state(panel.as_ref());
 7481            let min_size = panel.min_size(window, cx);
 7482            if position.axis() == Axis::Horizontal {
 7483                let use_flexible = panel.has_flexible_size(window, cx);
 7484                let flex_grow = if use_flexible {
 7485                    size_state
 7486                        .and_then(|state| state.flex)
 7487                        .or_else(|| self.default_dock_flex(position))
 7488                } else {
 7489                    None
 7490                };
 7491                if let Some(grow) = flex_grow {
 7492                    let grow = (grow / self.center_full_height_column_count()).max(0.001);
 7493                    let style = container.style();
 7494                    style.flex_grow = Some(grow);
 7495                    style.flex_shrink = Some(1.0);
 7496                    style.flex_basis = Some(relative(0.).into());
 7497                } else {
 7498                    let size = size_state
 7499                        .and_then(|state| state.size)
 7500                        .unwrap_or_else(|| panel.default_size(window, cx));
 7501                    container = container.w(size);
 7502                }
 7503                if let Some(min) = min_size {
 7504                    container = container.min_w(min);
 7505                }
 7506            } else {
 7507                let size = size_state
 7508                    .and_then(|state| state.size)
 7509                    .unwrap_or_else(|| panel.default_size(window, cx));
 7510                container = container.h(size);
 7511            }
 7512        }
 7513
 7514        Some(container)
 7515    }
 7516
 7517    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7518        window
 7519            .root::<MultiWorkspace>()
 7520            .flatten()
 7521            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7522    }
 7523
 7524    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7525        self.zoomed.as_ref()
 7526    }
 7527
 7528    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7529        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7530            return;
 7531        };
 7532        let windows = cx.windows();
 7533        let next_window =
 7534            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7535                || {
 7536                    windows
 7537                        .iter()
 7538                        .cycle()
 7539                        .skip_while(|window| window.window_id() != current_window_id)
 7540                        .nth(1)
 7541                },
 7542            );
 7543
 7544        if let Some(window) = next_window {
 7545            window
 7546                .update(cx, |_, window, _| window.activate_window())
 7547                .ok();
 7548        }
 7549    }
 7550
 7551    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7552        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7553            return;
 7554        };
 7555        let windows = cx.windows();
 7556        let prev_window =
 7557            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7558                || {
 7559                    windows
 7560                        .iter()
 7561                        .rev()
 7562                        .cycle()
 7563                        .skip_while(|window| window.window_id() != current_window_id)
 7564                        .nth(1)
 7565                },
 7566            );
 7567
 7568        if let Some(window) = prev_window {
 7569            window
 7570                .update(cx, |_, window, _| window.activate_window())
 7571                .ok();
 7572        }
 7573    }
 7574
 7575    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7576        if cx.stop_active_drag(window) {
 7577        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7578            dismiss_app_notification(&notification_id, cx);
 7579        } else {
 7580            cx.propagate();
 7581        }
 7582    }
 7583
 7584    fn resize_dock(
 7585        &mut self,
 7586        dock_pos: DockPosition,
 7587        new_size: Pixels,
 7588        window: &mut Window,
 7589        cx: &mut Context<Self>,
 7590    ) {
 7591        match dock_pos {
 7592            DockPosition::Left => self.resize_left_dock(new_size, window, cx),
 7593            DockPosition::Right => self.resize_right_dock(new_size, window, cx),
 7594            DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
 7595        }
 7596    }
 7597
 7598    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7599        let workspace_width = self.bounds.size.width;
 7600        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7601
 7602        self.right_dock.read_with(cx, |right_dock, cx| {
 7603            let right_dock_size = right_dock
 7604                .stored_active_panel_size(window, cx)
 7605                .unwrap_or(Pixels::ZERO);
 7606            if right_dock_size + size > workspace_width {
 7607                size = workspace_width - right_dock_size
 7608            }
 7609        });
 7610
 7611        let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
 7612        self.left_dock.update(cx, |left_dock, cx| {
 7613            if WorkspaceSettings::get_global(cx)
 7614                .resize_all_panels_in_dock
 7615                .contains(&DockPosition::Left)
 7616            {
 7617                left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7618            } else {
 7619                left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7620            }
 7621        });
 7622    }
 7623
 7624    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7625        let workspace_width = self.bounds.size.width;
 7626        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7627        self.left_dock.read_with(cx, |left_dock, cx| {
 7628            let left_dock_size = left_dock
 7629                .stored_active_panel_size(window, cx)
 7630                .unwrap_or(Pixels::ZERO);
 7631            if left_dock_size + size > workspace_width {
 7632                size = workspace_width - left_dock_size
 7633            }
 7634        });
 7635        let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
 7636        self.right_dock.update(cx, |right_dock, cx| {
 7637            if WorkspaceSettings::get_global(cx)
 7638                .resize_all_panels_in_dock
 7639                .contains(&DockPosition::Right)
 7640            {
 7641                right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7642            } else {
 7643                right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7644            }
 7645        });
 7646    }
 7647
 7648    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7649        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7650        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7651            if WorkspaceSettings::get_global(cx)
 7652                .resize_all_panels_in_dock
 7653                .contains(&DockPosition::Bottom)
 7654            {
 7655                bottom_dock.resize_all_panels(Some(size), None, window, cx);
 7656            } else {
 7657                bottom_dock.resize_active_panel(Some(size), None, window, cx);
 7658            }
 7659        });
 7660    }
 7661
 7662    fn toggle_edit_predictions_all_files(
 7663        &mut self,
 7664        _: &ToggleEditPrediction,
 7665        _window: &mut Window,
 7666        cx: &mut Context<Self>,
 7667    ) {
 7668        let fs = self.project().read(cx).fs().clone();
 7669        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7670        update_settings_file(fs, cx, move |file, _| {
 7671            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7672        });
 7673    }
 7674
 7675    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7676        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7677        let next_mode = match current_mode {
 7678            Some(theme_settings::ThemeAppearanceMode::Light) => {
 7679                theme_settings::ThemeAppearanceMode::Dark
 7680            }
 7681            Some(theme_settings::ThemeAppearanceMode::Dark) => {
 7682                theme_settings::ThemeAppearanceMode::Light
 7683            }
 7684            Some(theme_settings::ThemeAppearanceMode::System) | None => {
 7685                match cx.theme().appearance() {
 7686                    theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
 7687                    theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
 7688                }
 7689            }
 7690        };
 7691
 7692        let fs = self.project().read(cx).fs().clone();
 7693        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7694            theme_settings::set_mode(settings, next_mode);
 7695        });
 7696    }
 7697
 7698    pub fn show_worktree_trust_security_modal(
 7699        &mut self,
 7700        toggle: bool,
 7701        window: &mut Window,
 7702        cx: &mut Context<Self>,
 7703    ) {
 7704        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7705            if toggle {
 7706                security_modal.update(cx, |security_modal, cx| {
 7707                    security_modal.dismiss(cx);
 7708                })
 7709            } else {
 7710                security_modal.update(cx, |security_modal, cx| {
 7711                    security_modal.refresh_restricted_paths(cx);
 7712                });
 7713            }
 7714        } else {
 7715            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7716                .map(|trusted_worktrees| {
 7717                    trusted_worktrees
 7718                        .read(cx)
 7719                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7720                })
 7721                .unwrap_or(false);
 7722            if has_restricted_worktrees {
 7723                let project = self.project().read(cx);
 7724                let remote_host = project
 7725                    .remote_connection_options(cx)
 7726                    .map(RemoteHostLocation::from);
 7727                let worktree_store = project.worktree_store().downgrade();
 7728                self.toggle_modal(window, cx, |_, cx| {
 7729                    SecurityModal::new(worktree_store, remote_host, cx)
 7730                });
 7731            }
 7732        }
 7733    }
 7734}
 7735
 7736pub trait AnyActiveCall {
 7737    fn entity(&self) -> AnyEntity;
 7738    fn is_in_room(&self, _: &App) -> bool;
 7739    fn room_id(&self, _: &App) -> Option<u64>;
 7740    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7741    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7742    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7743    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7744    fn is_sharing_project(&self, _: &App) -> bool;
 7745    fn has_remote_participants(&self, _: &App) -> bool;
 7746    fn local_participant_is_guest(&self, _: &App) -> bool;
 7747    fn client(&self, _: &App) -> Arc<Client>;
 7748    fn share_on_join(&self, _: &App) -> bool;
 7749    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7750    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7751    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7752    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7753    fn join_project(
 7754        &self,
 7755        _: u64,
 7756        _: Arc<LanguageRegistry>,
 7757        _: Arc<dyn Fs>,
 7758        _: &mut App,
 7759    ) -> Task<Result<Entity<Project>>>;
 7760    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7761    fn subscribe(
 7762        &self,
 7763        _: &mut Window,
 7764        _: &mut Context<Workspace>,
 7765        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7766    ) -> Subscription;
 7767    fn create_shared_screen(
 7768        &self,
 7769        _: PeerId,
 7770        _: &Entity<Pane>,
 7771        _: &mut Window,
 7772        _: &mut App,
 7773    ) -> Option<Entity<SharedScreen>>;
 7774}
 7775
 7776#[derive(Clone)]
 7777pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7778impl Global for GlobalAnyActiveCall {}
 7779
 7780impl GlobalAnyActiveCall {
 7781    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7782        cx.try_global()
 7783    }
 7784
 7785    pub(crate) fn global(cx: &App) -> &Self {
 7786        cx.global()
 7787    }
 7788}
 7789
 7790/// Workspace-local view of a remote participant's location.
 7791#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7792pub enum ParticipantLocation {
 7793    SharedProject { project_id: u64 },
 7794    UnsharedProject,
 7795    External,
 7796}
 7797
 7798impl ParticipantLocation {
 7799    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7800        match location
 7801            .and_then(|l| l.variant)
 7802            .context("participant location was not provided")?
 7803        {
 7804            proto::participant_location::Variant::SharedProject(project) => {
 7805                Ok(Self::SharedProject {
 7806                    project_id: project.id,
 7807                })
 7808            }
 7809            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7810            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7811        }
 7812    }
 7813}
 7814/// Workspace-local view of a remote collaborator's state.
 7815/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7816#[derive(Clone)]
 7817pub struct RemoteCollaborator {
 7818    pub user: Arc<User>,
 7819    pub peer_id: PeerId,
 7820    pub location: ParticipantLocation,
 7821    pub participant_index: ParticipantIndex,
 7822}
 7823
 7824pub enum ActiveCallEvent {
 7825    ParticipantLocationChanged { participant_id: PeerId },
 7826    RemoteVideoTracksChanged { participant_id: PeerId },
 7827}
 7828
 7829fn leader_border_for_pane(
 7830    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7831    pane: &Entity<Pane>,
 7832    _: &Window,
 7833    cx: &App,
 7834) -> Option<Div> {
 7835    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7836        if state.pane() == pane {
 7837            Some((*leader_id, state))
 7838        } else {
 7839            None
 7840        }
 7841    })?;
 7842
 7843    let mut leader_color = match leader_id {
 7844        CollaboratorId::PeerId(leader_peer_id) => {
 7845            let leader = GlobalAnyActiveCall::try_global(cx)?
 7846                .0
 7847                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7848
 7849            cx.theme()
 7850                .players()
 7851                .color_for_participant(leader.participant_index.0)
 7852                .cursor
 7853        }
 7854        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7855    };
 7856    leader_color.fade_out(0.3);
 7857    Some(
 7858        div()
 7859            .absolute()
 7860            .size_full()
 7861            .left_0()
 7862            .top_0()
 7863            .border_2()
 7864            .border_color(leader_color),
 7865    )
 7866}
 7867
 7868fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7869    ZED_WINDOW_POSITION
 7870        .zip(*ZED_WINDOW_SIZE)
 7871        .map(|(position, size)| Bounds {
 7872            origin: position,
 7873            size,
 7874        })
 7875}
 7876
 7877fn open_items(
 7878    serialized_workspace: Option<SerializedWorkspace>,
 7879    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7880    window: &mut Window,
 7881    cx: &mut Context<Workspace>,
 7882) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7883    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7884        Workspace::load_workspace(
 7885            serialized_workspace,
 7886            project_paths_to_open
 7887                .iter()
 7888                .map(|(_, project_path)| project_path)
 7889                .cloned()
 7890                .collect(),
 7891            window,
 7892            cx,
 7893        )
 7894    });
 7895
 7896    cx.spawn_in(window, async move |workspace, cx| {
 7897        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7898
 7899        if let Some(restored_items) = restored_items {
 7900            let restored_items = restored_items.await?;
 7901
 7902            let restored_project_paths = restored_items
 7903                .iter()
 7904                .filter_map(|item| {
 7905                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7906                        .ok()
 7907                        .flatten()
 7908                })
 7909                .collect::<HashSet<_>>();
 7910
 7911            for restored_item in restored_items {
 7912                opened_items.push(restored_item.map(Ok));
 7913            }
 7914
 7915            project_paths_to_open
 7916                .iter_mut()
 7917                .for_each(|(_, project_path)| {
 7918                    if let Some(project_path_to_open) = project_path
 7919                        && restored_project_paths.contains(project_path_to_open)
 7920                    {
 7921                        *project_path = None;
 7922                    }
 7923                });
 7924        } else {
 7925            for _ in 0..project_paths_to_open.len() {
 7926                opened_items.push(None);
 7927            }
 7928        }
 7929        assert!(opened_items.len() == project_paths_to_open.len());
 7930
 7931        let tasks =
 7932            project_paths_to_open
 7933                .into_iter()
 7934                .enumerate()
 7935                .map(|(ix, (abs_path, project_path))| {
 7936                    let workspace = workspace.clone();
 7937                    cx.spawn(async move |cx| {
 7938                        let file_project_path = project_path?;
 7939                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7940                            workspace.project().update(cx, |project, cx| {
 7941                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7942                            })
 7943                        });
 7944
 7945                        // We only want to open file paths here. If one of the items
 7946                        // here is a directory, it was already opened further above
 7947                        // with a `find_or_create_worktree`.
 7948                        if let Ok(task) = abs_path_task
 7949                            && task.await.is_none_or(|p| p.is_file())
 7950                        {
 7951                            return Some((
 7952                                ix,
 7953                                workspace
 7954                                    .update_in(cx, |workspace, window, cx| {
 7955                                        workspace.open_path(
 7956                                            file_project_path,
 7957                                            None,
 7958                                            true,
 7959                                            window,
 7960                                            cx,
 7961                                        )
 7962                                    })
 7963                                    .log_err()?
 7964                                    .await,
 7965                            ));
 7966                        }
 7967                        None
 7968                    })
 7969                });
 7970
 7971        let tasks = tasks.collect::<Vec<_>>();
 7972
 7973        let tasks = futures::future::join_all(tasks);
 7974        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7975            opened_items[ix] = Some(path_open_result);
 7976        }
 7977
 7978        Ok(opened_items)
 7979    })
 7980}
 7981
 7982#[derive(Clone)]
 7983enum ActivateInDirectionTarget {
 7984    Pane(Entity<Pane>),
 7985    Dock(Entity<Dock>),
 7986    Sidebar(FocusHandle),
 7987}
 7988
 7989fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7990    window
 7991        .update(cx, |multi_workspace, _, cx| {
 7992            let workspace = multi_workspace.workspace().clone();
 7993            workspace.update(cx, |workspace, cx| {
 7994                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7995                    struct DatabaseFailedNotification;
 7996
 7997                    workspace.show_notification(
 7998                        NotificationId::unique::<DatabaseFailedNotification>(),
 7999                        cx,
 8000                        |cx| {
 8001                            cx.new(|cx| {
 8002                                MessageNotification::new("Failed to load the database file.", cx)
 8003                                    .primary_message("File an Issue")
 8004                                    .primary_icon(IconName::Plus)
 8005                                    .primary_on_click(|window, cx| {
 8006                                        window.dispatch_action(Box::new(FileBugReport), cx)
 8007                                    })
 8008                            })
 8009                        },
 8010                    );
 8011                }
 8012            });
 8013        })
 8014        .log_err();
 8015}
 8016
 8017fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 8018    if val == 0 {
 8019        ThemeSettings::get_global(cx).ui_font_size(cx)
 8020    } else {
 8021        px(val as f32)
 8022    }
 8023}
 8024
 8025fn adjust_active_dock_size_by_px(
 8026    px: Pixels,
 8027    workspace: &mut Workspace,
 8028    window: &mut Window,
 8029    cx: &mut Context<Workspace>,
 8030) {
 8031    let Some(active_dock) = workspace
 8032        .all_docks()
 8033        .into_iter()
 8034        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 8035    else {
 8036        return;
 8037    };
 8038    let dock = active_dock.read(cx);
 8039    let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
 8040        return;
 8041    };
 8042    workspace.resize_dock(dock.position(), panel_size + px, window, cx);
 8043}
 8044
 8045fn adjust_open_docks_size_by_px(
 8046    px: Pixels,
 8047    workspace: &mut Workspace,
 8048    window: &mut Window,
 8049    cx: &mut Context<Workspace>,
 8050) {
 8051    let docks = workspace
 8052        .all_docks()
 8053        .into_iter()
 8054        .filter_map(|dock_entity| {
 8055            let dock = dock_entity.read(cx);
 8056            if dock.is_open() {
 8057                let dock_pos = dock.position();
 8058                let panel_size = workspace.dock_size(&dock, window, cx)?;
 8059                Some((dock_pos, panel_size + px))
 8060            } else {
 8061                None
 8062            }
 8063        })
 8064        .collect::<Vec<_>>();
 8065
 8066    for (position, new_size) in docks {
 8067        workspace.resize_dock(position, new_size, window, cx);
 8068    }
 8069}
 8070
 8071impl Focusable for Workspace {
 8072    fn focus_handle(&self, cx: &App) -> FocusHandle {
 8073        self.active_pane.focus_handle(cx)
 8074    }
 8075}
 8076
 8077#[derive(Clone)]
 8078struct DraggedDock(DockPosition);
 8079
 8080impl Render for DraggedDock {
 8081    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 8082        gpui::Empty
 8083    }
 8084}
 8085
 8086impl Render for Workspace {
 8087    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 8088        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 8089        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 8090            log::info!("Rendered first frame");
 8091        }
 8092
 8093        let centered_layout = self.centered_layout
 8094            && self.center.panes().len() == 1
 8095            && self.active_item(cx).is_some();
 8096        let render_padding = |size| {
 8097            (size > 0.0).then(|| {
 8098                div()
 8099                    .h_full()
 8100                    .w(relative(size))
 8101                    .bg(cx.theme().colors().editor_background)
 8102                    .border_color(cx.theme().colors().pane_group_border)
 8103            })
 8104        };
 8105        let paddings = if centered_layout {
 8106            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 8107            (
 8108                render_padding(Self::adjust_padding(
 8109                    settings.left_padding.map(|padding| padding.0),
 8110                )),
 8111                render_padding(Self::adjust_padding(
 8112                    settings.right_padding.map(|padding| padding.0),
 8113                )),
 8114            )
 8115        } else {
 8116            (None, None)
 8117        };
 8118        let ui_font = theme_settings::setup_ui_font(window, cx);
 8119
 8120        let theme = cx.theme().clone();
 8121        let colors = theme.colors();
 8122        let notification_entities = self
 8123            .notifications
 8124            .iter()
 8125            .map(|(_, notification)| notification.entity_id())
 8126            .collect::<Vec<_>>();
 8127        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 8128
 8129        div()
 8130            .relative()
 8131            .size_full()
 8132            .flex()
 8133            .flex_col()
 8134            .font(ui_font)
 8135            .gap_0()
 8136                .justify_start()
 8137                .items_start()
 8138                .text_color(colors.text)
 8139                .overflow_hidden()
 8140                .children(self.titlebar_item.clone())
 8141                .on_modifiers_changed(move |_, _, cx| {
 8142                    for &id in &notification_entities {
 8143                        cx.notify(id);
 8144                    }
 8145                })
 8146                .child(
 8147                    div()
 8148                        .size_full()
 8149                        .relative()
 8150                        .flex_1()
 8151                        .flex()
 8152                        .flex_col()
 8153                        .child(
 8154                            div()
 8155                                .id("workspace")
 8156                                .bg(colors.background)
 8157                                .relative()
 8158                                .flex_1()
 8159                                .w_full()
 8160                                .flex()
 8161                                .flex_col()
 8162                                .overflow_hidden()
 8163                                .border_t_1()
 8164                                .border_b_1()
 8165                                .border_color(colors.border)
 8166                                .child({
 8167                                    let this = cx.entity();
 8168                                    canvas(
 8169                                        move |bounds, window, cx| {
 8170                                            this.update(cx, |this, cx| {
 8171                                                let bounds_changed = this.bounds != bounds;
 8172                                                this.bounds = bounds;
 8173
 8174                                                if bounds_changed {
 8175                                                    this.left_dock.update(cx, |dock, cx| {
 8176                                                        dock.clamp_panel_size(
 8177                                                            bounds.size.width,
 8178                                                            window,
 8179                                                            cx,
 8180                                                        )
 8181                                                    });
 8182
 8183                                                    this.right_dock.update(cx, |dock, cx| {
 8184                                                        dock.clamp_panel_size(
 8185                                                            bounds.size.width,
 8186                                                            window,
 8187                                                            cx,
 8188                                                        )
 8189                                                    });
 8190
 8191                                                    this.bottom_dock.update(cx, |dock, cx| {
 8192                                                        dock.clamp_panel_size(
 8193                                                            bounds.size.height,
 8194                                                            window,
 8195                                                            cx,
 8196                                                        )
 8197                                                    });
 8198                                                }
 8199                                            })
 8200                                        },
 8201                                        |_, _, _, _| {},
 8202                                    )
 8203                                    .absolute()
 8204                                    .size_full()
 8205                                })
 8206                                .when(self.zoomed.is_none(), |this| {
 8207                                    this.on_drag_move(cx.listener(
 8208                                        move |workspace,
 8209                                              e: &DragMoveEvent<DraggedDock>,
 8210                                              window,
 8211                                              cx| {
 8212                                            if workspace.previous_dock_drag_coordinates
 8213                                                != Some(e.event.position)
 8214                                            {
 8215                                                workspace.previous_dock_drag_coordinates =
 8216                                                    Some(e.event.position);
 8217
 8218                                                match e.drag(cx).0 {
 8219                                                    DockPosition::Left => {
 8220                                                        workspace.resize_left_dock(
 8221                                                            e.event.position.x
 8222                                                                - workspace.bounds.left(),
 8223                                                            window,
 8224                                                            cx,
 8225                                                        );
 8226                                                    }
 8227                                                    DockPosition::Right => {
 8228                                                        workspace.resize_right_dock(
 8229                                                            workspace.bounds.right()
 8230                                                                - e.event.position.x,
 8231                                                            window,
 8232                                                            cx,
 8233                                                        );
 8234                                                    }
 8235                                                    DockPosition::Bottom => {
 8236                                                        workspace.resize_bottom_dock(
 8237                                                            workspace.bounds.bottom()
 8238                                                                - e.event.position.y,
 8239                                                            window,
 8240                                                            cx,
 8241                                                        );
 8242                                                    }
 8243                                                };
 8244                                                workspace.serialize_workspace(window, cx);
 8245                                            }
 8246                                        },
 8247                                    ))
 8248
 8249                                })
 8250                                .child({
 8251                                    match bottom_dock_layout {
 8252                                        BottomDockLayout::Full => div()
 8253                                            .flex()
 8254                                            .flex_col()
 8255                                            .h_full()
 8256                                            .child(
 8257                                                div()
 8258                                                    .flex()
 8259                                                    .flex_row()
 8260                                                    .flex_1()
 8261                                                    .overflow_hidden()
 8262                                                    .children(self.render_dock(
 8263                                                        DockPosition::Left,
 8264                                                        &self.left_dock,
 8265                                                        window,
 8266                                                        cx,
 8267                                                    ))
 8268
 8269                                                    .child(
 8270                                                        div()
 8271                                                            .flex()
 8272                                                            .flex_col()
 8273                                                            .flex_1()
 8274                                                            .overflow_hidden()
 8275                                                            .child(
 8276                                                                h_flex()
 8277                                                                    .flex_1()
 8278                                                                    .when_some(
 8279                                                                        paddings.0,
 8280                                                                        |this, p| {
 8281                                                                            this.child(
 8282                                                                                p.border_r_1(),
 8283                                                                            )
 8284                                                                        },
 8285                                                                    )
 8286                                                                    .child(self.center.render(
 8287                                                                        self.zoomed.as_ref(),
 8288                                                                        &PaneRenderContext {
 8289                                                                            follower_states:
 8290                                                                                &self.follower_states,
 8291                                                                            active_call: self.active_call(),
 8292                                                                            active_pane: &self.active_pane,
 8293                                                                            app_state: &self.app_state,
 8294                                                                            project: &self.project,
 8295                                                                            workspace: &self.weak_self,
 8296                                                                        },
 8297                                                                        window,
 8298                                                                        cx,
 8299                                                                    ))
 8300                                                                    .when_some(
 8301                                                                        paddings.1,
 8302                                                                        |this, p| {
 8303                                                                            this.child(
 8304                                                                                p.border_l_1(),
 8305                                                                            )
 8306                                                                        },
 8307                                                                    ),
 8308                                                            ),
 8309                                                    )
 8310
 8311                                                    .children(self.render_dock(
 8312                                                        DockPosition::Right,
 8313                                                        &self.right_dock,
 8314                                                        window,
 8315                                                        cx,
 8316                                                    )),
 8317                                            )
 8318                                            .child(div().w_full().children(self.render_dock(
 8319                                                DockPosition::Bottom,
 8320                                                &self.bottom_dock,
 8321                                                window,
 8322                                                cx
 8323                                            ))),
 8324
 8325                                        BottomDockLayout::LeftAligned => div()
 8326                                            .flex()
 8327                                            .flex_row()
 8328                                            .h_full()
 8329                                            .child(
 8330                                                div()
 8331                                                    .flex()
 8332                                                    .flex_col()
 8333                                                    .flex_1()
 8334                                                    .h_full()
 8335                                                    .child(
 8336                                                        div()
 8337                                                            .flex()
 8338                                                            .flex_row()
 8339                                                            .flex_1()
 8340                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 8341
 8342                                                            .child(
 8343                                                                div()
 8344                                                                    .flex()
 8345                                                                    .flex_col()
 8346                                                                    .flex_1()
 8347                                                                    .overflow_hidden()
 8348                                                                    .child(
 8349                                                                        h_flex()
 8350                                                                            .flex_1()
 8351                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8352                                                                            .child(self.center.render(
 8353                                                                                self.zoomed.as_ref(),
 8354                                                                                &PaneRenderContext {
 8355                                                                                    follower_states:
 8356                                                                                        &self.follower_states,
 8357                                                                                    active_call: self.active_call(),
 8358                                                                                    active_pane: &self.active_pane,
 8359                                                                                    app_state: &self.app_state,
 8360                                                                                    project: &self.project,
 8361                                                                                    workspace: &self.weak_self,
 8362                                                                                },
 8363                                                                                window,
 8364                                                                                cx,
 8365                                                                            ))
 8366                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8367                                                                    )
 8368                                                            )
 8369
 8370                                                    )
 8371                                                    .child(
 8372                                                        div()
 8373                                                            .w_full()
 8374                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8375                                                    ),
 8376                                            )
 8377                                            .children(self.render_dock(
 8378                                                DockPosition::Right,
 8379                                                &self.right_dock,
 8380                                                window,
 8381                                                cx,
 8382                                            )),
 8383                                        BottomDockLayout::RightAligned => div()
 8384                                            .flex()
 8385                                            .flex_row()
 8386                                            .h_full()
 8387                                            .children(self.render_dock(
 8388                                                DockPosition::Left,
 8389                                                &self.left_dock,
 8390                                                window,
 8391                                                cx,
 8392                                            ))
 8393
 8394                                            .child(
 8395                                                div()
 8396                                                    .flex()
 8397                                                    .flex_col()
 8398                                                    .flex_1()
 8399                                                    .h_full()
 8400                                                    .child(
 8401                                                        div()
 8402                                                            .flex()
 8403                                                            .flex_row()
 8404                                                            .flex_1()
 8405                                                            .child(
 8406                                                                div()
 8407                                                                    .flex()
 8408                                                                    .flex_col()
 8409                                                                    .flex_1()
 8410                                                                    .overflow_hidden()
 8411                                                                    .child(
 8412                                                                        h_flex()
 8413                                                                            .flex_1()
 8414                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8415                                                                            .child(self.center.render(
 8416                                                                                self.zoomed.as_ref(),
 8417                                                                                &PaneRenderContext {
 8418                                                                                    follower_states:
 8419                                                                                        &self.follower_states,
 8420                                                                                    active_call: self.active_call(),
 8421                                                                                    active_pane: &self.active_pane,
 8422                                                                                    app_state: &self.app_state,
 8423                                                                                    project: &self.project,
 8424                                                                                    workspace: &self.weak_self,
 8425                                                                                },
 8426                                                                                window,
 8427                                                                                cx,
 8428                                                                            ))
 8429                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8430                                                                    )
 8431                                                            )
 8432
 8433                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 8434                                                    )
 8435                                                    .child(
 8436                                                        div()
 8437                                                            .w_full()
 8438                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8439                                                    ),
 8440                                            ),
 8441                                        BottomDockLayout::Contained => div()
 8442                                            .flex()
 8443                                            .flex_row()
 8444                                            .h_full()
 8445                                            .children(self.render_dock(
 8446                                                DockPosition::Left,
 8447                                                &self.left_dock,
 8448                                                window,
 8449                                                cx,
 8450                                            ))
 8451
 8452                                            .child(
 8453                                                div()
 8454                                                    .flex()
 8455                                                    .flex_col()
 8456                                                    .flex_1()
 8457                                                    .overflow_hidden()
 8458                                                    .child(
 8459                                                        h_flex()
 8460                                                            .flex_1()
 8461                                                            .when_some(paddings.0, |this, p| {
 8462                                                                this.child(p.border_r_1())
 8463                                                            })
 8464                                                            .child(self.center.render(
 8465                                                                self.zoomed.as_ref(),
 8466                                                                &PaneRenderContext {
 8467                                                                    follower_states:
 8468                                                                        &self.follower_states,
 8469                                                                    active_call: self.active_call(),
 8470                                                                    active_pane: &self.active_pane,
 8471                                                                    app_state: &self.app_state,
 8472                                                                    project: &self.project,
 8473                                                                    workspace: &self.weak_self,
 8474                                                                },
 8475                                                                window,
 8476                                                                cx,
 8477                                                            ))
 8478                                                            .when_some(paddings.1, |this, p| {
 8479                                                                this.child(p.border_l_1())
 8480                                                            }),
 8481                                                    )
 8482                                                    .children(self.render_dock(
 8483                                                        DockPosition::Bottom,
 8484                                                        &self.bottom_dock,
 8485                                                        window,
 8486                                                        cx,
 8487                                                    )),
 8488                                            )
 8489
 8490                                            .children(self.render_dock(
 8491                                                DockPosition::Right,
 8492                                                &self.right_dock,
 8493                                                window,
 8494                                                cx,
 8495                                            )),
 8496                                    }
 8497                                })
 8498                                .children(self.zoomed.as_ref().and_then(|view| {
 8499                                    let zoomed_view = view.upgrade()?;
 8500                                    let div = div()
 8501                                        .occlude()
 8502                                        .absolute()
 8503                                        .overflow_hidden()
 8504                                        .border_color(colors.border)
 8505                                        .bg(colors.background)
 8506                                        .child(zoomed_view)
 8507                                        .inset_0()
 8508                                        .shadow_lg();
 8509
 8510                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8511                                       return Some(div);
 8512                                    }
 8513
 8514                                    Some(match self.zoomed_position {
 8515                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8516                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8517                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8518                                        None => {
 8519                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8520                                        }
 8521                                    })
 8522                                }))
 8523                                .children(self.render_notifications(window, cx)),
 8524                        )
 8525                        .when(self.status_bar_visible(cx), |parent| {
 8526                            parent.child(self.status_bar.clone())
 8527                        })
 8528                        .child(self.toast_layer.clone()),
 8529                )
 8530    }
 8531}
 8532
 8533impl WorkspaceStore {
 8534    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8535        Self {
 8536            workspaces: Default::default(),
 8537            _subscriptions: vec![
 8538                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8539                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8540            ],
 8541            client,
 8542        }
 8543    }
 8544
 8545    pub fn update_followers(
 8546        &self,
 8547        project_id: Option<u64>,
 8548        update: proto::update_followers::Variant,
 8549        cx: &App,
 8550    ) -> Option<()> {
 8551        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8552        let room_id = active_call.0.room_id(cx)?;
 8553        self.client
 8554            .send(proto::UpdateFollowers {
 8555                room_id,
 8556                project_id,
 8557                variant: Some(update),
 8558            })
 8559            .log_err()
 8560    }
 8561
 8562    pub async fn handle_follow(
 8563        this: Entity<Self>,
 8564        envelope: TypedEnvelope<proto::Follow>,
 8565        mut cx: AsyncApp,
 8566    ) -> Result<proto::FollowResponse> {
 8567        this.update(&mut cx, |this, cx| {
 8568            let follower = Follower {
 8569                project_id: envelope.payload.project_id,
 8570                peer_id: envelope.original_sender_id()?,
 8571            };
 8572
 8573            let mut response = proto::FollowResponse::default();
 8574
 8575            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8576                let Some(workspace) = weak_workspace.upgrade() else {
 8577                    return false;
 8578                };
 8579                window_handle
 8580                    .update(cx, |_, window, cx| {
 8581                        workspace.update(cx, |workspace, cx| {
 8582                            let handler_response =
 8583                                workspace.handle_follow(follower.project_id, window, cx);
 8584                            if let Some(active_view) = handler_response.active_view
 8585                                && workspace.project.read(cx).remote_id() == follower.project_id
 8586                            {
 8587                                response.active_view = Some(active_view)
 8588                            }
 8589                        });
 8590                    })
 8591                    .is_ok()
 8592            });
 8593
 8594            Ok(response)
 8595        })
 8596    }
 8597
 8598    async fn handle_update_followers(
 8599        this: Entity<Self>,
 8600        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8601        mut cx: AsyncApp,
 8602    ) -> Result<()> {
 8603        let leader_id = envelope.original_sender_id()?;
 8604        let update = envelope.payload;
 8605
 8606        this.update(&mut cx, |this, cx| {
 8607            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8608                let Some(workspace) = weak_workspace.upgrade() else {
 8609                    return false;
 8610                };
 8611                window_handle
 8612                    .update(cx, |_, window, cx| {
 8613                        workspace.update(cx, |workspace, cx| {
 8614                            let project_id = workspace.project.read(cx).remote_id();
 8615                            if update.project_id != project_id && update.project_id.is_some() {
 8616                                return;
 8617                            }
 8618                            workspace.handle_update_followers(
 8619                                leader_id,
 8620                                update.clone(),
 8621                                window,
 8622                                cx,
 8623                            );
 8624                        });
 8625                    })
 8626                    .is_ok()
 8627            });
 8628            Ok(())
 8629        })
 8630    }
 8631
 8632    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8633        self.workspaces.iter().map(|(_, weak)| weak)
 8634    }
 8635
 8636    pub fn workspaces_with_windows(
 8637        &self,
 8638    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8639        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8640    }
 8641}
 8642
 8643impl ViewId {
 8644    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8645        Ok(Self {
 8646            creator: message
 8647                .creator
 8648                .map(CollaboratorId::PeerId)
 8649                .context("creator is missing")?,
 8650            id: message.id,
 8651        })
 8652    }
 8653
 8654    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8655        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8656            Some(proto::ViewId {
 8657                creator: Some(peer_id),
 8658                id: self.id,
 8659            })
 8660        } else {
 8661            None
 8662        }
 8663    }
 8664}
 8665
 8666impl FollowerState {
 8667    fn pane(&self) -> &Entity<Pane> {
 8668        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8669    }
 8670}
 8671
 8672pub trait WorkspaceHandle {
 8673    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8674}
 8675
 8676impl WorkspaceHandle for Entity<Workspace> {
 8677    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8678        self.read(cx)
 8679            .worktrees(cx)
 8680            .flat_map(|worktree| {
 8681                let worktree_id = worktree.read(cx).id();
 8682                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8683                    worktree_id,
 8684                    path: f.path.clone(),
 8685                })
 8686            })
 8687            .collect::<Vec<_>>()
 8688    }
 8689}
 8690
 8691pub async fn last_opened_workspace_location(
 8692    db: &WorkspaceDb,
 8693    fs: &dyn fs::Fs,
 8694) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8695    db.last_workspace(fs)
 8696        .await
 8697        .log_err()
 8698        .flatten()
 8699        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8700}
 8701
 8702pub async fn last_session_workspace_locations(
 8703    db: &WorkspaceDb,
 8704    last_session_id: &str,
 8705    last_session_window_stack: Option<Vec<WindowId>>,
 8706    fs: &dyn fs::Fs,
 8707) -> Option<Vec<SessionWorkspace>> {
 8708    db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8709        .await
 8710        .log_err()
 8711}
 8712
 8713pub async fn restore_multiworkspace(
 8714    multi_workspace: SerializedMultiWorkspace,
 8715    app_state: Arc<AppState>,
 8716    cx: &mut AsyncApp,
 8717) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8718    let SerializedMultiWorkspace {
 8719        active_workspace,
 8720        state,
 8721    } = multi_workspace;
 8722
 8723    let workspace_result = if active_workspace.paths.is_empty() {
 8724        cx.update(|cx| {
 8725            open_workspace_by_id(active_workspace.workspace_id, app_state.clone(), None, cx)
 8726        })
 8727        .await
 8728    } else {
 8729        cx.update(|cx| {
 8730            Workspace::new_local(
 8731                active_workspace.paths.paths().to_vec(),
 8732                app_state.clone(),
 8733                None,
 8734                None,
 8735                None,
 8736                OpenMode::Activate,
 8737                cx,
 8738            )
 8739        })
 8740        .await
 8741        .map(|result| result.window)
 8742    };
 8743
 8744    let window_handle = match workspace_result {
 8745        Ok(handle) => handle,
 8746        Err(err) => {
 8747            log::error!("Failed to restore active workspace: {err:#}");
 8748
 8749            let mut fallback_handle = None;
 8750            for key in &state.project_groups {
 8751                let key: ProjectGroupKey = key.clone().into();
 8752                let paths = key.path_list().paths().to_vec();
 8753                match cx
 8754                    .update(|cx| {
 8755                        Workspace::new_local(
 8756                            paths,
 8757                            app_state.clone(),
 8758                            None,
 8759                            None,
 8760                            None,
 8761                            OpenMode::Activate,
 8762                            cx,
 8763                        )
 8764                    })
 8765                    .await
 8766                {
 8767                    Ok(OpenResult { window, .. }) => {
 8768                        fallback_handle = Some(window);
 8769                        break;
 8770                    }
 8771                    Err(fallback_err) => {
 8772                        log::error!("Fallback project group also failed: {fallback_err:#}");
 8773                    }
 8774                }
 8775            }
 8776
 8777            fallback_handle.ok_or(err)?
 8778        }
 8779    };
 8780
 8781    apply_restored_multiworkspace_state(window_handle, &state, app_state.fs.clone(), cx).await;
 8782
 8783    window_handle
 8784        .update(cx, |_, window, _cx| {
 8785            window.activate_window();
 8786        })
 8787        .ok();
 8788
 8789    Ok(window_handle)
 8790}
 8791
 8792pub async fn apply_restored_multiworkspace_state(
 8793    window_handle: WindowHandle<MultiWorkspace>,
 8794    state: &MultiWorkspaceState,
 8795    fs: Arc<dyn fs::Fs>,
 8796    cx: &mut AsyncApp,
 8797) {
 8798    let MultiWorkspaceState {
 8799        sidebar_open,
 8800        project_groups,
 8801        sidebar_state,
 8802        ..
 8803    } = state;
 8804
 8805    if !project_groups.is_empty() {
 8806        // Resolve linked worktree paths to their main repo paths so
 8807        // stale keys from previous sessions get normalized and deduped.
 8808        let mut resolved_groups: Vec<SerializedProjectGroupState> = Vec::new();
 8809        for serialized in project_groups.iter().cloned() {
 8810            let SerializedProjectGroupState { key, expanded } = serialized.into_restored_state();
 8811            if key.path_list().paths().is_empty() {
 8812                continue;
 8813            }
 8814            let mut resolved_paths = Vec::new();
 8815            for path in key.path_list().paths() {
 8816                if key.host().is_none()
 8817                    && let Some(common_dir) =
 8818                        project::discover_root_repo_common_dir(path, fs.as_ref()).await
 8819                {
 8820                    let main_path = common_dir.parent().unwrap_or(&common_dir);
 8821                    resolved_paths.push(main_path.to_path_buf());
 8822                } else {
 8823                    resolved_paths.push(path.to_path_buf());
 8824                }
 8825            }
 8826            let resolved = ProjectGroupKey::new(key.host(), PathList::new(&resolved_paths));
 8827            if !resolved_groups.iter().any(|g| g.key == resolved) {
 8828                resolved_groups.push(SerializedProjectGroupState {
 8829                    key: resolved,
 8830                    expanded,
 8831                });
 8832            }
 8833        }
 8834
 8835        window_handle
 8836            .update(cx, |multi_workspace, _window, cx| {
 8837                multi_workspace.restore_project_groups(resolved_groups, cx);
 8838            })
 8839            .ok();
 8840    }
 8841
 8842    if *sidebar_open {
 8843        window_handle
 8844            .update(cx, |multi_workspace, _, cx| {
 8845                multi_workspace.restore_open_sidebar(cx);
 8846            })
 8847            .ok();
 8848    }
 8849
 8850    if let Some(sidebar_state) = sidebar_state {
 8851        window_handle
 8852            .update(cx, |multi_workspace, window, cx| {
 8853                if let Some(sidebar) = multi_workspace.sidebar() {
 8854                    sidebar.restore_serialized_state(sidebar_state, window, cx);
 8855                }
 8856                multi_workspace.serialize(cx);
 8857            })
 8858            .ok();
 8859    }
 8860}
 8861
 8862actions!(
 8863    collab,
 8864    [
 8865        /// Opens the channel notes for the current call.
 8866        ///
 8867        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8868        /// channel in the collab panel.
 8869        ///
 8870        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8871        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8872        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8873        OpenChannelNotes,
 8874        /// Mutes your microphone.
 8875        Mute,
 8876        /// Deafens yourself (mute both microphone and speakers).
 8877        Deafen,
 8878        /// Leaves the current call.
 8879        LeaveCall,
 8880        /// Shares the current project with collaborators.
 8881        ShareProject,
 8882        /// Shares your screen with collaborators.
 8883        ScreenShare,
 8884        /// Copies the current room name and session id for debugging purposes.
 8885        CopyRoomId,
 8886    ]
 8887);
 8888
 8889/// Opens the channel notes for a specific channel by its ID.
 8890#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8891#[action(namespace = collab)]
 8892#[serde(deny_unknown_fields)]
 8893pub struct OpenChannelNotesById {
 8894    pub channel_id: u64,
 8895}
 8896
 8897actions!(
 8898    zed,
 8899    [
 8900        /// Opens the Zed log file.
 8901        OpenLog,
 8902        /// Reveals the Zed log file in the system file manager.
 8903        RevealLogInFileManager
 8904    ]
 8905);
 8906
 8907async fn join_channel_internal(
 8908    channel_id: ChannelId,
 8909    app_state: &Arc<AppState>,
 8910    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8911    requesting_workspace: Option<WeakEntity<Workspace>>,
 8912    active_call: &dyn AnyActiveCall,
 8913    cx: &mut AsyncApp,
 8914) -> Result<bool> {
 8915    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8916        if !active_call.is_in_room(cx) {
 8917            return (false, false);
 8918        }
 8919
 8920        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8921        let should_prompt = active_call.is_sharing_project(cx)
 8922            && active_call.has_remote_participants(cx)
 8923            && !already_in_channel;
 8924        (should_prompt, already_in_channel)
 8925    });
 8926
 8927    if already_in_channel {
 8928        let task = cx.update(|cx| {
 8929            if let Some((project, host)) = active_call.most_active_project(cx) {
 8930                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8931            } else {
 8932                None
 8933            }
 8934        });
 8935        if let Some(task) = task {
 8936            task.await?;
 8937        }
 8938        return anyhow::Ok(true);
 8939    }
 8940
 8941    if should_prompt {
 8942        if let Some(multi_workspace) = requesting_window {
 8943            let answer = multi_workspace
 8944                .update(cx, |_, window, cx| {
 8945                    window.prompt(
 8946                        PromptLevel::Warning,
 8947                        "Do you want to switch channels?",
 8948                        Some("Leaving this call will unshare your current project."),
 8949                        &["Yes, Join Channel", "Cancel"],
 8950                        cx,
 8951                    )
 8952                })?
 8953                .await;
 8954
 8955            if answer == Ok(1) {
 8956                return Ok(false);
 8957            }
 8958        } else {
 8959            return Ok(false);
 8960        }
 8961    }
 8962
 8963    let client = cx.update(|cx| active_call.client(cx));
 8964
 8965    let mut client_status = client.status();
 8966
 8967    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8968    'outer: loop {
 8969        let Some(status) = client_status.recv().await else {
 8970            anyhow::bail!("error connecting");
 8971        };
 8972
 8973        match status {
 8974            Status::Connecting
 8975            | Status::Authenticating
 8976            | Status::Authenticated
 8977            | Status::Reconnecting
 8978            | Status::Reauthenticating
 8979            | Status::Reauthenticated => continue,
 8980            Status::Connected { .. } => break 'outer,
 8981            Status::SignedOut | Status::AuthenticationError => {
 8982                return Err(ErrorCode::SignedOut.into());
 8983            }
 8984            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8985            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8986                return Err(ErrorCode::Disconnected.into());
 8987            }
 8988        }
 8989    }
 8990
 8991    let joined = cx
 8992        .update(|cx| active_call.join_channel(channel_id, cx))
 8993        .await?;
 8994
 8995    if !joined {
 8996        return anyhow::Ok(true);
 8997    }
 8998
 8999    cx.update(|cx| active_call.room_update_completed(cx)).await;
 9000
 9001    let task = cx.update(|cx| {
 9002        if let Some((project, host)) = active_call.most_active_project(cx) {
 9003            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 9004        }
 9005
 9006        // If you are the first to join a channel, see if you should share your project.
 9007        if !active_call.has_remote_participants(cx)
 9008            && !active_call.local_participant_is_guest(cx)
 9009            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 9010        {
 9011            let project = workspace.update(cx, |workspace, cx| {
 9012                let project = workspace.project.read(cx);
 9013
 9014                if !active_call.share_on_join(cx) {
 9015                    return None;
 9016                }
 9017
 9018                if (project.is_local() || project.is_via_remote_server())
 9019                    && project.visible_worktrees(cx).any(|tree| {
 9020                        tree.read(cx)
 9021                            .root_entry()
 9022                            .is_some_and(|entry| entry.is_dir())
 9023                    })
 9024                {
 9025                    Some(workspace.project.clone())
 9026                } else {
 9027                    None
 9028                }
 9029            });
 9030            if let Some(project) = project {
 9031                let share_task = active_call.share_project(project, cx);
 9032                return Some(cx.spawn(async move |_cx| -> Result<()> {
 9033                    share_task.await?;
 9034                    Ok(())
 9035                }));
 9036            }
 9037        }
 9038
 9039        None
 9040    });
 9041    if let Some(task) = task {
 9042        task.await?;
 9043        return anyhow::Ok(true);
 9044    }
 9045    anyhow::Ok(false)
 9046}
 9047
 9048pub fn join_channel(
 9049    channel_id: ChannelId,
 9050    app_state: Arc<AppState>,
 9051    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9052    requesting_workspace: Option<WeakEntity<Workspace>>,
 9053    cx: &mut App,
 9054) -> Task<Result<()>> {
 9055    let active_call = GlobalAnyActiveCall::global(cx).clone();
 9056    cx.spawn(async move |cx| {
 9057        let result = join_channel_internal(
 9058            channel_id,
 9059            &app_state,
 9060            requesting_window,
 9061            requesting_workspace,
 9062            &*active_call.0,
 9063            cx,
 9064        )
 9065        .await;
 9066
 9067        // join channel succeeded, and opened a window
 9068        if matches!(result, Ok(true)) {
 9069            return anyhow::Ok(());
 9070        }
 9071
 9072        // find an existing workspace to focus and show call controls
 9073        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 9074        if active_window.is_none() {
 9075            // no open workspaces, make one to show the error in (blergh)
 9076            let OpenResult {
 9077                window: window_handle,
 9078                ..
 9079            } = cx
 9080                .update(|cx| {
 9081                    Workspace::new_local(
 9082                        vec![],
 9083                        app_state.clone(),
 9084                        requesting_window,
 9085                        None,
 9086                        None,
 9087                        OpenMode::Activate,
 9088                        cx,
 9089                    )
 9090                })
 9091                .await?;
 9092
 9093            window_handle
 9094                .update(cx, |_, window, _cx| {
 9095                    window.activate_window();
 9096                })
 9097                .ok();
 9098
 9099            if result.is_ok() {
 9100                cx.update(|cx| {
 9101                    cx.dispatch_action(&OpenChannelNotes);
 9102                });
 9103            }
 9104
 9105            active_window = Some(window_handle);
 9106        }
 9107
 9108        if let Err(err) = result {
 9109            log::error!("failed to join channel: {}", err);
 9110            if let Some(active_window) = active_window {
 9111                active_window
 9112                    .update(cx, |_, window, cx| {
 9113                        let detail: SharedString = match err.error_code() {
 9114                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 9115                            ErrorCode::UpgradeRequired => concat!(
 9116                                "Your are running an unsupported version of Zed. ",
 9117                                "Please update to continue."
 9118                            )
 9119                            .into(),
 9120                            ErrorCode::NoSuchChannel => concat!(
 9121                                "No matching channel was found. ",
 9122                                "Please check the link and try again."
 9123                            )
 9124                            .into(),
 9125                            ErrorCode::Forbidden => concat!(
 9126                                "This channel is private, and you do not have access. ",
 9127                                "Please ask someone to add you and try again."
 9128                            )
 9129                            .into(),
 9130                            ErrorCode::Disconnected => {
 9131                                "Please check your internet connection and try again.".into()
 9132                            }
 9133                            _ => format!("{}\n\nPlease try again.", err).into(),
 9134                        };
 9135                        window.prompt(
 9136                            PromptLevel::Critical,
 9137                            "Failed to join channel",
 9138                            Some(&detail),
 9139                            &["Ok"],
 9140                            cx,
 9141                        )
 9142                    })?
 9143                    .await
 9144                    .ok();
 9145            }
 9146        }
 9147
 9148        // return ok, we showed the error to the user.
 9149        anyhow::Ok(())
 9150    })
 9151}
 9152
 9153pub async fn get_any_active_multi_workspace(
 9154    app_state: Arc<AppState>,
 9155    mut cx: AsyncApp,
 9156) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 9157    // find an existing workspace to focus and show call controls
 9158    let active_window = activate_any_workspace_window(&mut cx);
 9159    if active_window.is_none() {
 9160        cx.update(|cx| {
 9161            Workspace::new_local(
 9162                vec![],
 9163                app_state.clone(),
 9164                None,
 9165                None,
 9166                None,
 9167                OpenMode::Activate,
 9168                cx,
 9169            )
 9170        })
 9171        .await?;
 9172    }
 9173    activate_any_workspace_window(&mut cx).context("could not open zed")
 9174}
 9175
 9176fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 9177    cx.update(|cx| {
 9178        if let Some(workspace_window) = cx
 9179            .active_window()
 9180            .and_then(|window| window.downcast::<MultiWorkspace>())
 9181        {
 9182            return Some(workspace_window);
 9183        }
 9184
 9185        for window in cx.windows() {
 9186            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 9187                workspace_window
 9188                    .update(cx, |_, window, _| window.activate_window())
 9189                    .ok();
 9190                return Some(workspace_window);
 9191            }
 9192        }
 9193        None
 9194    })
 9195}
 9196
 9197pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 9198    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 9199}
 9200
 9201pub fn workspace_windows_for_location(
 9202    serialized_location: &SerializedWorkspaceLocation,
 9203    cx: &App,
 9204) -> Vec<WindowHandle<MultiWorkspace>> {
 9205    cx.windows()
 9206        .into_iter()
 9207        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9208        .filter(|multi_workspace| {
 9209            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 9210                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 9211                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 9212                }
 9213                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 9214                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 9215                    a.distro_name == b.distro_name
 9216                }
 9217                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 9218                    a.container_id == b.container_id
 9219                }
 9220                #[cfg(any(test, feature = "test-support"))]
 9221                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 9222                    a.id == b.id
 9223                }
 9224                _ => false,
 9225            };
 9226
 9227            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 9228                multi_workspace.workspaces().any(|workspace| {
 9229                    match workspace.read(cx).workspace_location(cx) {
 9230                        WorkspaceLocation::Location(location, _) => {
 9231                            match (&location, serialized_location) {
 9232                                (
 9233                                    SerializedWorkspaceLocation::Local,
 9234                                    SerializedWorkspaceLocation::Local,
 9235                                ) => true,
 9236                                (
 9237                                    SerializedWorkspaceLocation::Remote(a),
 9238                                    SerializedWorkspaceLocation::Remote(b),
 9239                                ) => same_host(a, b),
 9240                                _ => false,
 9241                            }
 9242                        }
 9243                        _ => false,
 9244                    }
 9245                })
 9246            })
 9247        })
 9248        .collect()
 9249}
 9250
 9251pub async fn find_existing_workspace(
 9252    abs_paths: &[PathBuf],
 9253    open_options: &OpenOptions,
 9254    location: &SerializedWorkspaceLocation,
 9255    cx: &mut AsyncApp,
 9256) -> (
 9257    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 9258    OpenVisible,
 9259) {
 9260    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 9261    let mut open_visible = OpenVisible::All;
 9262    let mut best_match = None;
 9263
 9264    if open_options.workspace_matching != WorkspaceMatching::None {
 9265        cx.update(|cx| {
 9266            for window in workspace_windows_for_location(location, cx) {
 9267                if let Ok(multi_workspace) = window.read(cx) {
 9268                    for workspace in multi_workspace.workspaces() {
 9269                        let project = workspace.read(cx).project.read(cx);
 9270                        let m = project.visibility_for_paths(
 9271                            abs_paths,
 9272                            open_options.workspace_matching != WorkspaceMatching::MatchSubdirectory,
 9273                            cx,
 9274                        );
 9275                        if m > best_match {
 9276                            existing = Some((window, workspace.clone()));
 9277                            best_match = m;
 9278                        } else if best_match.is_none()
 9279                            && open_options.workspace_matching
 9280                                == WorkspaceMatching::MatchSubdirectory
 9281                        {
 9282                            existing = Some((window, workspace.clone()))
 9283                        }
 9284                    }
 9285                }
 9286            }
 9287        });
 9288
 9289        let all_paths_are_files = existing
 9290            .as_ref()
 9291            .and_then(|(_, target_workspace)| {
 9292                cx.update(|cx| {
 9293                    let workspace = target_workspace.read(cx);
 9294                    let project = workspace.project.read(cx);
 9295                    let path_style = workspace.path_style(cx);
 9296                    Some(!abs_paths.iter().any(|path| {
 9297                        let path = util::paths::SanitizedPath::new(path);
 9298                        project.worktrees(cx).any(|worktree| {
 9299                            let worktree = worktree.read(cx);
 9300                            let abs_path = worktree.abs_path();
 9301                            path_style
 9302                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 9303                                .and_then(|rel| worktree.entry_for_path(&rel))
 9304                                .is_some_and(|e| e.is_dir())
 9305                        })
 9306                    }))
 9307                })
 9308            })
 9309            .unwrap_or(false);
 9310
 9311        if open_options.wait && existing.is_some() && all_paths_are_files {
 9312            cx.update(|cx| {
 9313                let windows = workspace_windows_for_location(location, cx);
 9314                let window = cx
 9315                    .active_window()
 9316                    .and_then(|window| window.downcast::<MultiWorkspace>())
 9317                    .filter(|window| windows.contains(window))
 9318                    .or_else(|| windows.into_iter().next());
 9319                if let Some(window) = window {
 9320                    if let Ok(multi_workspace) = window.read(cx) {
 9321                        let active_workspace = multi_workspace.workspace().clone();
 9322                        existing = Some((window, active_workspace));
 9323                        open_visible = OpenVisible::None;
 9324                    }
 9325                }
 9326            });
 9327        }
 9328    }
 9329    (existing, open_visible)
 9330}
 9331
 9332/// Controls whether to reuse an existing workspace whose worktrees contain the
 9333/// given paths, and how broadly to match.
 9334#[derive(Clone, Debug, Default, PartialEq, Eq)]
 9335pub enum WorkspaceMatching {
 9336    /// Always open a new workspace. No matching against existing worktrees.
 9337    None,
 9338    /// Match paths against existing worktree roots and files within them.
 9339    #[default]
 9340    MatchExact,
 9341    /// Match paths against existing worktrees including subdirectories, and
 9342    /// fall back to any existing window if no worktree matched.
 9343    ///
 9344    /// For example, `zed -a foo/bar` will activate the `bar` workspace if it
 9345    /// exists, otherwise it will open a new window with `foo/bar` as the root.
 9346    MatchSubdirectory,
 9347}
 9348
 9349#[derive(Clone)]
 9350pub struct OpenOptions {
 9351    pub visible: Option<OpenVisible>,
 9352    pub focus: Option<bool>,
 9353    pub workspace_matching: WorkspaceMatching,
 9354    /// Whether to add unmatched directories to the existing window's sidebar
 9355    /// rather than opening a new window. Defaults to true, matching the default
 9356    /// `cli_default_open_behavior` setting.
 9357    pub add_dirs_to_sidebar: bool,
 9358    pub wait: bool,
 9359    pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9360    pub open_mode: OpenMode,
 9361    pub env: Option<HashMap<String, String>>,
 9362    pub open_in_dev_container: bool,
 9363}
 9364
 9365impl Default for OpenOptions {
 9366    fn default() -> Self {
 9367        Self {
 9368            visible: None,
 9369            focus: None,
 9370            workspace_matching: WorkspaceMatching::default(),
 9371            add_dirs_to_sidebar: true,
 9372            wait: false,
 9373            requesting_window: None,
 9374            open_mode: OpenMode::default(),
 9375            env: None,
 9376            open_in_dev_container: false,
 9377        }
 9378    }
 9379}
 9380
 9381impl OpenOptions {
 9382    fn should_reuse_existing_window(&self) -> bool {
 9383        self.workspace_matching != WorkspaceMatching::None && self.open_mode != OpenMode::NewWindow
 9384    }
 9385}
 9386
 9387/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 9388/// or [`Workspace::open_workspace_for_paths`].
 9389pub struct OpenResult {
 9390    pub window: WindowHandle<MultiWorkspace>,
 9391    pub workspace: Entity<Workspace>,
 9392    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 9393}
 9394
 9395/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 9396pub fn open_workspace_by_id(
 9397    workspace_id: WorkspaceId,
 9398    app_state: Arc<AppState>,
 9399    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9400    cx: &mut App,
 9401) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 9402    let project_handle = Project::local(
 9403        app_state.client.clone(),
 9404        app_state.node_runtime.clone(),
 9405        app_state.user_store.clone(),
 9406        app_state.languages.clone(),
 9407        app_state.fs.clone(),
 9408        None,
 9409        project::LocalProjectFlags {
 9410            init_worktree_trust: true,
 9411            ..project::LocalProjectFlags::default()
 9412        },
 9413        cx,
 9414    );
 9415
 9416    let db = WorkspaceDb::global(cx);
 9417    let kvp = db::kvp::KeyValueStore::global(cx);
 9418    cx.spawn(async move |cx| {
 9419        let serialized_workspace = db
 9420            .workspace_for_id(workspace_id)
 9421            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 9422
 9423        let centered_layout = serialized_workspace.centered_layout;
 9424
 9425        let (window, workspace) = if let Some(window) = requesting_window {
 9426            let workspace = window.update(cx, |multi_workspace, window, cx| {
 9427                let workspace = cx.new(|cx| {
 9428                    let mut workspace = Workspace::new(
 9429                        Some(workspace_id),
 9430                        project_handle.clone(),
 9431                        app_state.clone(),
 9432                        window,
 9433                        cx,
 9434                    );
 9435                    workspace.centered_layout = centered_layout;
 9436                    workspace
 9437                });
 9438                multi_workspace.add(workspace.clone(), &*window, cx);
 9439                workspace
 9440            })?;
 9441            (window, workspace)
 9442        } else {
 9443            let window_bounds_override = window_bounds_env_override();
 9444
 9445            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 9446                (Some(WindowBounds::Windowed(bounds)), None)
 9447            } else if let Some(display) = serialized_workspace.display
 9448                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 9449            {
 9450                (Some(bounds.0), Some(display))
 9451            } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
 9452                (Some(bounds), Some(display))
 9453            } else {
 9454                (None, None)
 9455            };
 9456
 9457            let options = cx.update(|cx| {
 9458                let mut options = (app_state.build_window_options)(display, cx);
 9459                options.window_bounds = window_bounds;
 9460                options
 9461            });
 9462
 9463            let window = cx.open_window(options, {
 9464                let app_state = app_state.clone();
 9465                let project_handle = project_handle.clone();
 9466                move |window, cx| {
 9467                    let workspace = cx.new(|cx| {
 9468                        let mut workspace = Workspace::new(
 9469                            Some(workspace_id),
 9470                            project_handle,
 9471                            app_state,
 9472                            window,
 9473                            cx,
 9474                        );
 9475                        workspace.centered_layout = centered_layout;
 9476                        workspace
 9477                    });
 9478                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9479                }
 9480            })?;
 9481
 9482            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 9483                multi_workspace.workspace().clone()
 9484            })?;
 9485
 9486            (window, workspace)
 9487        };
 9488
 9489        notify_if_database_failed(window, cx);
 9490
 9491        // Restore items from the serialized workspace
 9492        window
 9493            .update(cx, |_, window, cx| {
 9494                workspace.update(cx, |_workspace, cx| {
 9495                    open_items(Some(serialized_workspace), vec![], window, cx)
 9496                })
 9497            })?
 9498            .await?;
 9499
 9500        window.update(cx, |_, window, cx| {
 9501            workspace.update(cx, |workspace, cx| {
 9502                workspace.serialize_workspace(window, cx);
 9503            });
 9504        })?;
 9505
 9506        Ok(window)
 9507    })
 9508}
 9509
 9510#[allow(clippy::type_complexity)]
 9511pub fn open_paths(
 9512    abs_paths: &[PathBuf],
 9513    app_state: Arc<AppState>,
 9514    mut open_options: OpenOptions,
 9515    cx: &mut App,
 9516) -> Task<anyhow::Result<OpenResult>> {
 9517    let abs_paths = abs_paths.to_vec();
 9518    #[cfg(target_os = "windows")]
 9519    let wsl_path = abs_paths
 9520        .iter()
 9521        .find_map(|p| util::paths::WslPath::from_path(p));
 9522
 9523    cx.spawn(async move |cx| {
 9524        let (mut existing, mut open_visible) = find_existing_workspace(
 9525            &abs_paths,
 9526            &open_options,
 9527            &SerializedWorkspaceLocation::Local,
 9528            cx,
 9529        )
 9530        .await;
 9531
 9532        // Fallback: if no workspace contains the paths and all paths are files,
 9533        // prefer an existing local workspace window (active window first).
 9534        if open_options.should_reuse_existing_window() && existing.is_none() {
 9535            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 9536            let all_metadatas = futures::future::join_all(all_paths)
 9537                .await
 9538                .into_iter()
 9539                .filter_map(|result| result.ok().flatten());
 9540
 9541            if all_metadatas.into_iter().all(|file| !file.is_dir) {
 9542                cx.update(|cx| {
 9543                    let windows = workspace_windows_for_location(
 9544                        &SerializedWorkspaceLocation::Local,
 9545                        cx,
 9546                    );
 9547                    let window = cx
 9548                        .active_window()
 9549                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9550                        .filter(|window| windows.contains(window))
 9551                        .or_else(|| windows.into_iter().next());
 9552                    if let Some(window) = window {
 9553                        if let Ok(multi_workspace) = window.read(cx) {
 9554                            let active_workspace = multi_workspace.workspace().clone();
 9555                            existing = Some((window, active_workspace));
 9556                            open_visible = OpenVisible::None;
 9557                        }
 9558                    }
 9559                });
 9560            }
 9561        }
 9562
 9563        // Fallback for directories: when no flag is specified and no existing
 9564        // workspace matched, check the user's setting to decide whether to add
 9565        // the directory as a new workspace in the active window's MultiWorkspace
 9566        // or open a new window.
 9567        // Skip when requesting_window is already set: the caller (e.g.
 9568        // open_workspace_for_paths reusing an empty window) already chose the
 9569        // target window, so we must not open the sidebar as a side-effect.
 9570        if open_options.should_reuse_existing_window()
 9571            && existing.is_none()
 9572            && open_options.requesting_window.is_none()
 9573        {
 9574            let use_existing_window = open_options.add_dirs_to_sidebar;
 9575
 9576            if use_existing_window {
 9577                let target_window = cx.update(|cx| {
 9578                    let windows = workspace_windows_for_location(
 9579                        &SerializedWorkspaceLocation::Local,
 9580                        cx,
 9581                    );
 9582                    let window = cx
 9583                        .active_window()
 9584                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9585                        .filter(|window| windows.contains(window))
 9586                        .or_else(|| windows.into_iter().next());
 9587                    window.filter(|window| {
 9588                        window
 9589                            .read(cx)
 9590                            .is_ok_and(|mw| mw.multi_workspace_enabled(cx))
 9591                    })
 9592                });
 9593
 9594                if let Some(window) = target_window {
 9595                    open_options.requesting_window = Some(window);
 9596                    window
 9597                        .update(cx, |multi_workspace, _, cx| {
 9598                            multi_workspace.open_sidebar(cx);
 9599                        })
 9600                        .log_err();
 9601                }
 9602            }
 9603        }
 9604
 9605        let open_in_dev_container = open_options.open_in_dev_container;
 9606
 9607        let result = if let Some((existing, target_workspace)) = existing {
 9608            let open_task = existing
 9609                .update(cx, |multi_workspace, window, cx| {
 9610                    window.activate_window();
 9611                    multi_workspace.activate(target_workspace.clone(), window, cx);
 9612                    target_workspace.update(cx, |workspace, cx| {
 9613                        if open_in_dev_container {
 9614                            workspace.set_open_in_dev_container(true);
 9615                        }
 9616                        workspace.open_paths(
 9617                            abs_paths,
 9618                            OpenOptions {
 9619                                visible: Some(open_visible),
 9620                                ..Default::default()
 9621                            },
 9622                            None,
 9623                            window,
 9624                            cx,
 9625                        )
 9626                    })
 9627                })?
 9628                .await;
 9629
 9630            _ = existing.update(cx, |multi_workspace, _, cx| {
 9631                let workspace = multi_workspace.workspace().clone();
 9632                workspace.update(cx, |workspace, cx| {
 9633                    for item in open_task.iter().flatten() {
 9634                        if let Err(e) = item {
 9635                            workspace.show_error(&e, cx);
 9636                        }
 9637                    }
 9638                });
 9639            });
 9640
 9641            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9642        } else {
 9643            let init = if open_in_dev_container {
 9644                Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>| {
 9645                    workspace.set_open_in_dev_container(true);
 9646                }) as Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>)
 9647            } else {
 9648                None
 9649            };
 9650            let result = cx
 9651                .update(move |cx| {
 9652                    Workspace::new_local(
 9653                        abs_paths,
 9654                        app_state.clone(),
 9655                        open_options.requesting_window,
 9656                        open_options.env,
 9657                        init,
 9658                        open_options.open_mode,
 9659                        cx,
 9660                    )
 9661                })
 9662                .await;
 9663
 9664            if let Ok(ref result) = result {
 9665                result.window
 9666                    .update(cx, |_, window, _cx| {
 9667                        window.activate_window();
 9668                    })
 9669                    .log_err();
 9670            }
 9671
 9672            result
 9673        };
 9674
 9675        #[cfg(target_os = "windows")]
 9676        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9677            && let Ok(ref result) = result
 9678        {
 9679            result.window
 9680                .update(cx, move |multi_workspace, _window, cx| {
 9681                    struct OpenInWsl;
 9682                    let workspace = multi_workspace.workspace().clone();
 9683                    workspace.update(cx, |workspace, cx| {
 9684                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9685                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9686                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9687                            cx.new(move |cx| {
 9688                                MessageNotification::new(msg, cx)
 9689                                    .primary_message("Open in WSL")
 9690                                    .primary_icon(IconName::FolderOpen)
 9691                                    .primary_on_click(move |window, cx| {
 9692                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9693                                                distro: remote::WslConnectionOptions {
 9694                                                        distro_name: distro.clone(),
 9695                                                    user: None,
 9696                                                },
 9697                                                paths: vec![path.clone().into()],
 9698                                            }), cx)
 9699                                    })
 9700                            })
 9701                        });
 9702                    });
 9703                })
 9704                .unwrap();
 9705        };
 9706        result
 9707    })
 9708}
 9709
 9710pub fn open_new(
 9711    open_options: OpenOptions,
 9712    app_state: Arc<AppState>,
 9713    cx: &mut App,
 9714    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9715) -> Task<anyhow::Result<()>> {
 9716    let addition = open_options.open_mode;
 9717    let task = Workspace::new_local(
 9718        Vec::new(),
 9719        app_state,
 9720        open_options.requesting_window,
 9721        open_options.env,
 9722        Some(Box::new(init)),
 9723        addition,
 9724        cx,
 9725    );
 9726    cx.spawn(async move |cx| {
 9727        let OpenResult { window, .. } = task.await?;
 9728        window
 9729            .update(cx, |_, window, _cx| {
 9730                window.activate_window();
 9731            })
 9732            .ok();
 9733        Ok(())
 9734    })
 9735}
 9736
 9737pub fn create_and_open_local_file(
 9738    path: &'static Path,
 9739    window: &mut Window,
 9740    cx: &mut Context<Workspace>,
 9741    default_content: impl 'static + Send + FnOnce() -> Rope,
 9742) -> Task<Result<Box<dyn ItemHandle>>> {
 9743    cx.spawn_in(window, async move |workspace, cx| {
 9744        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9745        if !fs.is_file(path).await {
 9746            fs.create_file(path, Default::default()).await?;
 9747            fs.save(path, &default_content(), Default::default())
 9748                .await?;
 9749        }
 9750
 9751        workspace
 9752            .update_in(cx, |workspace, window, cx| {
 9753                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9754                    let path = workspace
 9755                        .project
 9756                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9757                    cx.spawn_in(window, async move |workspace, cx| {
 9758                        let path = path.await?;
 9759
 9760                        let path = fs.canonicalize(&path).await.unwrap_or(path);
 9761
 9762                        let mut items = workspace
 9763                            .update_in(cx, |workspace, window, cx| {
 9764                                workspace.open_paths(
 9765                                    vec![path.to_path_buf()],
 9766                                    OpenOptions {
 9767                                        visible: Some(OpenVisible::None),
 9768                                        ..Default::default()
 9769                                    },
 9770                                    None,
 9771                                    window,
 9772                                    cx,
 9773                                )
 9774                            })?
 9775                            .await;
 9776                        let item = items.pop().flatten();
 9777                        item.with_context(|| format!("path {path:?} is not a file"))?
 9778                    })
 9779                })
 9780            })?
 9781            .await?
 9782            .await
 9783    })
 9784}
 9785
 9786pub fn open_remote_project_with_new_connection(
 9787    window: WindowHandle<MultiWorkspace>,
 9788    remote_connection: Arc<dyn RemoteConnection>,
 9789    cancel_rx: oneshot::Receiver<()>,
 9790    delegate: Arc<dyn RemoteClientDelegate>,
 9791    app_state: Arc<AppState>,
 9792    paths: Vec<PathBuf>,
 9793    cx: &mut App,
 9794) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9795    cx.spawn(async move |cx| {
 9796        let (workspace_id, serialized_workspace) =
 9797            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9798                .await?;
 9799
 9800        let session = match cx
 9801            .update(|cx| {
 9802                remote::RemoteClient::new(
 9803                    ConnectionIdentifier::Workspace(workspace_id.0),
 9804                    remote_connection,
 9805                    cancel_rx,
 9806                    delegate,
 9807                    cx,
 9808                )
 9809            })
 9810            .await?
 9811        {
 9812            Some(result) => result,
 9813            None => return Ok(Vec::new()),
 9814        };
 9815
 9816        let project = cx.update(|cx| {
 9817            project::Project::remote(
 9818                session,
 9819                app_state.client.clone(),
 9820                app_state.node_runtime.clone(),
 9821                app_state.user_store.clone(),
 9822                app_state.languages.clone(),
 9823                app_state.fs.clone(),
 9824                true,
 9825                cx,
 9826            )
 9827        });
 9828
 9829        open_remote_project_inner(
 9830            project,
 9831            paths,
 9832            workspace_id,
 9833            serialized_workspace,
 9834            app_state,
 9835            window,
 9836            None,
 9837            cx,
 9838        )
 9839        .await
 9840    })
 9841}
 9842
 9843pub fn open_remote_project_with_existing_connection(
 9844    connection_options: RemoteConnectionOptions,
 9845    project: Entity<Project>,
 9846    paths: Vec<PathBuf>,
 9847    app_state: Arc<AppState>,
 9848    window: WindowHandle<MultiWorkspace>,
 9849    provisional_project_group_key: Option<ProjectGroupKey>,
 9850    cx: &mut AsyncApp,
 9851) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9852    cx.spawn(async move |cx| {
 9853        let (workspace_id, serialized_workspace) =
 9854            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9855
 9856        open_remote_project_inner(
 9857            project,
 9858            paths,
 9859            workspace_id,
 9860            serialized_workspace,
 9861            app_state,
 9862            window,
 9863            provisional_project_group_key,
 9864            cx,
 9865        )
 9866        .await
 9867    })
 9868}
 9869
 9870async fn open_remote_project_inner(
 9871    project: Entity<Project>,
 9872    paths: Vec<PathBuf>,
 9873    workspace_id: WorkspaceId,
 9874    serialized_workspace: Option<SerializedWorkspace>,
 9875    app_state: Arc<AppState>,
 9876    window: WindowHandle<MultiWorkspace>,
 9877    provisional_project_group_key: Option<ProjectGroupKey>,
 9878    cx: &mut AsyncApp,
 9879) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9880    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9881    let toolchains = db.toolchains(workspace_id).await?;
 9882    for (toolchain, worktree_path, path) in toolchains {
 9883        project
 9884            .update(cx, |this, cx| {
 9885                let Some(worktree_id) =
 9886                    this.find_worktree(&worktree_path, cx)
 9887                        .and_then(|(worktree, rel_path)| {
 9888                            if rel_path.is_empty() {
 9889                                Some(worktree.read(cx).id())
 9890                            } else {
 9891                                None
 9892                            }
 9893                        })
 9894                else {
 9895                    return Task::ready(None);
 9896                };
 9897
 9898                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9899            })
 9900            .await;
 9901    }
 9902    let mut project_paths_to_open = vec![];
 9903    let mut project_path_errors = vec![];
 9904
 9905    for path in paths {
 9906        let result = cx
 9907            .update(|cx| {
 9908                Workspace::project_path_for_path(project.clone(), path.as_path(), true, cx)
 9909            })
 9910            .await;
 9911        match result {
 9912            Ok((_, project_path)) => {
 9913                project_paths_to_open.push((path, Some(project_path)));
 9914            }
 9915            Err(error) => {
 9916                project_path_errors.push(error);
 9917            }
 9918        };
 9919    }
 9920
 9921    if project_paths_to_open.is_empty() {
 9922        return Err(project_path_errors.pop().context("no paths given")?);
 9923    }
 9924
 9925    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9926        telemetry::event!("SSH Project Opened");
 9927
 9928        let new_workspace = cx.new(|cx| {
 9929            let mut workspace =
 9930                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9931            workspace.update_history(cx);
 9932
 9933            if let Some(ref serialized) = serialized_workspace {
 9934                workspace.centered_layout = serialized.centered_layout;
 9935            }
 9936
 9937            workspace
 9938        });
 9939
 9940        if let Some(project_group_key) = provisional_project_group_key.clone() {
 9941            multi_workspace.retain_workspace(new_workspace.clone(), project_group_key, cx);
 9942        }
 9943        multi_workspace.activate(new_workspace.clone(), window, cx);
 9944        new_workspace
 9945    })?;
 9946
 9947    let items = window
 9948        .update(cx, |_, window, cx| {
 9949            window.activate_window();
 9950            workspace.update(cx, |_workspace, cx| {
 9951                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9952            })
 9953        })?
 9954        .await?;
 9955
 9956    workspace.update(cx, |workspace, cx| {
 9957        for error in project_path_errors {
 9958            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9959                if let Some(path) = error.error_tag("path") {
 9960                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9961                }
 9962            } else {
 9963                workspace.show_error(&error, cx)
 9964            }
 9965        }
 9966    });
 9967
 9968    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9969}
 9970
 9971fn deserialize_remote_project(
 9972    connection_options: RemoteConnectionOptions,
 9973    paths: Vec<PathBuf>,
 9974    cx: &AsyncApp,
 9975) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9976    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9977    cx.background_spawn(async move {
 9978        let remote_connection_id = db
 9979            .get_or_create_remote_connection(connection_options)
 9980            .await?;
 9981
 9982        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
 9983
 9984        let workspace_id = if let Some(workspace_id) =
 9985            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9986        {
 9987            workspace_id
 9988        } else {
 9989            db.next_id().await?
 9990        };
 9991
 9992        Ok((workspace_id, serialized_workspace))
 9993    })
 9994}
 9995
 9996pub fn join_in_room_project(
 9997    project_id: u64,
 9998    follow_user_id: u64,
 9999    app_state: Arc<AppState>,
10000    cx: &mut App,
10001) -> Task<Result<()>> {
10002    let windows = cx.windows();
10003    cx.spawn(async move |cx| {
10004        let existing_window_and_workspace: Option<(
10005            WindowHandle<MultiWorkspace>,
10006            Entity<Workspace>,
10007        )> = windows.into_iter().find_map(|window_handle| {
10008            window_handle
10009                .downcast::<MultiWorkspace>()
10010                .and_then(|window_handle| {
10011                    window_handle
10012                        .update(cx, |multi_workspace, _window, cx| {
10013                            multi_workspace
10014                                .workspaces()
10015                                .find(|workspace| {
10016                                    workspace.read(cx).project().read(cx).remote_id()
10017                                        == Some(project_id)
10018                                })
10019                                .map(|workspace| (window_handle, workspace.clone()))
10020                        })
10021                        .unwrap_or(None)
10022                })
10023        });
10024
10025        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
10026            existing_window_and_workspace
10027        {
10028            existing_window
10029                .update(cx, |multi_workspace, window, cx| {
10030                    multi_workspace.activate(target_workspace, window, cx);
10031                })
10032                .ok();
10033            existing_window
10034        } else {
10035            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
10036            let project = cx
10037                .update(|cx| {
10038                    active_call.0.join_project(
10039                        project_id,
10040                        app_state.languages.clone(),
10041                        app_state.fs.clone(),
10042                        cx,
10043                    )
10044                })
10045                .await?;
10046
10047            let window_bounds_override = window_bounds_env_override();
10048            cx.update(|cx| {
10049                let mut options = (app_state.build_window_options)(None, cx);
10050                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
10051                cx.open_window(options, |window, cx| {
10052                    let workspace = cx.new(|cx| {
10053                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
10054                    });
10055                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
10056                })
10057            })?
10058        };
10059
10060        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
10061            cx.activate(true);
10062            window.activate_window();
10063
10064            // We set the active workspace above, so this is the correct workspace.
10065            let workspace = multi_workspace.workspace().clone();
10066            workspace.update(cx, |workspace, cx| {
10067                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
10068                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
10069                    .or_else(|| {
10070                        // If we couldn't follow the given user, follow the host instead.
10071                        let collaborator = workspace
10072                            .project()
10073                            .read(cx)
10074                            .collaborators()
10075                            .values()
10076                            .find(|collaborator| collaborator.is_host)?;
10077                        Some(collaborator.peer_id)
10078                    });
10079
10080                if let Some(follow_peer_id) = follow_peer_id {
10081                    workspace.follow(follow_peer_id, window, cx);
10082                }
10083            });
10084        })?;
10085
10086        anyhow::Ok(())
10087    })
10088}
10089
10090pub fn reload(cx: &mut App) {
10091    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
10092    let mut workspace_windows = cx
10093        .windows()
10094        .into_iter()
10095        .filter_map(|window| window.downcast::<MultiWorkspace>())
10096        .collect::<Vec<_>>();
10097
10098    // If multiple windows have unsaved changes, and need a save prompt,
10099    // prompt in the active window before switching to a different window.
10100    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
10101
10102    let mut prompt = None;
10103    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
10104        prompt = window
10105            .update(cx, |_, window, cx| {
10106                window.prompt(
10107                    PromptLevel::Info,
10108                    "Are you sure you want to restart?",
10109                    None,
10110                    &["Restart", "Cancel"],
10111                    cx,
10112                )
10113            })
10114            .ok();
10115    }
10116
10117    cx.spawn(async move |cx| {
10118        if let Some(prompt) = prompt {
10119            let answer = prompt.await?;
10120            if answer != 0 {
10121                return anyhow::Ok(());
10122            }
10123        }
10124
10125        // If the user cancels any save prompt, then keep the app open.
10126        for window in workspace_windows {
10127            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
10128                let workspace = multi_workspace.workspace().clone();
10129                workspace.update(cx, |workspace, cx| {
10130                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
10131                })
10132            }) && !should_close.await?
10133            {
10134                return anyhow::Ok(());
10135            }
10136        }
10137        cx.update(|cx| cx.restart());
10138        anyhow::Ok(())
10139    })
10140    .detach_and_log_err(cx);
10141}
10142
10143fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
10144    let mut parts = value.split(',');
10145    let x: usize = parts.next()?.parse().ok()?;
10146    let y: usize = parts.next()?.parse().ok()?;
10147    Some(point(px(x as f32), px(y as f32)))
10148}
10149
10150fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
10151    let mut parts = value.split(',');
10152    let width: usize = parts.next()?.parse().ok()?;
10153    let height: usize = parts.next()?.parse().ok()?;
10154    Some(size(px(width as f32), px(height as f32)))
10155}
10156
10157/// Add client-side decorations (rounded corners, shadows, resize handling) when
10158/// appropriate.
10159///
10160/// The `border_radius_tiling` parameter allows overriding which corners get
10161/// rounded, independently of the actual window tiling state. This is used
10162/// specifically for the workspace switcher sidebar: when the sidebar is open,
10163/// we want square corners on the left (so the sidebar appears flush with the
10164/// window edge) but we still need the shadow padding for proper visual
10165/// appearance. Unlike actual window tiling, this only affects border radius -
10166/// not padding or shadows.
10167pub fn client_side_decorations(
10168    element: impl IntoElement,
10169    window: &mut Window,
10170    cx: &mut App,
10171    border_radius_tiling: Tiling,
10172) -> Stateful<Div> {
10173    const BORDER_SIZE: Pixels = px(1.0);
10174    let decorations = window.window_decorations();
10175    let tiling = match decorations {
10176        Decorations::Server => Tiling::default(),
10177        Decorations::Client { tiling } => tiling,
10178    };
10179
10180    match decorations {
10181        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
10182        Decorations::Server => window.set_client_inset(px(0.0)),
10183    }
10184
10185    struct GlobalResizeEdge(ResizeEdge);
10186    impl Global for GlobalResizeEdge {}
10187
10188    div()
10189        .id("window-backdrop")
10190        .bg(transparent_black())
10191        .map(|div| match decorations {
10192            Decorations::Server => div,
10193            Decorations::Client { .. } => div
10194                .when(
10195                    !(tiling.top
10196                        || tiling.right
10197                        || border_radius_tiling.top
10198                        || border_radius_tiling.right),
10199                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10200                )
10201                .when(
10202                    !(tiling.top
10203                        || tiling.left
10204                        || border_radius_tiling.top
10205                        || border_radius_tiling.left),
10206                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10207                )
10208                .when(
10209                    !(tiling.bottom
10210                        || tiling.right
10211                        || border_radius_tiling.bottom
10212                        || border_radius_tiling.right),
10213                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10214                )
10215                .when(
10216                    !(tiling.bottom
10217                        || tiling.left
10218                        || border_radius_tiling.bottom
10219                        || border_radius_tiling.left),
10220                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10221                )
10222                .when(!tiling.top, |div| {
10223                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
10224                })
10225                .when(!tiling.bottom, |div| {
10226                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
10227                })
10228                .when(!tiling.left, |div| {
10229                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10230                })
10231                .when(!tiling.right, |div| {
10232                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10233                })
10234                .on_mouse_move(move |e, window, cx| {
10235                    let size = window.window_bounds().get_bounds().size;
10236                    let pos = e.position;
10237
10238                    let new_edge =
10239                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10240
10241                    let edge = cx.try_global::<GlobalResizeEdge>();
10242                    if new_edge != edge.map(|edge| edge.0) {
10243                        window
10244                            .window_handle()
10245                            .update(cx, |workspace, _, cx| {
10246                                cx.notify(workspace.entity_id());
10247                            })
10248                            .ok();
10249                    }
10250                })
10251                .on_mouse_down(MouseButton::Left, move |e, window, _| {
10252                    let size = window.window_bounds().get_bounds().size;
10253                    let pos = e.position;
10254
10255                    let edge = match resize_edge(
10256                        pos,
10257                        theme::CLIENT_SIDE_DECORATION_SHADOW,
10258                        size,
10259                        tiling,
10260                    ) {
10261                        Some(value) => value,
10262                        None => return,
10263                    };
10264
10265                    window.start_window_resize(edge);
10266                }),
10267        })
10268        .size_full()
10269        .child(
10270            div()
10271                .cursor(CursorStyle::Arrow)
10272                .map(|div| match decorations {
10273                    Decorations::Server => div,
10274                    Decorations::Client { .. } => div
10275                        .border_color(cx.theme().colors().border)
10276                        .when(
10277                            !(tiling.top
10278                                || tiling.right
10279                                || border_radius_tiling.top
10280                                || border_radius_tiling.right),
10281                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10282                        )
10283                        .when(
10284                            !(tiling.top
10285                                || tiling.left
10286                                || border_radius_tiling.top
10287                                || border_radius_tiling.left),
10288                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10289                        )
10290                        .when(
10291                            !(tiling.bottom
10292                                || tiling.right
10293                                || border_radius_tiling.bottom
10294                                || border_radius_tiling.right),
10295                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10296                        )
10297                        .when(
10298                            !(tiling.bottom
10299                                || tiling.left
10300                                || border_radius_tiling.bottom
10301                                || border_radius_tiling.left),
10302                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10303                        )
10304                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10305                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10306                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10307                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10308                        .when(!tiling.is_tiled(), |div| {
10309                            div.shadow(vec![gpui::BoxShadow {
10310                                color: Hsla {
10311                                    h: 0.,
10312                                    s: 0.,
10313                                    l: 0.,
10314                                    a: 0.4,
10315                                },
10316                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10317                                spread_radius: px(0.),
10318                                offset: point(px(0.0), px(0.0)),
10319                            }])
10320                        }),
10321                })
10322                .on_mouse_move(|_e, _, cx| {
10323                    cx.stop_propagation();
10324                })
10325                .size_full()
10326                .child(element),
10327        )
10328        .map(|div| match decorations {
10329            Decorations::Server => div,
10330            Decorations::Client { tiling, .. } => div.child(
10331                canvas(
10332                    |_bounds, window, _| {
10333                        window.insert_hitbox(
10334                            Bounds::new(
10335                                point(px(0.0), px(0.0)),
10336                                window.window_bounds().get_bounds().size,
10337                            ),
10338                            HitboxBehavior::Normal,
10339                        )
10340                    },
10341                    move |_bounds, hitbox, window, cx| {
10342                        let mouse = window.mouse_position();
10343                        let size = window.window_bounds().get_bounds().size;
10344                        let Some(edge) =
10345                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10346                        else {
10347                            return;
10348                        };
10349                        cx.set_global(GlobalResizeEdge(edge));
10350                        window.set_cursor_style(
10351                            match edge {
10352                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10353                                ResizeEdge::Left | ResizeEdge::Right => {
10354                                    CursorStyle::ResizeLeftRight
10355                                }
10356                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10357                                    CursorStyle::ResizeUpLeftDownRight
10358                                }
10359                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10360                                    CursorStyle::ResizeUpRightDownLeft
10361                                }
10362                            },
10363                            &hitbox,
10364                        );
10365                    },
10366                )
10367                .size_full()
10368                .absolute(),
10369            ),
10370        })
10371}
10372
10373fn resize_edge(
10374    pos: Point<Pixels>,
10375    shadow_size: Pixels,
10376    window_size: Size<Pixels>,
10377    tiling: Tiling,
10378) -> Option<ResizeEdge> {
10379    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10380    if bounds.contains(&pos) {
10381        return None;
10382    }
10383
10384    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10385    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10386    if !tiling.top && top_left_bounds.contains(&pos) {
10387        return Some(ResizeEdge::TopLeft);
10388    }
10389
10390    let top_right_bounds = Bounds::new(
10391        Point::new(window_size.width - corner_size.width, px(0.)),
10392        corner_size,
10393    );
10394    if !tiling.top && top_right_bounds.contains(&pos) {
10395        return Some(ResizeEdge::TopRight);
10396    }
10397
10398    let bottom_left_bounds = Bounds::new(
10399        Point::new(px(0.), window_size.height - corner_size.height),
10400        corner_size,
10401    );
10402    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10403        return Some(ResizeEdge::BottomLeft);
10404    }
10405
10406    let bottom_right_bounds = Bounds::new(
10407        Point::new(
10408            window_size.width - corner_size.width,
10409            window_size.height - corner_size.height,
10410        ),
10411        corner_size,
10412    );
10413    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10414        return Some(ResizeEdge::BottomRight);
10415    }
10416
10417    if !tiling.top && pos.y < shadow_size {
10418        Some(ResizeEdge::Top)
10419    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10420        Some(ResizeEdge::Bottom)
10421    } else if !tiling.left && pos.x < shadow_size {
10422        Some(ResizeEdge::Left)
10423    } else if !tiling.right && pos.x > window_size.width - shadow_size {
10424        Some(ResizeEdge::Right)
10425    } else {
10426        None
10427    }
10428}
10429
10430fn join_pane_into_active(
10431    active_pane: &Entity<Pane>,
10432    pane: &Entity<Pane>,
10433    window: &mut Window,
10434    cx: &mut App,
10435) {
10436    if pane == active_pane {
10437    } else if pane.read(cx).items_len() == 0 {
10438        pane.update(cx, |_, cx| {
10439            cx.emit(pane::Event::Remove {
10440                focus_on_pane: None,
10441            });
10442        })
10443    } else {
10444        move_all_items(pane, active_pane, window, cx);
10445    }
10446}
10447
10448fn move_all_items(
10449    from_pane: &Entity<Pane>,
10450    to_pane: &Entity<Pane>,
10451    window: &mut Window,
10452    cx: &mut App,
10453) {
10454    let destination_is_different = from_pane != to_pane;
10455    let mut moved_items = 0;
10456    for (item_ix, item_handle) in from_pane
10457        .read(cx)
10458        .items()
10459        .enumerate()
10460        .map(|(ix, item)| (ix, item.clone()))
10461        .collect::<Vec<_>>()
10462    {
10463        let ix = item_ix - moved_items;
10464        if destination_is_different {
10465            // Close item from previous pane
10466            from_pane.update(cx, |source, cx| {
10467                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10468            });
10469            moved_items += 1;
10470        }
10471
10472        // This automatically removes duplicate items in the pane
10473        to_pane.update(cx, |destination, cx| {
10474            destination.add_item(item_handle, true, true, None, window, cx);
10475            window.focus(&destination.focus_handle(cx), cx)
10476        });
10477    }
10478}
10479
10480pub fn move_item(
10481    source: &Entity<Pane>,
10482    destination: &Entity<Pane>,
10483    item_id_to_move: EntityId,
10484    destination_index: usize,
10485    activate: bool,
10486    window: &mut Window,
10487    cx: &mut App,
10488) {
10489    let Some((item_ix, item_handle)) = source
10490        .read(cx)
10491        .items()
10492        .enumerate()
10493        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10494        .map(|(ix, item)| (ix, item.clone()))
10495    else {
10496        // Tab was closed during drag
10497        return;
10498    };
10499
10500    if source != destination {
10501        // Close item from previous pane
10502        source.update(cx, |source, cx| {
10503            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10504        });
10505    }
10506
10507    // This automatically removes duplicate items in the pane
10508    destination.update(cx, |destination, cx| {
10509        destination.add_item_inner(
10510            item_handle,
10511            activate,
10512            activate,
10513            activate,
10514            Some(destination_index),
10515            window,
10516            cx,
10517        );
10518        if activate {
10519            window.focus(&destination.focus_handle(cx), cx)
10520        }
10521    });
10522}
10523
10524pub fn move_active_item(
10525    source: &Entity<Pane>,
10526    destination: &Entity<Pane>,
10527    focus_destination: bool,
10528    close_if_empty: bool,
10529    window: &mut Window,
10530    cx: &mut App,
10531) {
10532    if source == destination {
10533        return;
10534    }
10535    let Some(active_item) = source.read(cx).active_item() else {
10536        return;
10537    };
10538    source.update(cx, |source_pane, cx| {
10539        let item_id = active_item.item_id();
10540        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10541        destination.update(cx, |target_pane, cx| {
10542            target_pane.add_item(
10543                active_item,
10544                focus_destination,
10545                focus_destination,
10546                Some(target_pane.items_len()),
10547                window,
10548                cx,
10549            );
10550        });
10551    });
10552}
10553
10554pub fn clone_active_item(
10555    workspace_id: Option<WorkspaceId>,
10556    source: &Entity<Pane>,
10557    destination: &Entity<Pane>,
10558    focus_destination: bool,
10559    window: &mut Window,
10560    cx: &mut App,
10561) {
10562    if source == destination {
10563        return;
10564    }
10565    let Some(active_item) = source.read(cx).active_item() else {
10566        return;
10567    };
10568    if !active_item.can_split(cx) {
10569        return;
10570    }
10571    let destination = destination.downgrade();
10572    let task = active_item.clone_on_split(workspace_id, window, cx);
10573    window
10574        .spawn(cx, async move |cx| {
10575            let Some(clone) = task.await else {
10576                return;
10577            };
10578            destination
10579                .update_in(cx, |target_pane, window, cx| {
10580                    target_pane.add_item(
10581                        clone,
10582                        focus_destination,
10583                        focus_destination,
10584                        Some(target_pane.items_len()),
10585                        window,
10586                        cx,
10587                    );
10588                })
10589                .log_err();
10590        })
10591        .detach();
10592}
10593
10594#[derive(Debug)]
10595pub struct WorkspacePosition {
10596    pub window_bounds: Option<WindowBounds>,
10597    pub display: Option<Uuid>,
10598    pub centered_layout: bool,
10599}
10600
10601pub fn remote_workspace_position_from_db(
10602    connection_options: RemoteConnectionOptions,
10603    paths_to_open: &[PathBuf],
10604    cx: &App,
10605) -> Task<Result<WorkspacePosition>> {
10606    let paths = paths_to_open.to_vec();
10607    let db = WorkspaceDb::global(cx);
10608    let kvp = db::kvp::KeyValueStore::global(cx);
10609
10610    cx.background_spawn(async move {
10611        let remote_connection_id = db
10612            .get_or_create_remote_connection(connection_options)
10613            .await
10614            .context("fetching serialized ssh project")?;
10615        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10616
10617        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10618            (Some(WindowBounds::Windowed(bounds)), None)
10619        } else {
10620            let restorable_bounds = serialized_workspace
10621                .as_ref()
10622                .and_then(|workspace| {
10623                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10624                })
10625                .or_else(|| persistence::read_default_window_bounds(&kvp));
10626
10627            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10628                (Some(serialized_bounds), Some(serialized_display))
10629            } else {
10630                (None, None)
10631            }
10632        };
10633
10634        let centered_layout = serialized_workspace
10635            .as_ref()
10636            .map(|w| w.centered_layout)
10637            .unwrap_or(false);
10638
10639        Ok(WorkspacePosition {
10640            window_bounds,
10641            display,
10642            centered_layout,
10643        })
10644    })
10645}
10646
10647pub fn with_active_or_new_workspace(
10648    cx: &mut App,
10649    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10650) {
10651    match cx
10652        .active_window()
10653        .and_then(|w| w.downcast::<MultiWorkspace>())
10654    {
10655        Some(multi_workspace) => {
10656            cx.defer(move |cx| {
10657                multi_workspace
10658                    .update(cx, |multi_workspace, window, cx| {
10659                        let workspace = multi_workspace.workspace().clone();
10660                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10661                    })
10662                    .log_err();
10663            });
10664        }
10665        None => {
10666            let app_state = AppState::global(cx);
10667            open_new(
10668                OpenOptions::default(),
10669                app_state,
10670                cx,
10671                move |workspace, window, cx| f(workspace, window, cx),
10672            )
10673            .detach_and_log_err(cx);
10674        }
10675    }
10676}
10677
10678/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10679/// key. This migration path only runs once per panel per workspace.
10680fn load_legacy_panel_size(
10681    panel_key: &str,
10682    dock_position: DockPosition,
10683    workspace: &Workspace,
10684    cx: &mut App,
10685) -> Option<Pixels> {
10686    #[derive(Deserialize)]
10687    struct LegacyPanelState {
10688        #[serde(default)]
10689        width: Option<Pixels>,
10690        #[serde(default)]
10691        height: Option<Pixels>,
10692    }
10693
10694    let workspace_id = workspace
10695        .database_id()
10696        .map(|id| i64::from(id).to_string())
10697        .or_else(|| workspace.session_id())?;
10698
10699    let legacy_key = match panel_key {
10700        "ProjectPanel" => {
10701            format!("{}-{:?}", "ProjectPanel", workspace_id)
10702        }
10703        "OutlinePanel" => {
10704            format!("{}-{:?}", "OutlinePanel", workspace_id)
10705        }
10706        "GitPanel" => {
10707            format!("{}-{:?}", "GitPanel", workspace_id)
10708        }
10709        "TerminalPanel" => {
10710            format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10711        }
10712        _ => return None,
10713    };
10714
10715    let kvp = db::kvp::KeyValueStore::global(cx);
10716    let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10717    let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10718    let size = match dock_position {
10719        DockPosition::Bottom => state.height,
10720        DockPosition::Left | DockPosition::Right => state.width,
10721    }?;
10722
10723    cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10724        .detach_and_log_err(cx);
10725
10726    Some(size)
10727}
10728
10729#[cfg(test)]
10730mod tests {
10731    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10732
10733    use super::*;
10734    use crate::{
10735        dock::{PanelEvent, test::TestPanel},
10736        item::{
10737            ItemBufferKind, ItemEvent,
10738            test::{TestItem, TestProjectItem},
10739        },
10740    };
10741    use fs::FakeFs;
10742    use gpui::{
10743        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10744        UpdateGlobal, VisualTestContext, px,
10745    };
10746    use project::{Project, ProjectEntryId};
10747    use serde_json::json;
10748    use settings::SettingsStore;
10749    use util::path;
10750    use util::rel_path::rel_path;
10751
10752    #[gpui::test]
10753    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10754        init_test(cx);
10755
10756        let fs = FakeFs::new(cx.executor());
10757        let project = Project::test(fs, [], cx).await;
10758        let (workspace, cx) =
10759            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10760
10761        // Adding an item with no ambiguity renders the tab without detail.
10762        let item1 = cx.new(|cx| {
10763            let mut item = TestItem::new(cx);
10764            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10765            item
10766        });
10767        workspace.update_in(cx, |workspace, window, cx| {
10768            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10769        });
10770        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10771
10772        // Adding an item that creates ambiguity increases the level of detail on
10773        // both tabs.
10774        let item2 = cx.new_window_entity(|_window, cx| {
10775            let mut item = TestItem::new(cx);
10776            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10777            item
10778        });
10779        workspace.update_in(cx, |workspace, window, cx| {
10780            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10781        });
10782        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10783        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10784
10785        // Adding an item that creates ambiguity increases the level of detail only
10786        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10787        // we stop at the highest detail available.
10788        let item3 = cx.new(|cx| {
10789            let mut item = TestItem::new(cx);
10790            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10791            item
10792        });
10793        workspace.update_in(cx, |workspace, window, cx| {
10794            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10795        });
10796        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10797        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10798        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10799    }
10800
10801    #[gpui::test]
10802    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10803        init_test(cx);
10804
10805        let fs = FakeFs::new(cx.executor());
10806        fs.insert_tree(
10807            "/root1",
10808            json!({
10809                "one.txt": "",
10810                "two.txt": "",
10811            }),
10812        )
10813        .await;
10814        fs.insert_tree(
10815            "/root2",
10816            json!({
10817                "three.txt": "",
10818            }),
10819        )
10820        .await;
10821
10822        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10823        let (workspace, cx) =
10824            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10825        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10826        let worktree_id = project.update(cx, |project, cx| {
10827            project.worktrees(cx).next().unwrap().read(cx).id()
10828        });
10829
10830        let item1 = cx.new(|cx| {
10831            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10832        });
10833        let item2 = cx.new(|cx| {
10834            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10835        });
10836
10837        // Add an item to an empty pane
10838        workspace.update_in(cx, |workspace, window, cx| {
10839            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10840        });
10841        project.update(cx, |project, cx| {
10842            assert_eq!(
10843                project.active_entry(),
10844                project
10845                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10846                    .map(|e| e.id)
10847            );
10848        });
10849        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10850
10851        // Add a second item to a non-empty pane
10852        workspace.update_in(cx, |workspace, window, cx| {
10853            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10854        });
10855        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10856        project.update(cx, |project, cx| {
10857            assert_eq!(
10858                project.active_entry(),
10859                project
10860                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10861                    .map(|e| e.id)
10862            );
10863        });
10864
10865        // Close the active item
10866        pane.update_in(cx, |pane, window, cx| {
10867            pane.close_active_item(&Default::default(), window, cx)
10868        })
10869        .await
10870        .unwrap();
10871        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10872        project.update(cx, |project, cx| {
10873            assert_eq!(
10874                project.active_entry(),
10875                project
10876                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10877                    .map(|e| e.id)
10878            );
10879        });
10880
10881        // Add a project folder
10882        project
10883            .update(cx, |project, cx| {
10884                project.find_or_create_worktree("root2", true, cx)
10885            })
10886            .await
10887            .unwrap();
10888        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10889
10890        // Remove a project folder
10891        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10892        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10893    }
10894
10895    #[gpui::test]
10896    async fn test_close_window(cx: &mut TestAppContext) {
10897        init_test(cx);
10898
10899        let fs = FakeFs::new(cx.executor());
10900        fs.insert_tree("/root", json!({ "one": "" })).await;
10901
10902        let project = Project::test(fs, ["root".as_ref()], cx).await;
10903        let (workspace, cx) =
10904            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10905
10906        // When there are no dirty items, there's nothing to do.
10907        let item1 = cx.new(TestItem::new);
10908        workspace.update_in(cx, |w, window, cx| {
10909            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10910        });
10911        let task = workspace.update_in(cx, |w, window, cx| {
10912            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10913        });
10914        assert!(task.await.unwrap());
10915
10916        // When there are dirty untitled items, prompt to save each one. If the user
10917        // cancels any prompt, then abort.
10918        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10919        let item3 = cx.new(|cx| {
10920            TestItem::new(cx)
10921                .with_dirty(true)
10922                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10923        });
10924        workspace.update_in(cx, |w, window, cx| {
10925            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10926            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10927        });
10928        let task = workspace.update_in(cx, |w, window, cx| {
10929            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10930        });
10931        cx.executor().run_until_parked();
10932        cx.simulate_prompt_answer("Cancel"); // cancel save all
10933        cx.executor().run_until_parked();
10934        assert!(!cx.has_pending_prompt());
10935        assert!(!task.await.unwrap());
10936    }
10937
10938    #[gpui::test]
10939    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10940        init_test(cx);
10941
10942        let fs = FakeFs::new(cx.executor());
10943        fs.insert_tree("/root", json!({ "one": "" })).await;
10944
10945        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10946        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10947        let multi_workspace_handle =
10948            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10949        cx.run_until_parked();
10950
10951        multi_workspace_handle
10952            .update(cx, |mw, _window, cx| {
10953                mw.open_sidebar(cx);
10954            })
10955            .unwrap();
10956
10957        let workspace_a = multi_workspace_handle
10958            .read_with(cx, |mw, _| mw.workspace().clone())
10959            .unwrap();
10960
10961        let workspace_b = multi_workspace_handle
10962            .update(cx, |mw, window, cx| {
10963                mw.test_add_workspace(project_b, window, cx)
10964            })
10965            .unwrap();
10966
10967        // Activate workspace A
10968        multi_workspace_handle
10969            .update(cx, |mw, window, cx| {
10970                mw.activate(workspace_a.clone(), window, cx);
10971            })
10972            .unwrap();
10973
10974        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10975
10976        // Workspace A has a clean item
10977        let item_a = cx.new(TestItem::new);
10978        workspace_a.update_in(cx, |w, window, cx| {
10979            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10980        });
10981
10982        // Workspace B has a dirty item
10983        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10984        workspace_b.update_in(cx, |w, window, cx| {
10985            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10986        });
10987
10988        // Verify workspace A is active
10989        multi_workspace_handle
10990            .read_with(cx, |mw, _| {
10991                assert_eq!(mw.workspace(), &workspace_a);
10992            })
10993            .unwrap();
10994
10995        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10996        multi_workspace_handle
10997            .update(cx, |mw, window, cx| {
10998                mw.close_window(&CloseWindow, window, cx);
10999            })
11000            .unwrap();
11001        cx.run_until_parked();
11002
11003        // Workspace B should now be active since it has dirty items that need attention
11004        multi_workspace_handle
11005            .read_with(cx, |mw, _| {
11006                assert_eq!(
11007                    mw.workspace(),
11008                    &workspace_b,
11009                    "workspace B should be activated when it prompts"
11010                );
11011            })
11012            .unwrap();
11013
11014        // User cancels the save prompt from workspace B
11015        cx.simulate_prompt_answer("Cancel");
11016        cx.run_until_parked();
11017
11018        // Window should still exist because workspace B's close was cancelled
11019        assert!(
11020            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
11021            "window should still exist after cancelling one workspace's close"
11022        );
11023    }
11024
11025    #[gpui::test]
11026    async fn test_remove_workspace_prompts_for_unsaved_changes(cx: &mut TestAppContext) {
11027        init_test(cx);
11028
11029        let fs = FakeFs::new(cx.executor());
11030        fs.insert_tree("/root", json!({ "one": "" })).await;
11031
11032        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
11033        let project_b = Project::test(fs.clone(), ["root".as_ref()], cx).await;
11034        let multi_workspace_handle =
11035            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
11036        cx.run_until_parked();
11037
11038        multi_workspace_handle
11039            .update(cx, |mw, _window, cx| mw.open_sidebar(cx))
11040            .unwrap();
11041
11042        let workspace_a = multi_workspace_handle
11043            .read_with(cx, |mw, _| mw.workspace().clone())
11044            .unwrap();
11045
11046        let workspace_b = multi_workspace_handle
11047            .update(cx, |mw, window, cx| {
11048                mw.test_add_workspace(project_b, window, cx)
11049            })
11050            .unwrap();
11051
11052        // Activate workspace A.
11053        multi_workspace_handle
11054            .update(cx, |mw, window, cx| {
11055                mw.activate(workspace_a.clone(), window, cx);
11056            })
11057            .unwrap();
11058
11059        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
11060
11061        // Workspace B has a dirty item.
11062        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
11063        workspace_b.update_in(cx, |w, window, cx| {
11064            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
11065        });
11066
11067        // Try to remove workspace B. It should prompt because of the dirty item.
11068        let remove_task = multi_workspace_handle
11069            .update(cx, |mw, window, cx| {
11070                mw.remove([workspace_b.clone()], |_, _, _| unreachable!(), window, cx)
11071            })
11072            .unwrap();
11073        cx.run_until_parked();
11074
11075        // The prompt should have activated workspace B.
11076        multi_workspace_handle
11077            .read_with(cx, |mw, _| {
11078                assert_eq!(
11079                    mw.workspace(),
11080                    &workspace_b,
11081                    "workspace B should be active while prompting"
11082                );
11083            })
11084            .unwrap();
11085
11086        // Cancel the prompt — user stays on workspace B.
11087        cx.simulate_prompt_answer("Cancel");
11088        cx.run_until_parked();
11089        let removed = remove_task.await.unwrap();
11090        assert!(!removed, "removal should have been cancelled");
11091
11092        multi_workspace_handle
11093            .read_with(cx, |mw, _cx| {
11094                assert_eq!(
11095                    mw.workspace(),
11096                    &workspace_b,
11097                    "user should stay on workspace B after cancelling"
11098                );
11099                assert_eq!(mw.workspaces().count(), 2, "both workspaces should remain");
11100            })
11101            .unwrap();
11102
11103        // Try again. This time accept the prompt.
11104        let remove_task = multi_workspace_handle
11105            .update(cx, |mw, window, cx| {
11106                // First switch back to A.
11107                mw.activate(workspace_a.clone(), window, cx);
11108                mw.remove([workspace_b.clone()], |_, _, _| unreachable!(), window, cx)
11109            })
11110            .unwrap();
11111        cx.run_until_parked();
11112
11113        // Accept the save prompt.
11114        cx.simulate_prompt_answer("Don't Save");
11115        cx.run_until_parked();
11116        let removed = remove_task.await.unwrap();
11117        assert!(removed, "removal should have succeeded");
11118
11119        // Should be back on workspace A, and B should be gone.
11120        multi_workspace_handle
11121            .read_with(cx, |mw, _cx| {
11122                assert_eq!(
11123                    mw.workspace(),
11124                    &workspace_a,
11125                    "should be back on workspace A after removing B"
11126                );
11127                assert_eq!(mw.workspaces().count(), 1, "only workspace A should remain");
11128            })
11129            .unwrap();
11130    }
11131
11132    #[gpui::test]
11133    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
11134        init_test(cx);
11135
11136        // Register TestItem as a serializable item
11137        cx.update(|cx| {
11138            register_serializable_item::<TestItem>(cx);
11139        });
11140
11141        let fs = FakeFs::new(cx.executor());
11142        fs.insert_tree("/root", json!({ "one": "" })).await;
11143
11144        let project = Project::test(fs, ["root".as_ref()], cx).await;
11145        let (workspace, cx) =
11146            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11147
11148        // When there are dirty untitled items, but they can serialize, then there is no prompt.
11149        let item1 = cx.new(|cx| {
11150            TestItem::new(cx)
11151                .with_dirty(true)
11152                .with_serialize(|| Some(Task::ready(Ok(()))))
11153        });
11154        let item2 = cx.new(|cx| {
11155            TestItem::new(cx)
11156                .with_dirty(true)
11157                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11158                .with_serialize(|| Some(Task::ready(Ok(()))))
11159        });
11160        workspace.update_in(cx, |w, window, cx| {
11161            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
11162            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
11163        });
11164        let task = workspace.update_in(cx, |w, window, cx| {
11165            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
11166        });
11167        assert!(task.await.unwrap());
11168    }
11169
11170    #[gpui::test]
11171    async fn test_close_pane_items(cx: &mut TestAppContext) {
11172        init_test(cx);
11173
11174        let fs = FakeFs::new(cx.executor());
11175
11176        let project = Project::test(fs, None, cx).await;
11177        let (workspace, cx) =
11178            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11179
11180        let item1 = cx.new(|cx| {
11181            TestItem::new(cx)
11182                .with_dirty(true)
11183                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11184        });
11185        let item2 = cx.new(|cx| {
11186            TestItem::new(cx)
11187                .with_dirty(true)
11188                .with_conflict(true)
11189                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11190        });
11191        let item3 = cx.new(|cx| {
11192            TestItem::new(cx)
11193                .with_dirty(true)
11194                .with_conflict(true)
11195                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
11196        });
11197        let item4 = cx.new(|cx| {
11198            TestItem::new(cx).with_dirty(true).with_project_items(&[{
11199                let project_item = TestProjectItem::new_untitled(cx);
11200                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11201                project_item
11202            }])
11203        });
11204        let pane = workspace.update_in(cx, |workspace, window, cx| {
11205            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
11206            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
11207            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
11208            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
11209            workspace.active_pane().clone()
11210        });
11211
11212        let close_items = pane.update_in(cx, |pane, window, cx| {
11213            pane.activate_item(1, true, true, window, cx);
11214            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
11215            let item1_id = item1.item_id();
11216            let item3_id = item3.item_id();
11217            let item4_id = item4.item_id();
11218            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
11219                [item1_id, item3_id, item4_id].contains(&id)
11220            })
11221        });
11222        cx.executor().run_until_parked();
11223
11224        assert!(cx.has_pending_prompt());
11225        cx.simulate_prompt_answer("Save all");
11226
11227        cx.executor().run_until_parked();
11228
11229        // Item 1 is saved. There's a prompt to save item 3.
11230        pane.update(cx, |pane, cx| {
11231            assert_eq!(item1.read(cx).save_count, 1);
11232            assert_eq!(item1.read(cx).save_as_count, 0);
11233            assert_eq!(item1.read(cx).reload_count, 0);
11234            assert_eq!(pane.items_len(), 3);
11235            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
11236        });
11237        assert!(cx.has_pending_prompt());
11238
11239        // Cancel saving item 3.
11240        cx.simulate_prompt_answer("Discard");
11241        cx.executor().run_until_parked();
11242
11243        // Item 3 is reloaded. There's a prompt to save item 4.
11244        pane.update(cx, |pane, cx| {
11245            assert_eq!(item3.read(cx).save_count, 0);
11246            assert_eq!(item3.read(cx).save_as_count, 0);
11247            assert_eq!(item3.read(cx).reload_count, 1);
11248            assert_eq!(pane.items_len(), 2);
11249            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
11250        });
11251
11252        // There's a prompt for a path for item 4.
11253        cx.simulate_new_path_selection(|_| Some(Default::default()));
11254        close_items.await.unwrap();
11255
11256        // The requested items are closed.
11257        pane.update(cx, |pane, cx| {
11258            assert_eq!(item4.read(cx).save_count, 0);
11259            assert_eq!(item4.read(cx).save_as_count, 1);
11260            assert_eq!(item4.read(cx).reload_count, 0);
11261            assert_eq!(pane.items_len(), 1);
11262            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
11263        });
11264    }
11265
11266    #[gpui::test]
11267    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
11268        init_test(cx);
11269
11270        let fs = FakeFs::new(cx.executor());
11271        let project = Project::test(fs, [], cx).await;
11272        let (workspace, cx) =
11273            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11274
11275        // Create several workspace items with single project entries, and two
11276        // workspace items with multiple project entries.
11277        let single_entry_items = (0..=4)
11278            .map(|project_entry_id| {
11279                cx.new(|cx| {
11280                    TestItem::new(cx)
11281                        .with_dirty(true)
11282                        .with_project_items(&[dirty_project_item(
11283                            project_entry_id,
11284                            &format!("{project_entry_id}.txt"),
11285                            cx,
11286                        )])
11287                })
11288            })
11289            .collect::<Vec<_>>();
11290        let item_2_3 = cx.new(|cx| {
11291            TestItem::new(cx)
11292                .with_dirty(true)
11293                .with_buffer_kind(ItemBufferKind::Multibuffer)
11294                .with_project_items(&[
11295                    single_entry_items[2].read(cx).project_items[0].clone(),
11296                    single_entry_items[3].read(cx).project_items[0].clone(),
11297                ])
11298        });
11299        let item_3_4 = cx.new(|cx| {
11300            TestItem::new(cx)
11301                .with_dirty(true)
11302                .with_buffer_kind(ItemBufferKind::Multibuffer)
11303                .with_project_items(&[
11304                    single_entry_items[3].read(cx).project_items[0].clone(),
11305                    single_entry_items[4].read(cx).project_items[0].clone(),
11306                ])
11307        });
11308
11309        // Create two panes that contain the following project entries:
11310        //   left pane:
11311        //     multi-entry items:   (2, 3)
11312        //     single-entry items:  0, 2, 3, 4
11313        //   right pane:
11314        //     single-entry items:  4, 1
11315        //     multi-entry items:   (3, 4)
11316        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
11317            let left_pane = workspace.active_pane().clone();
11318            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
11319            workspace.add_item_to_active_pane(
11320                single_entry_items[0].boxed_clone(),
11321                None,
11322                true,
11323                window,
11324                cx,
11325            );
11326            workspace.add_item_to_active_pane(
11327                single_entry_items[2].boxed_clone(),
11328                None,
11329                true,
11330                window,
11331                cx,
11332            );
11333            workspace.add_item_to_active_pane(
11334                single_entry_items[3].boxed_clone(),
11335                None,
11336                true,
11337                window,
11338                cx,
11339            );
11340            workspace.add_item_to_active_pane(
11341                single_entry_items[4].boxed_clone(),
11342                None,
11343                true,
11344                window,
11345                cx,
11346            );
11347
11348            let right_pane =
11349                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11350
11351            let boxed_clone = single_entry_items[1].boxed_clone();
11352            let right_pane = window.spawn(cx, async move |cx| {
11353                right_pane.await.inspect(|right_pane| {
11354                    right_pane
11355                        .update_in(cx, |pane, window, cx| {
11356                            pane.add_item(boxed_clone, true, true, None, window, cx);
11357                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11358                        })
11359                        .unwrap();
11360                })
11361            });
11362
11363            (left_pane, right_pane)
11364        });
11365        let right_pane = right_pane.await.unwrap();
11366        cx.focus(&right_pane);
11367
11368        let close = right_pane.update_in(cx, |pane, window, cx| {
11369            pane.close_all_items(&CloseAllItems::default(), window, cx)
11370                .unwrap()
11371        });
11372        cx.executor().run_until_parked();
11373
11374        let msg = cx.pending_prompt().unwrap().0;
11375        assert!(msg.contains("1.txt"));
11376        assert!(!msg.contains("2.txt"));
11377        assert!(!msg.contains("3.txt"));
11378        assert!(!msg.contains("4.txt"));
11379
11380        // With best-effort close, cancelling item 1 keeps it open but items 4
11381        // and (3,4) still close since their entries exist in left pane.
11382        cx.simulate_prompt_answer("Cancel");
11383        close.await;
11384
11385        right_pane.read_with(cx, |pane, _| {
11386            assert_eq!(pane.items_len(), 1);
11387        });
11388
11389        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11390        left_pane
11391            .update_in(cx, |left_pane, window, cx| {
11392                left_pane.close_item_by_id(
11393                    single_entry_items[3].entity_id(),
11394                    SaveIntent::Skip,
11395                    window,
11396                    cx,
11397                )
11398            })
11399            .await
11400            .unwrap();
11401
11402        let close = left_pane.update_in(cx, |pane, window, cx| {
11403            pane.close_all_items(&CloseAllItems::default(), window, cx)
11404                .unwrap()
11405        });
11406        cx.executor().run_until_parked();
11407
11408        let details = cx.pending_prompt().unwrap().1;
11409        assert!(details.contains("0.txt"));
11410        assert!(details.contains("3.txt"));
11411        assert!(details.contains("4.txt"));
11412        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11413        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11414        // assert!(!details.contains("2.txt"));
11415
11416        cx.simulate_prompt_answer("Save all");
11417        cx.executor().run_until_parked();
11418        close.await;
11419
11420        left_pane.read_with(cx, |pane, _| {
11421            assert_eq!(pane.items_len(), 0);
11422        });
11423    }
11424
11425    #[gpui::test]
11426    async fn test_autosave(cx: &mut gpui::TestAppContext) {
11427        init_test(cx);
11428
11429        let fs = FakeFs::new(cx.executor());
11430        let project = Project::test(fs, [], cx).await;
11431        let (workspace, cx) =
11432            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11433        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11434
11435        let item = cx.new(|cx| {
11436            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11437        });
11438        let item_id = item.entity_id();
11439        workspace.update_in(cx, |workspace, window, cx| {
11440            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11441        });
11442
11443        // Autosave on window change.
11444        item.update(cx, |item, cx| {
11445            SettingsStore::update_global(cx, |settings, cx| {
11446                settings.update_user_settings(cx, |settings| {
11447                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11448                })
11449            });
11450            item.is_dirty = true;
11451        });
11452
11453        // Deactivating the window saves the file.
11454        cx.deactivate_window();
11455        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11456
11457        // Re-activating the window doesn't save the file.
11458        cx.update(|window, _| window.activate_window());
11459        cx.executor().run_until_parked();
11460        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11461
11462        // Autosave on focus change.
11463        item.update_in(cx, |item, window, cx| {
11464            cx.focus_self(window);
11465            SettingsStore::update_global(cx, |settings, cx| {
11466                settings.update_user_settings(cx, |settings| {
11467                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11468                })
11469            });
11470            item.is_dirty = true;
11471        });
11472        // Blurring the item saves the file.
11473        item.update_in(cx, |_, window, _| window.blur());
11474        cx.executor().run_until_parked();
11475        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11476
11477        // Deactivating the window still saves the file.
11478        item.update_in(cx, |item, window, cx| {
11479            cx.focus_self(window);
11480            item.is_dirty = true;
11481        });
11482        cx.deactivate_window();
11483        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11484
11485        // Autosave after delay.
11486        item.update(cx, |item, cx| {
11487            SettingsStore::update_global(cx, |settings, cx| {
11488                settings.update_user_settings(cx, |settings| {
11489                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11490                        milliseconds: 500.into(),
11491                    });
11492                })
11493            });
11494            item.is_dirty = true;
11495            cx.emit(ItemEvent::Edit);
11496        });
11497
11498        // Delay hasn't fully expired, so the file is still dirty and unsaved.
11499        cx.executor().advance_clock(Duration::from_millis(250));
11500        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11501
11502        // After delay expires, the file is saved.
11503        cx.executor().advance_clock(Duration::from_millis(250));
11504        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11505
11506        // Autosave after delay, should save earlier than delay if tab is closed
11507        item.update(cx, |item, cx| {
11508            item.is_dirty = true;
11509            cx.emit(ItemEvent::Edit);
11510        });
11511        cx.executor().advance_clock(Duration::from_millis(250));
11512        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11513
11514        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11515        pane.update_in(cx, |pane, window, cx| {
11516            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11517        })
11518        .await
11519        .unwrap();
11520        assert!(!cx.has_pending_prompt());
11521        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11522
11523        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11524        workspace.update_in(cx, |workspace, window, cx| {
11525            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11526        });
11527        item.update_in(cx, |item, _window, cx| {
11528            item.is_dirty = true;
11529            for project_item in &mut item.project_items {
11530                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11531            }
11532        });
11533        cx.run_until_parked();
11534        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11535
11536        // Autosave on focus change, ensuring closing the tab counts as such.
11537        item.update(cx, |item, cx| {
11538            SettingsStore::update_global(cx, |settings, cx| {
11539                settings.update_user_settings(cx, |settings| {
11540                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11541                })
11542            });
11543            item.is_dirty = true;
11544            for project_item in &mut item.project_items {
11545                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11546            }
11547        });
11548
11549        pane.update_in(cx, |pane, window, cx| {
11550            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11551        })
11552        .await
11553        .unwrap();
11554        assert!(!cx.has_pending_prompt());
11555        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11556
11557        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11558        workspace.update_in(cx, |workspace, window, cx| {
11559            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11560        });
11561        item.update_in(cx, |item, window, cx| {
11562            item.project_items[0].update(cx, |item, _| {
11563                item.entry_id = None;
11564            });
11565            item.is_dirty = true;
11566            window.blur();
11567        });
11568        cx.run_until_parked();
11569        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11570
11571        // Ensure autosave is prevented for deleted files also when closing the buffer.
11572        let _close_items = pane.update_in(cx, |pane, window, cx| {
11573            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11574        });
11575        cx.run_until_parked();
11576        assert!(cx.has_pending_prompt());
11577        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11578    }
11579
11580    #[gpui::test]
11581    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11582        init_test(cx);
11583
11584        let fs = FakeFs::new(cx.executor());
11585        let project = Project::test(fs, [], cx).await;
11586        let (workspace, cx) =
11587            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11588
11589        // Create a multibuffer-like item with two child focus handles,
11590        // simulating individual buffer editors within a multibuffer.
11591        let item = cx.new(|cx| {
11592            TestItem::new(cx)
11593                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11594                .with_child_focus_handles(2, cx)
11595        });
11596        workspace.update_in(cx, |workspace, window, cx| {
11597            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11598        });
11599
11600        // Set autosave to OnFocusChange and focus the first child handle,
11601        // simulating the user's cursor being inside one of the multibuffer's excerpts.
11602        item.update_in(cx, |item, window, cx| {
11603            SettingsStore::update_global(cx, |settings, cx| {
11604                settings.update_user_settings(cx, |settings| {
11605                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11606                })
11607            });
11608            item.is_dirty = true;
11609            window.focus(&item.child_focus_handles[0], cx);
11610        });
11611        cx.executor().run_until_parked();
11612        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11613
11614        // Moving focus from one child to another within the same item should
11615        // NOT trigger autosave — focus is still within the item's focus hierarchy.
11616        item.update_in(cx, |item, window, cx| {
11617            window.focus(&item.child_focus_handles[1], cx);
11618        });
11619        cx.executor().run_until_parked();
11620        item.read_with(cx, |item, _| {
11621            assert_eq!(
11622                item.save_count, 0,
11623                "Switching focus between children within the same item should not autosave"
11624            );
11625        });
11626
11627        // Blurring the item saves the file. This is the core regression scenario:
11628        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11629        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11630        // the leaf is always a child focus handle, so `on_blur` never detected
11631        // focus leaving the item.
11632        item.update_in(cx, |_, window, _| window.blur());
11633        cx.executor().run_until_parked();
11634        item.read_with(cx, |item, _| {
11635            assert_eq!(
11636                item.save_count, 1,
11637                "Blurring should trigger autosave when focus was on a child of the item"
11638            );
11639        });
11640
11641        // Deactivating the window should also trigger autosave when a child of
11642        // the multibuffer item currently owns focus.
11643        item.update_in(cx, |item, window, cx| {
11644            item.is_dirty = true;
11645            window.focus(&item.child_focus_handles[0], cx);
11646        });
11647        cx.executor().run_until_parked();
11648        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11649
11650        cx.deactivate_window();
11651        item.read_with(cx, |item, _| {
11652            assert_eq!(
11653                item.save_count, 2,
11654                "Deactivating window should trigger autosave when focus was on a child"
11655            );
11656        });
11657    }
11658
11659    #[gpui::test]
11660    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11661        init_test(cx);
11662
11663        let fs = FakeFs::new(cx.executor());
11664
11665        let project = Project::test(fs, [], cx).await;
11666        let (workspace, cx) =
11667            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11668
11669        let item = cx.new(|cx| {
11670            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11671        });
11672        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11673        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11674        let toolbar_notify_count = Rc::new(RefCell::new(0));
11675
11676        workspace.update_in(cx, |workspace, window, cx| {
11677            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11678            let toolbar_notification_count = toolbar_notify_count.clone();
11679            cx.observe_in(&toolbar, window, move |_, _, _, _| {
11680                *toolbar_notification_count.borrow_mut() += 1
11681            })
11682            .detach();
11683        });
11684
11685        pane.read_with(cx, |pane, _| {
11686            assert!(!pane.can_navigate_backward());
11687            assert!(!pane.can_navigate_forward());
11688        });
11689
11690        item.update_in(cx, |item, _, cx| {
11691            item.set_state("one".to_string(), cx);
11692        });
11693
11694        // Toolbar must be notified to re-render the navigation buttons
11695        assert_eq!(*toolbar_notify_count.borrow(), 1);
11696
11697        pane.read_with(cx, |pane, _| {
11698            assert!(pane.can_navigate_backward());
11699            assert!(!pane.can_navigate_forward());
11700        });
11701
11702        workspace
11703            .update_in(cx, |workspace, window, cx| {
11704                workspace.go_back(pane.downgrade(), window, cx)
11705            })
11706            .await
11707            .unwrap();
11708
11709        assert_eq!(*toolbar_notify_count.borrow(), 2);
11710        pane.read_with(cx, |pane, _| {
11711            assert!(!pane.can_navigate_backward());
11712            assert!(pane.can_navigate_forward());
11713        });
11714    }
11715
11716    /// Tests that the navigation history deduplicates entries for the same item.
11717    ///
11718    /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11719    /// the navigation history deduplicates by keeping only the most recent visit to each item,
11720    /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11721    /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11722    /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11723    ///
11724    /// This behavior prevents the navigation history from growing unnecessarily large and provides
11725    /// a better user experience by eliminating redundant navigation steps when jumping between files.
11726    #[gpui::test]
11727    async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11728        init_test(cx);
11729
11730        let fs = FakeFs::new(cx.executor());
11731        let project = Project::test(fs, [], cx).await;
11732        let (workspace, cx) =
11733            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11734
11735        let item_a = cx.new(|cx| {
11736            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11737        });
11738        let item_b = cx.new(|cx| {
11739            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11740        });
11741        let item_c = cx.new(|cx| {
11742            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11743        });
11744
11745        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11746
11747        workspace.update_in(cx, |workspace, window, cx| {
11748            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11749            workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11750            workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11751        });
11752
11753        workspace.update_in(cx, |workspace, window, cx| {
11754            workspace.activate_item(&item_a, false, false, window, cx);
11755        });
11756        cx.run_until_parked();
11757
11758        workspace.update_in(cx, |workspace, window, cx| {
11759            workspace.activate_item(&item_b, false, false, window, cx);
11760        });
11761        cx.run_until_parked();
11762
11763        workspace.update_in(cx, |workspace, window, cx| {
11764            workspace.activate_item(&item_a, false, false, window, cx);
11765        });
11766        cx.run_until_parked();
11767
11768        workspace.update_in(cx, |workspace, window, cx| {
11769            workspace.activate_item(&item_b, false, false, window, cx);
11770        });
11771        cx.run_until_parked();
11772
11773        workspace.update_in(cx, |workspace, window, cx| {
11774            workspace.activate_item(&item_a, false, false, window, cx);
11775        });
11776        cx.run_until_parked();
11777
11778        workspace.update_in(cx, |workspace, window, cx| {
11779            workspace.activate_item(&item_b, false, false, window, cx);
11780        });
11781        cx.run_until_parked();
11782
11783        workspace.update_in(cx, |workspace, window, cx| {
11784            workspace.activate_item(&item_c, false, false, window, cx);
11785        });
11786        cx.run_until_parked();
11787
11788        let backward_count = pane.read_with(cx, |pane, cx| {
11789            let mut count = 0;
11790            pane.nav_history().for_each_entry(cx, &mut |_, _| {
11791                count += 1;
11792            });
11793            count
11794        });
11795        assert!(
11796            backward_count <= 4,
11797            "Should have at most 4 entries, got {}",
11798            backward_count
11799        );
11800
11801        workspace
11802            .update_in(cx, |workspace, window, cx| {
11803                workspace.go_back(pane.downgrade(), window, cx)
11804            })
11805            .await
11806            .unwrap();
11807
11808        let active_item = workspace.read_with(cx, |workspace, cx| {
11809            workspace.active_item(cx).unwrap().item_id()
11810        });
11811        assert_eq!(
11812            active_item,
11813            item_b.entity_id(),
11814            "After first go_back, should be at item B"
11815        );
11816
11817        workspace
11818            .update_in(cx, |workspace, window, cx| {
11819                workspace.go_back(pane.downgrade(), window, cx)
11820            })
11821            .await
11822            .unwrap();
11823
11824        let active_item = workspace.read_with(cx, |workspace, cx| {
11825            workspace.active_item(cx).unwrap().item_id()
11826        });
11827        assert_eq!(
11828            active_item,
11829            item_a.entity_id(),
11830            "After second go_back, should be at item A"
11831        );
11832
11833        pane.read_with(cx, |pane, _| {
11834            assert!(pane.can_navigate_forward(), "Should be able to go forward");
11835        });
11836    }
11837
11838    #[gpui::test]
11839    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11840        init_test(cx);
11841        let fs = FakeFs::new(cx.executor());
11842        let project = Project::test(fs, [], cx).await;
11843        let (multi_workspace, cx) =
11844            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11845        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11846
11847        workspace.update_in(cx, |workspace, window, cx| {
11848            let first_item = cx.new(|cx| {
11849                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11850            });
11851            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11852            workspace.split_pane(
11853                workspace.active_pane().clone(),
11854                SplitDirection::Right,
11855                window,
11856                cx,
11857            );
11858            workspace.split_pane(
11859                workspace.active_pane().clone(),
11860                SplitDirection::Right,
11861                window,
11862                cx,
11863            );
11864        });
11865
11866        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11867            let panes = workspace.center.panes();
11868            assert!(panes.len() >= 2);
11869            (
11870                panes.first().expect("at least one pane").entity_id(),
11871                panes.last().expect("at least one pane").entity_id(),
11872            )
11873        });
11874
11875        workspace.update_in(cx, |workspace, window, cx| {
11876            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11877        });
11878        workspace.update(cx, |workspace, _| {
11879            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11880            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11881        });
11882
11883        cx.dispatch_action(ActivateLastPane);
11884
11885        workspace.update(cx, |workspace, _| {
11886            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11887        });
11888    }
11889
11890    #[gpui::test]
11891    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11892        init_test(cx);
11893        let fs = FakeFs::new(cx.executor());
11894
11895        let project = Project::test(fs, [], cx).await;
11896        let (workspace, cx) =
11897            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11898
11899        let panel = workspace.update_in(cx, |workspace, window, cx| {
11900            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11901            workspace.add_panel(panel.clone(), window, cx);
11902
11903            workspace
11904                .right_dock()
11905                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11906
11907            panel
11908        });
11909
11910        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11911        pane.update_in(cx, |pane, window, cx| {
11912            let item = cx.new(TestItem::new);
11913            pane.add_item(Box::new(item), true, true, None, window, cx);
11914        });
11915
11916        // Transfer focus from center to panel
11917        workspace.update_in(cx, |workspace, window, cx| {
11918            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11919        });
11920
11921        workspace.update_in(cx, |workspace, window, cx| {
11922            assert!(workspace.right_dock().read(cx).is_open());
11923            assert!(!panel.is_zoomed(window, cx));
11924            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11925        });
11926
11927        // Transfer focus from panel to center
11928        workspace.update_in(cx, |workspace, window, cx| {
11929            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11930        });
11931
11932        workspace.update_in(cx, |workspace, window, cx| {
11933            assert!(workspace.right_dock().read(cx).is_open());
11934            assert!(!panel.is_zoomed(window, cx));
11935            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11936            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11937        });
11938
11939        // Close the dock
11940        workspace.update_in(cx, |workspace, window, cx| {
11941            workspace.toggle_dock(DockPosition::Right, window, cx);
11942        });
11943
11944        workspace.update_in(cx, |workspace, window, cx| {
11945            assert!(!workspace.right_dock().read(cx).is_open());
11946            assert!(!panel.is_zoomed(window, cx));
11947            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11948            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11949        });
11950
11951        // Open the dock
11952        workspace.update_in(cx, |workspace, window, cx| {
11953            workspace.toggle_dock(DockPosition::Right, window, cx);
11954        });
11955
11956        workspace.update_in(cx, |workspace, window, cx| {
11957            assert!(workspace.right_dock().read(cx).is_open());
11958            assert!(!panel.is_zoomed(window, cx));
11959            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11960        });
11961
11962        // Focus and zoom panel
11963        panel.update_in(cx, |panel, window, cx| {
11964            cx.focus_self(window);
11965            panel.set_zoomed(true, window, cx)
11966        });
11967
11968        workspace.update_in(cx, |workspace, window, cx| {
11969            assert!(workspace.right_dock().read(cx).is_open());
11970            assert!(panel.is_zoomed(window, cx));
11971            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11972        });
11973
11974        // Transfer focus to the center closes the dock
11975        workspace.update_in(cx, |workspace, window, cx| {
11976            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11977        });
11978
11979        workspace.update_in(cx, |workspace, window, cx| {
11980            assert!(!workspace.right_dock().read(cx).is_open());
11981            assert!(panel.is_zoomed(window, cx));
11982            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11983        });
11984
11985        // Transferring focus back to the panel keeps it zoomed
11986        workspace.update_in(cx, |workspace, window, cx| {
11987            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11988        });
11989
11990        workspace.update_in(cx, |workspace, window, cx| {
11991            assert!(workspace.right_dock().read(cx).is_open());
11992            assert!(panel.is_zoomed(window, cx));
11993            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11994        });
11995
11996        // Close the dock while it is zoomed
11997        workspace.update_in(cx, |workspace, window, cx| {
11998            workspace.toggle_dock(DockPosition::Right, window, cx)
11999        });
12000
12001        workspace.update_in(cx, |workspace, window, cx| {
12002            assert!(!workspace.right_dock().read(cx).is_open());
12003            assert!(panel.is_zoomed(window, cx));
12004            assert!(workspace.zoomed.is_none());
12005            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12006        });
12007
12008        // Opening the dock, when it's zoomed, retains focus
12009        workspace.update_in(cx, |workspace, window, cx| {
12010            workspace.toggle_dock(DockPosition::Right, window, cx)
12011        });
12012
12013        workspace.update_in(cx, |workspace, window, cx| {
12014            assert!(workspace.right_dock().read(cx).is_open());
12015            assert!(panel.is_zoomed(window, cx));
12016            assert!(workspace.zoomed.is_some());
12017            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12018        });
12019
12020        // Unzoom and close the panel, zoom the active pane.
12021        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
12022        workspace.update_in(cx, |workspace, window, cx| {
12023            workspace.toggle_dock(DockPosition::Right, window, cx)
12024        });
12025        pane.update_in(cx, |pane, window, cx| {
12026            pane.toggle_zoom(&Default::default(), window, cx)
12027        });
12028
12029        // Opening a dock unzooms the pane.
12030        workspace.update_in(cx, |workspace, window, cx| {
12031            workspace.toggle_dock(DockPosition::Right, window, cx)
12032        });
12033        workspace.update_in(cx, |workspace, window, cx| {
12034            let pane = pane.read(cx);
12035            assert!(!pane.is_zoomed());
12036            assert!(!pane.focus_handle(cx).is_focused(window));
12037            assert!(workspace.right_dock().read(cx).is_open());
12038            assert!(workspace.zoomed.is_none());
12039        });
12040    }
12041
12042    #[gpui::test]
12043    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
12044        init_test(cx);
12045        let fs = FakeFs::new(cx.executor());
12046
12047        let project = Project::test(fs, [], cx).await;
12048        let (workspace, cx) =
12049            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12050
12051        let panel = workspace.update_in(cx, |workspace, window, cx| {
12052            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12053            workspace.add_panel(panel.clone(), window, cx);
12054            panel
12055        });
12056
12057        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12058        pane.update_in(cx, |pane, window, cx| {
12059            let item = cx.new(TestItem::new);
12060            pane.add_item(Box::new(item), true, true, None, window, cx);
12061        });
12062
12063        // Enable close_panel_on_toggle
12064        cx.update_global(|store: &mut SettingsStore, cx| {
12065            store.update_user_settings(cx, |settings| {
12066                settings.workspace.close_panel_on_toggle = Some(true);
12067            });
12068        });
12069
12070        // Panel starts closed. Toggling should open and focus it.
12071        workspace.update_in(cx, |workspace, window, cx| {
12072            assert!(!workspace.right_dock().read(cx).is_open());
12073            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12074        });
12075
12076        workspace.update_in(cx, |workspace, window, cx| {
12077            assert!(
12078                workspace.right_dock().read(cx).is_open(),
12079                "Dock should be open after toggling from center"
12080            );
12081            assert!(
12082                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12083                "Panel should be focused after toggling from center"
12084            );
12085        });
12086
12087        // Panel is open and focused. Toggling should close the panel and
12088        // return focus to the center.
12089        workspace.update_in(cx, |workspace, window, cx| {
12090            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12091        });
12092
12093        workspace.update_in(cx, |workspace, window, cx| {
12094            assert!(
12095                !workspace.right_dock().read(cx).is_open(),
12096                "Dock should be closed after toggling from focused panel"
12097            );
12098            assert!(
12099                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12100                "Panel should not be focused after toggling from focused panel"
12101            );
12102        });
12103
12104        // Open the dock and focus something else so the panel is open but not
12105        // focused. Toggling should focus the panel (not close it).
12106        workspace.update_in(cx, |workspace, window, cx| {
12107            workspace
12108                .right_dock()
12109                .update(cx, |dock, cx| dock.set_open(true, window, cx));
12110            window.focus(&pane.read(cx).focus_handle(cx), cx);
12111        });
12112
12113        workspace.update_in(cx, |workspace, window, cx| {
12114            assert!(workspace.right_dock().read(cx).is_open());
12115            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12116            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12117        });
12118
12119        workspace.update_in(cx, |workspace, window, cx| {
12120            assert!(
12121                workspace.right_dock().read(cx).is_open(),
12122                "Dock should remain open when toggling focuses an open-but-unfocused panel"
12123            );
12124            assert!(
12125                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12126                "Panel should be focused after toggling an open-but-unfocused panel"
12127            );
12128        });
12129
12130        // Now disable the setting and verify the original behavior: toggling
12131        // from a focused panel moves focus to center but leaves the dock open.
12132        cx.update_global(|store: &mut SettingsStore, cx| {
12133            store.update_user_settings(cx, |settings| {
12134                settings.workspace.close_panel_on_toggle = Some(false);
12135            });
12136        });
12137
12138        workspace.update_in(cx, |workspace, window, cx| {
12139            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12140        });
12141
12142        workspace.update_in(cx, |workspace, window, cx| {
12143            assert!(
12144                workspace.right_dock().read(cx).is_open(),
12145                "Dock should remain open when setting is disabled"
12146            );
12147            assert!(
12148                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12149                "Panel should not be focused after toggling with setting disabled"
12150            );
12151        });
12152    }
12153
12154    #[gpui::test]
12155    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
12156        init_test(cx);
12157        let fs = FakeFs::new(cx.executor());
12158
12159        let project = Project::test(fs, [], cx).await;
12160        let (workspace, cx) =
12161            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12162
12163        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
12164            workspace.active_pane().clone()
12165        });
12166
12167        // Add an item to the pane so it can be zoomed
12168        workspace.update_in(cx, |workspace, window, cx| {
12169            let item = cx.new(TestItem::new);
12170            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
12171        });
12172
12173        // Initially not zoomed
12174        workspace.update_in(cx, |workspace, _window, cx| {
12175            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
12176            assert!(
12177                workspace.zoomed.is_none(),
12178                "Workspace should track no zoomed pane"
12179            );
12180            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
12181        });
12182
12183        // Zoom In
12184        pane.update_in(cx, |pane, window, cx| {
12185            pane.zoom_in(&crate::ZoomIn, window, cx);
12186        });
12187
12188        workspace.update_in(cx, |workspace, window, cx| {
12189            assert!(
12190                pane.read(cx).is_zoomed(),
12191                "Pane should be zoomed after ZoomIn"
12192            );
12193            assert!(
12194                workspace.zoomed.is_some(),
12195                "Workspace should track the zoomed pane"
12196            );
12197            assert!(
12198                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
12199                "ZoomIn should focus the pane"
12200            );
12201        });
12202
12203        // Zoom In again is a no-op
12204        pane.update_in(cx, |pane, window, cx| {
12205            pane.zoom_in(&crate::ZoomIn, window, cx);
12206        });
12207
12208        workspace.update_in(cx, |workspace, window, cx| {
12209            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
12210            assert!(
12211                workspace.zoomed.is_some(),
12212                "Workspace still tracks zoomed pane"
12213            );
12214            assert!(
12215                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
12216                "Pane remains focused after repeated ZoomIn"
12217            );
12218        });
12219
12220        // Zoom Out
12221        pane.update_in(cx, |pane, window, cx| {
12222            pane.zoom_out(&crate::ZoomOut, window, cx);
12223        });
12224
12225        workspace.update_in(cx, |workspace, _window, cx| {
12226            assert!(
12227                !pane.read(cx).is_zoomed(),
12228                "Pane should unzoom after ZoomOut"
12229            );
12230            assert!(
12231                workspace.zoomed.is_none(),
12232                "Workspace clears zoom tracking after ZoomOut"
12233            );
12234        });
12235
12236        // Zoom Out again is a no-op
12237        pane.update_in(cx, |pane, window, cx| {
12238            pane.zoom_out(&crate::ZoomOut, window, cx);
12239        });
12240
12241        workspace.update_in(cx, |workspace, _window, cx| {
12242            assert!(
12243                !pane.read(cx).is_zoomed(),
12244                "Second ZoomOut keeps pane unzoomed"
12245            );
12246            assert!(
12247                workspace.zoomed.is_none(),
12248                "Workspace remains without zoomed pane"
12249            );
12250        });
12251    }
12252
12253    #[gpui::test]
12254    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
12255        init_test(cx);
12256        let fs = FakeFs::new(cx.executor());
12257
12258        let project = Project::test(fs, [], cx).await;
12259        let (workspace, cx) =
12260            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12261        workspace.update_in(cx, |workspace, window, cx| {
12262            // Open two docks
12263            let left_dock = workspace.dock_at_position(DockPosition::Left);
12264            let right_dock = workspace.dock_at_position(DockPosition::Right);
12265
12266            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12267            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12268
12269            assert!(left_dock.read(cx).is_open());
12270            assert!(right_dock.read(cx).is_open());
12271        });
12272
12273        workspace.update_in(cx, |workspace, window, cx| {
12274            // Toggle all docks - should close both
12275            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12276
12277            let left_dock = workspace.dock_at_position(DockPosition::Left);
12278            let right_dock = workspace.dock_at_position(DockPosition::Right);
12279            assert!(!left_dock.read(cx).is_open());
12280            assert!(!right_dock.read(cx).is_open());
12281        });
12282
12283        workspace.update_in(cx, |workspace, window, cx| {
12284            // Toggle again - should reopen both
12285            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12286
12287            let left_dock = workspace.dock_at_position(DockPosition::Left);
12288            let right_dock = workspace.dock_at_position(DockPosition::Right);
12289            assert!(left_dock.read(cx).is_open());
12290            assert!(right_dock.read(cx).is_open());
12291        });
12292    }
12293
12294    #[gpui::test]
12295    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
12296        init_test(cx);
12297        let fs = FakeFs::new(cx.executor());
12298
12299        let project = Project::test(fs, [], cx).await;
12300        let (workspace, cx) =
12301            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12302        workspace.update_in(cx, |workspace, window, cx| {
12303            // Open two docks
12304            let left_dock = workspace.dock_at_position(DockPosition::Left);
12305            let right_dock = workspace.dock_at_position(DockPosition::Right);
12306
12307            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12308            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12309
12310            assert!(left_dock.read(cx).is_open());
12311            assert!(right_dock.read(cx).is_open());
12312        });
12313
12314        workspace.update_in(cx, |workspace, window, cx| {
12315            // Close them manually
12316            workspace.toggle_dock(DockPosition::Left, window, cx);
12317            workspace.toggle_dock(DockPosition::Right, window, cx);
12318
12319            let left_dock = workspace.dock_at_position(DockPosition::Left);
12320            let right_dock = workspace.dock_at_position(DockPosition::Right);
12321            assert!(!left_dock.read(cx).is_open());
12322            assert!(!right_dock.read(cx).is_open());
12323        });
12324
12325        workspace.update_in(cx, |workspace, window, cx| {
12326            // Toggle all docks - only last closed (right dock) should reopen
12327            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12328
12329            let left_dock = workspace.dock_at_position(DockPosition::Left);
12330            let right_dock = workspace.dock_at_position(DockPosition::Right);
12331            assert!(!left_dock.read(cx).is_open());
12332            assert!(right_dock.read(cx).is_open());
12333        });
12334    }
12335
12336    #[gpui::test]
12337    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
12338        init_test(cx);
12339        let fs = FakeFs::new(cx.executor());
12340        let project = Project::test(fs, [], cx).await;
12341        let (multi_workspace, cx) =
12342            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12343        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12344
12345        // Open two docks (left and right) with one panel each
12346        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12347            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12348            workspace.add_panel(left_panel.clone(), window, cx);
12349
12350            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12351            workspace.add_panel(right_panel.clone(), window, cx);
12352
12353            workspace.toggle_dock(DockPosition::Left, window, cx);
12354            workspace.toggle_dock(DockPosition::Right, window, cx);
12355
12356            // Verify initial state
12357            assert!(
12358                workspace.left_dock().read(cx).is_open(),
12359                "Left dock should be open"
12360            );
12361            assert_eq!(
12362                workspace
12363                    .left_dock()
12364                    .read(cx)
12365                    .visible_panel()
12366                    .unwrap()
12367                    .panel_id(),
12368                left_panel.panel_id(),
12369                "Left panel should be visible in left dock"
12370            );
12371            assert!(
12372                workspace.right_dock().read(cx).is_open(),
12373                "Right dock should be open"
12374            );
12375            assert_eq!(
12376                workspace
12377                    .right_dock()
12378                    .read(cx)
12379                    .visible_panel()
12380                    .unwrap()
12381                    .panel_id(),
12382                right_panel.panel_id(),
12383                "Right panel should be visible in right dock"
12384            );
12385            assert!(
12386                !workspace.bottom_dock().read(cx).is_open(),
12387                "Bottom dock should be closed"
12388            );
12389
12390            (left_panel, right_panel)
12391        });
12392
12393        // Focus the left panel and move it to the next position (bottom dock)
12394        workspace.update_in(cx, |workspace, window, cx| {
12395            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12396            assert!(
12397                left_panel.read(cx).focus_handle(cx).is_focused(window),
12398                "Left panel should be focused"
12399            );
12400        });
12401
12402        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12403
12404        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12405        workspace.update(cx, |workspace, cx| {
12406            assert!(
12407                !workspace.left_dock().read(cx).is_open(),
12408                "Left dock should be closed"
12409            );
12410            assert!(
12411                workspace.bottom_dock().read(cx).is_open(),
12412                "Bottom dock should now be open"
12413            );
12414            assert_eq!(
12415                left_panel.read(cx).position,
12416                DockPosition::Bottom,
12417                "Left panel should now be in the bottom dock"
12418            );
12419            assert_eq!(
12420                workspace
12421                    .bottom_dock()
12422                    .read(cx)
12423                    .visible_panel()
12424                    .unwrap()
12425                    .panel_id(),
12426                left_panel.panel_id(),
12427                "Left panel should be the visible panel in the bottom dock"
12428            );
12429        });
12430
12431        // Toggle all docks off
12432        workspace.update_in(cx, |workspace, window, cx| {
12433            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12434            assert!(
12435                !workspace.left_dock().read(cx).is_open(),
12436                "Left dock should be closed"
12437            );
12438            assert!(
12439                !workspace.right_dock().read(cx).is_open(),
12440                "Right dock should be closed"
12441            );
12442            assert!(
12443                !workspace.bottom_dock().read(cx).is_open(),
12444                "Bottom dock should be closed"
12445            );
12446        });
12447
12448        // Toggle all docks back on and verify positions are restored
12449        workspace.update_in(cx, |workspace, window, cx| {
12450            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12451            assert!(
12452                !workspace.left_dock().read(cx).is_open(),
12453                "Left dock should remain closed"
12454            );
12455            assert!(
12456                workspace.right_dock().read(cx).is_open(),
12457                "Right dock should remain open"
12458            );
12459            assert!(
12460                workspace.bottom_dock().read(cx).is_open(),
12461                "Bottom dock should remain open"
12462            );
12463            assert_eq!(
12464                left_panel.read(cx).position,
12465                DockPosition::Bottom,
12466                "Left panel should remain in the bottom dock"
12467            );
12468            assert_eq!(
12469                right_panel.read(cx).position,
12470                DockPosition::Right,
12471                "Right panel should remain in the right dock"
12472            );
12473            assert_eq!(
12474                workspace
12475                    .bottom_dock()
12476                    .read(cx)
12477                    .visible_panel()
12478                    .unwrap()
12479                    .panel_id(),
12480                left_panel.panel_id(),
12481                "Left panel should be the visible panel in the right dock"
12482            );
12483        });
12484    }
12485
12486    #[gpui::test]
12487    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12488        init_test(cx);
12489
12490        let fs = FakeFs::new(cx.executor());
12491
12492        let project = Project::test(fs, None, cx).await;
12493        let (workspace, cx) =
12494            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12495
12496        // Let's arrange the panes like this:
12497        //
12498        // +-----------------------+
12499        // |         top           |
12500        // +------+--------+-------+
12501        // | left | center | right |
12502        // +------+--------+-------+
12503        // |        bottom         |
12504        // +-----------------------+
12505
12506        let top_item = cx.new(|cx| {
12507            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12508        });
12509        let bottom_item = cx.new(|cx| {
12510            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12511        });
12512        let left_item = cx.new(|cx| {
12513            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12514        });
12515        let right_item = cx.new(|cx| {
12516            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12517        });
12518        let center_item = cx.new(|cx| {
12519            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12520        });
12521
12522        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12523            let top_pane_id = workspace.active_pane().entity_id();
12524            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12525            workspace.split_pane(
12526                workspace.active_pane().clone(),
12527                SplitDirection::Down,
12528                window,
12529                cx,
12530            );
12531            top_pane_id
12532        });
12533        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12534            let bottom_pane_id = workspace.active_pane().entity_id();
12535            workspace.add_item_to_active_pane(
12536                Box::new(bottom_item.clone()),
12537                None,
12538                false,
12539                window,
12540                cx,
12541            );
12542            workspace.split_pane(
12543                workspace.active_pane().clone(),
12544                SplitDirection::Up,
12545                window,
12546                cx,
12547            );
12548            bottom_pane_id
12549        });
12550        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12551            let left_pane_id = workspace.active_pane().entity_id();
12552            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12553            workspace.split_pane(
12554                workspace.active_pane().clone(),
12555                SplitDirection::Right,
12556                window,
12557                cx,
12558            );
12559            left_pane_id
12560        });
12561        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12562            let right_pane_id = workspace.active_pane().entity_id();
12563            workspace.add_item_to_active_pane(
12564                Box::new(right_item.clone()),
12565                None,
12566                false,
12567                window,
12568                cx,
12569            );
12570            workspace.split_pane(
12571                workspace.active_pane().clone(),
12572                SplitDirection::Left,
12573                window,
12574                cx,
12575            );
12576            right_pane_id
12577        });
12578        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12579            let center_pane_id = workspace.active_pane().entity_id();
12580            workspace.add_item_to_active_pane(
12581                Box::new(center_item.clone()),
12582                None,
12583                false,
12584                window,
12585                cx,
12586            );
12587            center_pane_id
12588        });
12589        cx.executor().run_until_parked();
12590
12591        workspace.update_in(cx, |workspace, window, cx| {
12592            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12593
12594            // Join into next from center pane into right
12595            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12596        });
12597
12598        workspace.update_in(cx, |workspace, window, cx| {
12599            let active_pane = workspace.active_pane();
12600            assert_eq!(right_pane_id, active_pane.entity_id());
12601            assert_eq!(2, active_pane.read(cx).items_len());
12602            let item_ids_in_pane =
12603                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12604            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12605            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12606
12607            // Join into next from right pane into bottom
12608            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12609        });
12610
12611        workspace.update_in(cx, |workspace, window, cx| {
12612            let active_pane = workspace.active_pane();
12613            assert_eq!(bottom_pane_id, active_pane.entity_id());
12614            assert_eq!(3, active_pane.read(cx).items_len());
12615            let item_ids_in_pane =
12616                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12617            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12618            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12619            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12620
12621            // Join into next from bottom pane into left
12622            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12623        });
12624
12625        workspace.update_in(cx, |workspace, window, cx| {
12626            let active_pane = workspace.active_pane();
12627            assert_eq!(left_pane_id, active_pane.entity_id());
12628            assert_eq!(4, active_pane.read(cx).items_len());
12629            let item_ids_in_pane =
12630                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12631            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12632            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12633            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12634            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12635
12636            // Join into next from left pane into top
12637            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12638        });
12639
12640        workspace.update_in(cx, |workspace, window, cx| {
12641            let active_pane = workspace.active_pane();
12642            assert_eq!(top_pane_id, active_pane.entity_id());
12643            assert_eq!(5, active_pane.read(cx).items_len());
12644            let item_ids_in_pane =
12645                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12646            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12647            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12648            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12649            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12650            assert!(item_ids_in_pane.contains(&top_item.item_id()));
12651
12652            // Single pane left: no-op
12653            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12654        });
12655
12656        workspace.update(cx, |workspace, _cx| {
12657            let active_pane = workspace.active_pane();
12658            assert_eq!(top_pane_id, active_pane.entity_id());
12659        });
12660    }
12661
12662    fn add_an_item_to_active_pane(
12663        cx: &mut VisualTestContext,
12664        workspace: &Entity<Workspace>,
12665        item_id: u64,
12666    ) -> Entity<TestItem> {
12667        let item = cx.new(|cx| {
12668            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12669                item_id,
12670                "item{item_id}.txt",
12671                cx,
12672            )])
12673        });
12674        workspace.update_in(cx, |workspace, window, cx| {
12675            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12676        });
12677        item
12678    }
12679
12680    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12681        workspace.update_in(cx, |workspace, window, cx| {
12682            workspace.split_pane(
12683                workspace.active_pane().clone(),
12684                SplitDirection::Right,
12685                window,
12686                cx,
12687            )
12688        })
12689    }
12690
12691    #[gpui::test]
12692    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12693        init_test(cx);
12694        let fs = FakeFs::new(cx.executor());
12695        let project = Project::test(fs, None, cx).await;
12696        let (workspace, cx) =
12697            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12698
12699        add_an_item_to_active_pane(cx, &workspace, 1);
12700        split_pane(cx, &workspace);
12701        add_an_item_to_active_pane(cx, &workspace, 2);
12702        split_pane(cx, &workspace); // empty pane
12703        split_pane(cx, &workspace);
12704        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12705
12706        cx.executor().run_until_parked();
12707
12708        workspace.update(cx, |workspace, cx| {
12709            let num_panes = workspace.panes().len();
12710            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12711            let active_item = workspace
12712                .active_pane()
12713                .read(cx)
12714                .active_item()
12715                .expect("item is in focus");
12716
12717            assert_eq!(num_panes, 4);
12718            assert_eq!(num_items_in_current_pane, 1);
12719            assert_eq!(active_item.item_id(), last_item.item_id());
12720        });
12721
12722        workspace.update_in(cx, |workspace, window, cx| {
12723            workspace.join_all_panes(window, cx);
12724        });
12725
12726        workspace.update(cx, |workspace, cx| {
12727            let num_panes = workspace.panes().len();
12728            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12729            let active_item = workspace
12730                .active_pane()
12731                .read(cx)
12732                .active_item()
12733                .expect("item is in focus");
12734
12735            assert_eq!(num_panes, 1);
12736            assert_eq!(num_items_in_current_pane, 3);
12737            assert_eq!(active_item.item_id(), last_item.item_id());
12738        });
12739    }
12740
12741    #[gpui::test]
12742    async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12743        init_test(cx);
12744        let fs = FakeFs::new(cx.executor());
12745
12746        let project = Project::test(fs, [], cx).await;
12747        let (multi_workspace, cx) =
12748            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12749        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12750
12751        workspace.update(cx, |workspace, _cx| {
12752            workspace.set_random_database_id();
12753        });
12754
12755        workspace.update_in(cx, |workspace, window, cx| {
12756            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12757            workspace.add_panel(panel.clone(), window, cx);
12758            workspace.toggle_dock(DockPosition::Right, window, cx);
12759
12760            let right_dock = workspace.right_dock().clone();
12761            right_dock.update(cx, |dock, cx| {
12762                dock.set_panel_size_state(
12763                    &panel,
12764                    dock::PanelSizeState {
12765                        size: None,
12766                        flex: Some(1.0),
12767                    },
12768                    cx,
12769                );
12770            });
12771        });
12772
12773        workspace.update_in(cx, |workspace, window, cx| {
12774            let item = cx.new(|cx| {
12775                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12776            });
12777            workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12778            workspace.bounds.size.width = px(1920.);
12779
12780            let dock = workspace.right_dock().read(cx);
12781            let initial_width = workspace
12782                .dock_size(&dock, window, cx)
12783                .expect("flexible dock should have an initial width");
12784
12785            assert_eq!(initial_width, px(960.));
12786        });
12787
12788        workspace.update_in(cx, |workspace, window, cx| {
12789            workspace.split_pane(
12790                workspace.active_pane().clone(),
12791                SplitDirection::Right,
12792                window,
12793                cx,
12794            );
12795
12796            let center_column_count = workspace.center.full_height_column_count();
12797            assert_eq!(center_column_count, 2);
12798
12799            let dock = workspace.right_dock().read(cx);
12800            assert_eq!(workspace.dock_size(&dock, window, cx).unwrap(), px(640.));
12801
12802            workspace.bounds.size.width = px(2400.);
12803
12804            let dock = workspace.right_dock().read(cx);
12805            assert_eq!(workspace.dock_size(&dock, window, cx).unwrap(), px(800.));
12806        });
12807    }
12808
12809    #[gpui::test]
12810    async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12811        init_test(cx);
12812        let fs = FakeFs::new(cx.executor());
12813
12814        // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12815        {
12816            let project = Project::test(fs.clone(), [], cx).await;
12817            let (multi_workspace, cx) =
12818                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12819            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12820
12821            workspace.update(cx, |workspace, _cx| {
12822                workspace.set_random_database_id();
12823                workspace.bounds.size.width = px(800.);
12824            });
12825
12826            let panel = workspace.update_in(cx, |workspace, window, cx| {
12827                let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12828                workspace.add_panel(panel.clone(), window, cx);
12829                workspace.toggle_dock(DockPosition::Left, window, cx);
12830                panel
12831            });
12832
12833            workspace.update_in(cx, |workspace, window, cx| {
12834                workspace.resize_left_dock(px(350.), window, cx);
12835            });
12836
12837            cx.run_until_parked();
12838
12839            let persisted = workspace.read_with(cx, |workspace, cx| {
12840                workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12841            });
12842            assert_eq!(
12843                persisted.and_then(|s| s.size),
12844                Some(px(350.)),
12845                "fixed-width panel size should be persisted to KVP"
12846            );
12847
12848            // Remove the panel and re-add a fresh instance with the same key.
12849            // The new instance should have its size state restored from KVP.
12850            workspace.update_in(cx, |workspace, window, cx| {
12851                workspace.remove_panel(&panel, window, cx);
12852            });
12853
12854            workspace.update_in(cx, |workspace, window, cx| {
12855                let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12856                workspace.add_panel(new_panel, window, cx);
12857
12858                let left_dock = workspace.left_dock().read(cx);
12859                let size_state = left_dock
12860                    .panel::<TestPanel>()
12861                    .and_then(|p| left_dock.stored_panel_size_state(&p));
12862                assert_eq!(
12863                    size_state.and_then(|s| s.size),
12864                    Some(px(350.)),
12865                    "re-added fixed-width panel should restore persisted size from KVP"
12866                );
12867            });
12868        }
12869
12870        // Flexible panel: both pixel size and ratio are persisted and restored.
12871        {
12872            let project = Project::test(fs.clone(), [], cx).await;
12873            let (multi_workspace, cx) =
12874                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12875            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12876
12877            workspace.update(cx, |workspace, _cx| {
12878                workspace.set_random_database_id();
12879                workspace.bounds.size.width = px(800.);
12880            });
12881
12882            let panel = workspace.update_in(cx, |workspace, window, cx| {
12883                let item = cx.new(|cx| {
12884                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12885                });
12886                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12887
12888                let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12889                workspace.add_panel(panel.clone(), window, cx);
12890                workspace.toggle_dock(DockPosition::Right, window, cx);
12891                panel
12892            });
12893
12894            workspace.update_in(cx, |workspace, window, cx| {
12895                workspace.resize_right_dock(px(300.), window, cx);
12896            });
12897
12898            cx.run_until_parked();
12899
12900            let persisted = workspace
12901                .read_with(cx, |workspace, cx| {
12902                    workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12903                })
12904                .expect("flexible panel state should be persisted to KVP");
12905            assert_eq!(
12906                persisted.size, None,
12907                "flexible panel should not persist a redundant pixel size"
12908            );
12909            let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12910
12911            // Remove the panel and re-add: both size and ratio should be restored.
12912            workspace.update_in(cx, |workspace, window, cx| {
12913                workspace.remove_panel(&panel, window, cx);
12914            });
12915
12916            workspace.update_in(cx, |workspace, window, cx| {
12917                let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12918                workspace.add_panel(new_panel, window, cx);
12919
12920                let right_dock = workspace.right_dock().read(cx);
12921                let size_state = right_dock
12922                    .panel::<TestPanel>()
12923                    .and_then(|p| right_dock.stored_panel_size_state(&p))
12924                    .expect("re-added flexible panel should have restored size state from KVP");
12925                assert_eq!(
12926                    size_state.size, None,
12927                    "re-added flexible panel should not have a persisted pixel size"
12928                );
12929                assert_eq!(
12930                    size_state.flex,
12931                    Some(original_ratio),
12932                    "re-added flexible panel should restore persisted flex"
12933                );
12934            });
12935        }
12936    }
12937
12938    #[gpui::test]
12939    async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12940        init_test(cx);
12941        let fs = FakeFs::new(cx.executor());
12942
12943        let project = Project::test(fs, [], cx).await;
12944        let (multi_workspace, cx) =
12945            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12946        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12947
12948        workspace.update(cx, |workspace, _cx| {
12949            workspace.bounds.size.width = px(900.);
12950        });
12951
12952        // Step 1: Add a tab to the center pane then open a flexible panel in the left
12953        // dock. With one full-width center pane the default ratio is 0.5, so the panel
12954        // and the center pane each take half the workspace width.
12955        workspace.update_in(cx, |workspace, window, cx| {
12956            let item = cx.new(|cx| {
12957                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12958            });
12959            workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12960
12961            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12962            workspace.add_panel(panel, window, cx);
12963            workspace.toggle_dock(DockPosition::Left, window, cx);
12964
12965            let left_dock = workspace.left_dock().read(cx);
12966            let left_width = workspace
12967                .dock_size(&left_dock, window, cx)
12968                .expect("left dock should have an active panel");
12969
12970            assert_eq!(
12971                left_width,
12972                workspace.bounds.size.width / 2.,
12973                "flexible left panel should split evenly with the center pane"
12974            );
12975        });
12976
12977        // Step 2: Split the center pane left/right. The flexible panel is treated as one
12978        // average center column, so with two center columns it should take one third of
12979        // the workspace width.
12980        workspace.update_in(cx, |workspace, window, cx| {
12981            workspace.split_pane(
12982                workspace.active_pane().clone(),
12983                SplitDirection::Right,
12984                window,
12985                cx,
12986            );
12987
12988            let left_dock = workspace.left_dock().read(cx);
12989            let left_width = workspace
12990                .dock_size(&left_dock, window, cx)
12991                .expect("left dock should still have an active panel after horizontal split");
12992
12993            assert_eq!(
12994                left_width,
12995                workspace.bounds.size.width / 3.,
12996                "flexible left panel width should match the average center column width"
12997            );
12998        });
12999
13000        // Step 3: Split the active center pane vertically (top/bottom). Vertical splits do
13001        // not change the number of center columns, so the flexible panel width stays the same.
13002        workspace.update_in(cx, |workspace, window, cx| {
13003            workspace.split_pane(
13004                workspace.active_pane().clone(),
13005                SplitDirection::Down,
13006                window,
13007                cx,
13008            );
13009
13010            let left_dock = workspace.left_dock().read(cx);
13011            let left_width = workspace
13012                .dock_size(&left_dock, window, cx)
13013                .expect("left dock should still have an active panel after vertical split");
13014
13015            assert_eq!(
13016                left_width,
13017                workspace.bounds.size.width / 3.,
13018                "flexible left panel width should still match the average center column width"
13019            );
13020        });
13021
13022        // Step 4: Open a fixed-width panel in the right dock. The right dock's default
13023        // size reduces the available width, so the flexible left panel keeps matching one
13024        // average center column within the remaining space.
13025        workspace.update_in(cx, |workspace, window, cx| {
13026            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
13027            workspace.add_panel(panel, window, cx);
13028            workspace.toggle_dock(DockPosition::Right, window, cx);
13029
13030            let right_dock = workspace.right_dock().read(cx);
13031            let right_width = workspace
13032                .dock_size(&right_dock, window, cx)
13033                .expect("right dock should have an active panel");
13034
13035            let left_dock = workspace.left_dock().read(cx);
13036            let left_width = workspace
13037                .dock_size(&left_dock, window, cx)
13038                .expect("left dock should still have an active panel");
13039
13040            let available_width = workspace.bounds.size.width - right_width;
13041            assert_eq!(
13042                left_width,
13043                available_width / 3.,
13044                "flexible left panel should keep matching one average center column"
13045            );
13046        });
13047
13048        // Step 5: Toggle the right dock's panel to flexible. Now both docks use
13049        // column-equivalent flex sizing and the workspace width is divided among
13050        // left-flex, two center columns, and right-flex.
13051        workspace.update_in(cx, |workspace, window, cx| {
13052            let right_dock = workspace.right_dock().clone();
13053            let right_panel = right_dock
13054                .read(cx)
13055                .visible_panel()
13056                .expect("right dock should have a visible panel")
13057                .clone();
13058            workspace.toggle_dock_panel_flexible_size(
13059                &right_dock,
13060                right_panel.as_ref(),
13061                window,
13062                cx,
13063            );
13064
13065            let right_dock = right_dock.read(cx);
13066            let right_panel = right_dock
13067                .visible_panel()
13068                .expect("right dock should still have a visible panel");
13069            assert!(
13070                right_panel.has_flexible_size(window, cx),
13071                "right panel should now be flexible"
13072            );
13073
13074            let right_size_state = right_dock
13075                .stored_panel_size_state(right_panel.as_ref())
13076                .expect("right panel should have a stored size state after toggling");
13077            let right_flex = right_size_state
13078                .flex
13079                .expect("right panel should have a flex value after toggling");
13080
13081            let left_dock = workspace.left_dock().read(cx);
13082            let left_width = workspace
13083                .dock_size(&left_dock, window, cx)
13084                .expect("left dock should still have an active panel");
13085            let right_width = workspace
13086                .dock_size(&right_dock, window, cx)
13087                .expect("right dock should still have an active panel");
13088
13089            let left_flex = workspace
13090                .default_dock_flex(DockPosition::Left)
13091                .expect("left dock should have a default flex");
13092            let center_column_count = workspace.center.full_height_column_count() as f32;
13093
13094            let total_flex = left_flex + center_column_count + right_flex;
13095            let expected_left = left_flex / total_flex * workspace.bounds.size.width;
13096            let expected_right = right_flex / total_flex * workspace.bounds.size.width;
13097            assert_eq!(
13098                left_width, expected_left,
13099                "flexible left panel should share workspace width via flex ratios"
13100            );
13101            assert_eq!(
13102                right_width, expected_right,
13103                "flexible right panel should share workspace width via flex ratios"
13104            );
13105        });
13106    }
13107
13108    struct TestModal(FocusHandle);
13109
13110    impl TestModal {
13111        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
13112            Self(cx.focus_handle())
13113        }
13114    }
13115
13116    impl EventEmitter<DismissEvent> for TestModal {}
13117
13118    impl Focusable for TestModal {
13119        fn focus_handle(&self, _cx: &App) -> FocusHandle {
13120            self.0.clone()
13121        }
13122    }
13123
13124    impl ModalView for TestModal {}
13125
13126    impl Render for TestModal {
13127        fn render(
13128            &mut self,
13129            _window: &mut Window,
13130            _cx: &mut Context<TestModal>,
13131        ) -> impl IntoElement {
13132            div().track_focus(&self.0)
13133        }
13134    }
13135
13136    #[gpui::test]
13137    async fn test_panels(cx: &mut gpui::TestAppContext) {
13138        init_test(cx);
13139        let fs = FakeFs::new(cx.executor());
13140
13141        let project = Project::test(fs, [], cx).await;
13142        let (multi_workspace, cx) =
13143            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13144        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13145
13146        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
13147            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
13148            workspace.add_panel(panel_1.clone(), window, cx);
13149            workspace.toggle_dock(DockPosition::Left, window, cx);
13150            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
13151            workspace.add_panel(panel_2.clone(), window, cx);
13152            workspace.toggle_dock(DockPosition::Right, window, cx);
13153
13154            let left_dock = workspace.left_dock();
13155            assert_eq!(
13156                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13157                panel_1.panel_id()
13158            );
13159            assert_eq!(
13160                workspace.dock_size(&left_dock.read(cx), window, cx),
13161                Some(px(300.))
13162            );
13163
13164            workspace.resize_left_dock(px(1337.), window, cx);
13165            assert_eq!(
13166                workspace
13167                    .right_dock()
13168                    .read(cx)
13169                    .visible_panel()
13170                    .unwrap()
13171                    .panel_id(),
13172                panel_2.panel_id(),
13173            );
13174
13175            (panel_1, panel_2)
13176        });
13177
13178        // Move panel_1 to the right
13179        panel_1.update_in(cx, |panel_1, window, cx| {
13180            panel_1.set_position(DockPosition::Right, window, cx)
13181        });
13182
13183        workspace.update_in(cx, |workspace, window, cx| {
13184            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
13185            // Since it was the only panel on the left, the left dock should now be closed.
13186            assert!(!workspace.left_dock().read(cx).is_open());
13187            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
13188            let right_dock = workspace.right_dock();
13189            assert_eq!(
13190                right_dock.read(cx).visible_panel().unwrap().panel_id(),
13191                panel_1.panel_id()
13192            );
13193            assert_eq!(
13194                right_dock
13195                    .read(cx)
13196                    .active_panel_size()
13197                    .unwrap()
13198                    .size
13199                    .unwrap(),
13200                px(1337.)
13201            );
13202
13203            // Now we move panel_2 to the left
13204            panel_2.set_position(DockPosition::Left, window, cx);
13205        });
13206
13207        workspace.update(cx, |workspace, cx| {
13208            // Since panel_2 was not visible on the right, we don't open the left dock.
13209            assert!(!workspace.left_dock().read(cx).is_open());
13210            // And the right dock is unaffected in its displaying of panel_1
13211            assert!(workspace.right_dock().read(cx).is_open());
13212            assert_eq!(
13213                workspace
13214                    .right_dock()
13215                    .read(cx)
13216                    .visible_panel()
13217                    .unwrap()
13218                    .panel_id(),
13219                panel_1.panel_id(),
13220            );
13221        });
13222
13223        // Move panel_1 back to the left
13224        panel_1.update_in(cx, |panel_1, window, cx| {
13225            panel_1.set_position(DockPosition::Left, window, cx)
13226        });
13227
13228        workspace.update_in(cx, |workspace, window, cx| {
13229            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
13230            let left_dock = workspace.left_dock();
13231            assert!(left_dock.read(cx).is_open());
13232            assert_eq!(
13233                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13234                panel_1.panel_id()
13235            );
13236            assert_eq!(
13237                workspace.dock_size(&left_dock.read(cx), window, cx),
13238                Some(px(1337.))
13239            );
13240            // And the right dock should be closed as it no longer has any panels.
13241            assert!(!workspace.right_dock().read(cx).is_open());
13242
13243            // Now we move panel_1 to the bottom
13244            panel_1.set_position(DockPosition::Bottom, window, cx);
13245        });
13246
13247        workspace.update_in(cx, |workspace, window, cx| {
13248            // Since panel_1 was visible on the left, we close the left dock.
13249            assert!(!workspace.left_dock().read(cx).is_open());
13250            // The bottom dock is sized based on the panel's default size,
13251            // since the panel orientation changed from vertical to horizontal.
13252            let bottom_dock = workspace.bottom_dock();
13253            assert_eq!(
13254                workspace.dock_size(&bottom_dock.read(cx), window, cx),
13255                Some(px(300.))
13256            );
13257            // Close bottom dock and move panel_1 back to the left.
13258            bottom_dock.update(cx, |bottom_dock, cx| {
13259                bottom_dock.set_open(false, window, cx)
13260            });
13261            panel_1.set_position(DockPosition::Left, window, cx);
13262        });
13263
13264        // Emit activated event on panel 1
13265        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
13266
13267        // Now the left dock is open and panel_1 is active and focused.
13268        workspace.update_in(cx, |workspace, window, cx| {
13269            let left_dock = workspace.left_dock();
13270            assert!(left_dock.read(cx).is_open());
13271            assert_eq!(
13272                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13273                panel_1.panel_id(),
13274            );
13275            assert!(panel_1.focus_handle(cx).is_focused(window));
13276        });
13277
13278        // Emit closed event on panel 2, which is not active
13279        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13280
13281        // Wo don't close the left dock, because panel_2 wasn't the active panel
13282        workspace.update(cx, |workspace, cx| {
13283            let left_dock = workspace.left_dock();
13284            assert!(left_dock.read(cx).is_open());
13285            assert_eq!(
13286                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13287                panel_1.panel_id(),
13288            );
13289        });
13290
13291        // Emitting a ZoomIn event shows the panel as zoomed.
13292        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
13293        workspace.read_with(cx, |workspace, _| {
13294            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13295            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
13296        });
13297
13298        // Move panel to another dock while it is zoomed
13299        panel_1.update_in(cx, |panel, window, cx| {
13300            panel.set_position(DockPosition::Right, window, cx)
13301        });
13302        workspace.read_with(cx, |workspace, _| {
13303            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13304
13305            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13306        });
13307
13308        // This is a helper for getting a:
13309        // - valid focus on an element,
13310        // - that isn't a part of the panes and panels system of the Workspace,
13311        // - and doesn't trigger the 'on_focus_lost' API.
13312        let focus_other_view = {
13313            let workspace = workspace.clone();
13314            move |cx: &mut VisualTestContext| {
13315                workspace.update_in(cx, |workspace, window, cx| {
13316                    if workspace.active_modal::<TestModal>(cx).is_some() {
13317                        workspace.toggle_modal(window, cx, TestModal::new);
13318                        workspace.toggle_modal(window, cx, TestModal::new);
13319                    } else {
13320                        workspace.toggle_modal(window, cx, TestModal::new);
13321                    }
13322                })
13323            }
13324        };
13325
13326        // If focus is transferred to another view that's not a panel or another pane, we still show
13327        // the panel as zoomed.
13328        focus_other_view(cx);
13329        workspace.read_with(cx, |workspace, _| {
13330            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13331            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13332        });
13333
13334        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13335        workspace.update_in(cx, |_workspace, window, cx| {
13336            cx.focus_self(window);
13337        });
13338        workspace.read_with(cx, |workspace, _| {
13339            assert_eq!(workspace.zoomed, None);
13340            assert_eq!(workspace.zoomed_position, None);
13341        });
13342
13343        // If focus is transferred again to another view that's not a panel or a pane, we won't
13344        // show the panel as zoomed because it wasn't zoomed before.
13345        focus_other_view(cx);
13346        workspace.read_with(cx, |workspace, _| {
13347            assert_eq!(workspace.zoomed, None);
13348            assert_eq!(workspace.zoomed_position, None);
13349        });
13350
13351        // When the panel is activated, it is zoomed again.
13352        cx.dispatch_action(ToggleRightDock);
13353        workspace.read_with(cx, |workspace, _| {
13354            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13355            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13356        });
13357
13358        // Emitting a ZoomOut event unzooms the panel.
13359        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13360        workspace.read_with(cx, |workspace, _| {
13361            assert_eq!(workspace.zoomed, None);
13362            assert_eq!(workspace.zoomed_position, None);
13363        });
13364
13365        // Emit closed event on panel 1, which is active
13366        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13367
13368        // Now the left dock is closed, because panel_1 was the active panel
13369        workspace.update(cx, |workspace, cx| {
13370            let right_dock = workspace.right_dock();
13371            assert!(!right_dock.read(cx).is_open());
13372        });
13373    }
13374
13375    #[gpui::test]
13376    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13377        init_test(cx);
13378
13379        let fs = FakeFs::new(cx.background_executor.clone());
13380        let project = Project::test(fs, [], cx).await;
13381        let (workspace, cx) =
13382            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13383        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13384
13385        let dirty_regular_buffer = cx.new(|cx| {
13386            TestItem::new(cx)
13387                .with_dirty(true)
13388                .with_label("1.txt")
13389                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13390        });
13391        let dirty_regular_buffer_2 = cx.new(|cx| {
13392            TestItem::new(cx)
13393                .with_dirty(true)
13394                .with_label("2.txt")
13395                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13396        });
13397        let dirty_multi_buffer_with_both = cx.new(|cx| {
13398            TestItem::new(cx)
13399                .with_dirty(true)
13400                .with_buffer_kind(ItemBufferKind::Multibuffer)
13401                .with_label("Fake Project Search")
13402                .with_project_items(&[
13403                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13404                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13405                ])
13406        });
13407        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13408        workspace.update_in(cx, |workspace, window, cx| {
13409            workspace.add_item(
13410                pane.clone(),
13411                Box::new(dirty_regular_buffer.clone()),
13412                None,
13413                false,
13414                false,
13415                window,
13416                cx,
13417            );
13418            workspace.add_item(
13419                pane.clone(),
13420                Box::new(dirty_regular_buffer_2.clone()),
13421                None,
13422                false,
13423                false,
13424                window,
13425                cx,
13426            );
13427            workspace.add_item(
13428                pane.clone(),
13429                Box::new(dirty_multi_buffer_with_both.clone()),
13430                None,
13431                false,
13432                false,
13433                window,
13434                cx,
13435            );
13436        });
13437
13438        pane.update_in(cx, |pane, window, cx| {
13439            pane.activate_item(2, true, true, window, cx);
13440            assert_eq!(
13441                pane.active_item().unwrap().item_id(),
13442                multi_buffer_with_both_files_id,
13443                "Should select the multi buffer in the pane"
13444            );
13445        });
13446        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13447            pane.close_other_items(
13448                &CloseOtherItems {
13449                    save_intent: Some(SaveIntent::Save),
13450                    close_pinned: true,
13451                },
13452                None,
13453                window,
13454                cx,
13455            )
13456        });
13457        cx.background_executor.run_until_parked();
13458        assert!(!cx.has_pending_prompt());
13459        close_all_but_multi_buffer_task
13460            .await
13461            .expect("Closing all buffers but the multi buffer failed");
13462        pane.update(cx, |pane, cx| {
13463            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13464            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13465            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13466            assert_eq!(pane.items_len(), 1);
13467            assert_eq!(
13468                pane.active_item().unwrap().item_id(),
13469                multi_buffer_with_both_files_id,
13470                "Should have only the multi buffer left in the pane"
13471            );
13472            assert!(
13473                dirty_multi_buffer_with_both.read(cx).is_dirty,
13474                "The multi buffer containing the unsaved buffer should still be dirty"
13475            );
13476        });
13477
13478        dirty_regular_buffer.update(cx, |buffer, cx| {
13479            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13480        });
13481
13482        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13483            pane.close_active_item(
13484                &CloseActiveItem {
13485                    save_intent: Some(SaveIntent::Close),
13486                    close_pinned: false,
13487                },
13488                window,
13489                cx,
13490            )
13491        });
13492        cx.background_executor.run_until_parked();
13493        assert!(
13494            cx.has_pending_prompt(),
13495            "Dirty multi buffer should prompt a save dialog"
13496        );
13497        cx.simulate_prompt_answer("Save");
13498        cx.background_executor.run_until_parked();
13499        close_multi_buffer_task
13500            .await
13501            .expect("Closing the multi buffer failed");
13502        pane.update(cx, |pane, cx| {
13503            assert_eq!(
13504                dirty_multi_buffer_with_both.read(cx).save_count,
13505                1,
13506                "Multi buffer item should get be saved"
13507            );
13508            // Test impl does not save inner items, so we do not assert them
13509            assert_eq!(
13510                pane.items_len(),
13511                0,
13512                "No more items should be left in the pane"
13513            );
13514            assert!(pane.active_item().is_none());
13515        });
13516    }
13517
13518    #[gpui::test]
13519    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13520        cx: &mut TestAppContext,
13521    ) {
13522        init_test(cx);
13523
13524        let fs = FakeFs::new(cx.background_executor.clone());
13525        let project = Project::test(fs, [], cx).await;
13526        let (workspace, cx) =
13527            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13528        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13529
13530        let dirty_regular_buffer = cx.new(|cx| {
13531            TestItem::new(cx)
13532                .with_dirty(true)
13533                .with_label("1.txt")
13534                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13535        });
13536        let dirty_regular_buffer_2 = cx.new(|cx| {
13537            TestItem::new(cx)
13538                .with_dirty(true)
13539                .with_label("2.txt")
13540                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13541        });
13542        let clear_regular_buffer = cx.new(|cx| {
13543            TestItem::new(cx)
13544                .with_label("3.txt")
13545                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13546        });
13547
13548        let dirty_multi_buffer_with_both = cx.new(|cx| {
13549            TestItem::new(cx)
13550                .with_dirty(true)
13551                .with_buffer_kind(ItemBufferKind::Multibuffer)
13552                .with_label("Fake Project Search")
13553                .with_project_items(&[
13554                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13555                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13556                    clear_regular_buffer.read(cx).project_items[0].clone(),
13557                ])
13558        });
13559        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13560        workspace.update_in(cx, |workspace, window, cx| {
13561            workspace.add_item(
13562                pane.clone(),
13563                Box::new(dirty_regular_buffer.clone()),
13564                None,
13565                false,
13566                false,
13567                window,
13568                cx,
13569            );
13570            workspace.add_item(
13571                pane.clone(),
13572                Box::new(dirty_multi_buffer_with_both.clone()),
13573                None,
13574                false,
13575                false,
13576                window,
13577                cx,
13578            );
13579        });
13580
13581        pane.update_in(cx, |pane, window, cx| {
13582            pane.activate_item(1, true, true, window, cx);
13583            assert_eq!(
13584                pane.active_item().unwrap().item_id(),
13585                multi_buffer_with_both_files_id,
13586                "Should select the multi buffer in the pane"
13587            );
13588        });
13589        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13590            pane.close_active_item(
13591                &CloseActiveItem {
13592                    save_intent: None,
13593                    close_pinned: false,
13594                },
13595                window,
13596                cx,
13597            )
13598        });
13599        cx.background_executor.run_until_parked();
13600        assert!(
13601            cx.has_pending_prompt(),
13602            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13603        );
13604    }
13605
13606    /// Tests that when `close_on_file_delete` is enabled, files are automatically
13607    /// closed when they are deleted from disk.
13608    #[gpui::test]
13609    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13610        init_test(cx);
13611
13612        // Enable the close_on_disk_deletion setting
13613        cx.update_global(|store: &mut SettingsStore, cx| {
13614            store.update_user_settings(cx, |settings| {
13615                settings.workspace.close_on_file_delete = Some(true);
13616            });
13617        });
13618
13619        let fs = FakeFs::new(cx.background_executor.clone());
13620        let project = Project::test(fs, [], cx).await;
13621        let (workspace, cx) =
13622            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13623        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13624
13625        // Create a test item that simulates a file
13626        let item = cx.new(|cx| {
13627            TestItem::new(cx)
13628                .with_label("test.txt")
13629                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13630        });
13631
13632        // Add item to workspace
13633        workspace.update_in(cx, |workspace, window, cx| {
13634            workspace.add_item(
13635                pane.clone(),
13636                Box::new(item.clone()),
13637                None,
13638                false,
13639                false,
13640                window,
13641                cx,
13642            );
13643        });
13644
13645        // Verify the item is in the pane
13646        pane.read_with(cx, |pane, _| {
13647            assert_eq!(pane.items().count(), 1);
13648        });
13649
13650        // Simulate file deletion by setting the item's deleted state
13651        item.update(cx, |item, _| {
13652            item.set_has_deleted_file(true);
13653        });
13654
13655        // Emit UpdateTab event to trigger the close behavior
13656        cx.run_until_parked();
13657        item.update(cx, |_, cx| {
13658            cx.emit(ItemEvent::UpdateTab);
13659        });
13660
13661        // Allow the close operation to complete
13662        cx.run_until_parked();
13663
13664        // Verify the item was automatically closed
13665        pane.read_with(cx, |pane, _| {
13666            assert_eq!(
13667                pane.items().count(),
13668                0,
13669                "Item should be automatically closed when file is deleted"
13670            );
13671        });
13672    }
13673
13674    /// Tests that when `close_on_file_delete` is disabled (default), files remain
13675    /// open with a strikethrough when they are deleted from disk.
13676    #[gpui::test]
13677    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13678        init_test(cx);
13679
13680        // Ensure close_on_disk_deletion is disabled (default)
13681        cx.update_global(|store: &mut SettingsStore, cx| {
13682            store.update_user_settings(cx, |settings| {
13683                settings.workspace.close_on_file_delete = Some(false);
13684            });
13685        });
13686
13687        let fs = FakeFs::new(cx.background_executor.clone());
13688        let project = Project::test(fs, [], cx).await;
13689        let (workspace, cx) =
13690            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13691        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13692
13693        // Create a test item that simulates a file
13694        let item = cx.new(|cx| {
13695            TestItem::new(cx)
13696                .with_label("test.txt")
13697                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13698        });
13699
13700        // Add item to workspace
13701        workspace.update_in(cx, |workspace, window, cx| {
13702            workspace.add_item(
13703                pane.clone(),
13704                Box::new(item.clone()),
13705                None,
13706                false,
13707                false,
13708                window,
13709                cx,
13710            );
13711        });
13712
13713        // Verify the item is in the pane
13714        pane.read_with(cx, |pane, _| {
13715            assert_eq!(pane.items().count(), 1);
13716        });
13717
13718        // Simulate file deletion
13719        item.update(cx, |item, _| {
13720            item.set_has_deleted_file(true);
13721        });
13722
13723        // Emit UpdateTab event
13724        cx.run_until_parked();
13725        item.update(cx, |_, cx| {
13726            cx.emit(ItemEvent::UpdateTab);
13727        });
13728
13729        // Allow any potential close operation to complete
13730        cx.run_until_parked();
13731
13732        // Verify the item remains open (with strikethrough)
13733        pane.read_with(cx, |pane, _| {
13734            assert_eq!(
13735                pane.items().count(),
13736                1,
13737                "Item should remain open when close_on_disk_deletion is disabled"
13738            );
13739        });
13740
13741        // Verify the item shows as deleted
13742        item.read_with(cx, |item, _| {
13743            assert!(
13744                item.has_deleted_file,
13745                "Item should be marked as having deleted file"
13746            );
13747        });
13748    }
13749
13750    /// Tests that dirty files are not automatically closed when deleted from disk,
13751    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13752    /// unsaved changes without being prompted.
13753    #[gpui::test]
13754    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13755        init_test(cx);
13756
13757        // Enable the close_on_file_delete setting
13758        cx.update_global(|store: &mut SettingsStore, cx| {
13759            store.update_user_settings(cx, |settings| {
13760                settings.workspace.close_on_file_delete = Some(true);
13761            });
13762        });
13763
13764        let fs = FakeFs::new(cx.background_executor.clone());
13765        let project = Project::test(fs, [], cx).await;
13766        let (workspace, cx) =
13767            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13768        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13769
13770        // Create a dirty test item
13771        let item = cx.new(|cx| {
13772            TestItem::new(cx)
13773                .with_dirty(true)
13774                .with_label("test.txt")
13775                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13776        });
13777
13778        // Add item to workspace
13779        workspace.update_in(cx, |workspace, window, cx| {
13780            workspace.add_item(
13781                pane.clone(),
13782                Box::new(item.clone()),
13783                None,
13784                false,
13785                false,
13786                window,
13787                cx,
13788            );
13789        });
13790
13791        // Simulate file deletion
13792        item.update(cx, |item, _| {
13793            item.set_has_deleted_file(true);
13794        });
13795
13796        // Emit UpdateTab event to trigger the close behavior
13797        cx.run_until_parked();
13798        item.update(cx, |_, cx| {
13799            cx.emit(ItemEvent::UpdateTab);
13800        });
13801
13802        // Allow any potential close operation to complete
13803        cx.run_until_parked();
13804
13805        // Verify the item remains open (dirty files are not auto-closed)
13806        pane.read_with(cx, |pane, _| {
13807            assert_eq!(
13808                pane.items().count(),
13809                1,
13810                "Dirty items should not be automatically closed even when file is deleted"
13811            );
13812        });
13813
13814        // Verify the item is marked as deleted and still dirty
13815        item.read_with(cx, |item, _| {
13816            assert!(
13817                item.has_deleted_file,
13818                "Item should be marked as having deleted file"
13819            );
13820            assert!(item.is_dirty, "Item should still be dirty");
13821        });
13822    }
13823
13824    /// Tests that navigation history is cleaned up when files are auto-closed
13825    /// due to deletion from disk.
13826    #[gpui::test]
13827    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13828        init_test(cx);
13829
13830        // Enable the close_on_file_delete setting
13831        cx.update_global(|store: &mut SettingsStore, cx| {
13832            store.update_user_settings(cx, |settings| {
13833                settings.workspace.close_on_file_delete = Some(true);
13834            });
13835        });
13836
13837        let fs = FakeFs::new(cx.background_executor.clone());
13838        let project = Project::test(fs, [], cx).await;
13839        let (workspace, cx) =
13840            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13841        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13842
13843        // Create test items
13844        let item1 = cx.new(|cx| {
13845            TestItem::new(cx)
13846                .with_label("test1.txt")
13847                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13848        });
13849        let item1_id = item1.item_id();
13850
13851        let item2 = cx.new(|cx| {
13852            TestItem::new(cx)
13853                .with_label("test2.txt")
13854                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13855        });
13856
13857        // Add items to workspace
13858        workspace.update_in(cx, |workspace, window, cx| {
13859            workspace.add_item(
13860                pane.clone(),
13861                Box::new(item1.clone()),
13862                None,
13863                false,
13864                false,
13865                window,
13866                cx,
13867            );
13868            workspace.add_item(
13869                pane.clone(),
13870                Box::new(item2.clone()),
13871                None,
13872                false,
13873                false,
13874                window,
13875                cx,
13876            );
13877        });
13878
13879        // Activate item1 to ensure it gets navigation entries
13880        pane.update_in(cx, |pane, window, cx| {
13881            pane.activate_item(0, true, true, window, cx);
13882        });
13883
13884        // Switch to item2 and back to create navigation history
13885        pane.update_in(cx, |pane, window, cx| {
13886            pane.activate_item(1, true, true, window, cx);
13887        });
13888        cx.run_until_parked();
13889
13890        pane.update_in(cx, |pane, window, cx| {
13891            pane.activate_item(0, true, true, window, cx);
13892        });
13893        cx.run_until_parked();
13894
13895        // Simulate file deletion for item1
13896        item1.update(cx, |item, _| {
13897            item.set_has_deleted_file(true);
13898        });
13899
13900        // Emit UpdateTab event to trigger the close behavior
13901        item1.update(cx, |_, cx| {
13902            cx.emit(ItemEvent::UpdateTab);
13903        });
13904        cx.run_until_parked();
13905
13906        // Verify item1 was closed
13907        pane.read_with(cx, |pane, _| {
13908            assert_eq!(
13909                pane.items().count(),
13910                1,
13911                "Should have 1 item remaining after auto-close"
13912            );
13913        });
13914
13915        // Check navigation history after close
13916        let has_item = pane.read_with(cx, |pane, cx| {
13917            let mut has_item = false;
13918            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13919                if entry.item.id() == item1_id {
13920                    has_item = true;
13921                }
13922            });
13923            has_item
13924        });
13925
13926        assert!(
13927            !has_item,
13928            "Navigation history should not contain closed item entries"
13929        );
13930    }
13931
13932    #[gpui::test]
13933    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13934        cx: &mut TestAppContext,
13935    ) {
13936        init_test(cx);
13937
13938        let fs = FakeFs::new(cx.background_executor.clone());
13939        let project = Project::test(fs, [], cx).await;
13940        let (workspace, cx) =
13941            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13942        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13943
13944        let dirty_regular_buffer = cx.new(|cx| {
13945            TestItem::new(cx)
13946                .with_dirty(true)
13947                .with_label("1.txt")
13948                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13949        });
13950        let dirty_regular_buffer_2 = cx.new(|cx| {
13951            TestItem::new(cx)
13952                .with_dirty(true)
13953                .with_label("2.txt")
13954                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13955        });
13956        let clear_regular_buffer = cx.new(|cx| {
13957            TestItem::new(cx)
13958                .with_label("3.txt")
13959                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13960        });
13961
13962        let dirty_multi_buffer = cx.new(|cx| {
13963            TestItem::new(cx)
13964                .with_dirty(true)
13965                .with_buffer_kind(ItemBufferKind::Multibuffer)
13966                .with_label("Fake Project Search")
13967                .with_project_items(&[
13968                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13969                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13970                    clear_regular_buffer.read(cx).project_items[0].clone(),
13971                ])
13972        });
13973        workspace.update_in(cx, |workspace, window, cx| {
13974            workspace.add_item(
13975                pane.clone(),
13976                Box::new(dirty_regular_buffer.clone()),
13977                None,
13978                false,
13979                false,
13980                window,
13981                cx,
13982            );
13983            workspace.add_item(
13984                pane.clone(),
13985                Box::new(dirty_regular_buffer_2.clone()),
13986                None,
13987                false,
13988                false,
13989                window,
13990                cx,
13991            );
13992            workspace.add_item(
13993                pane.clone(),
13994                Box::new(dirty_multi_buffer.clone()),
13995                None,
13996                false,
13997                false,
13998                window,
13999                cx,
14000            );
14001        });
14002
14003        pane.update_in(cx, |pane, window, cx| {
14004            pane.activate_item(2, true, true, window, cx);
14005            assert_eq!(
14006                pane.active_item().unwrap().item_id(),
14007                dirty_multi_buffer.item_id(),
14008                "Should select the multi buffer in the pane"
14009            );
14010        });
14011        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
14012            pane.close_active_item(
14013                &CloseActiveItem {
14014                    save_intent: None,
14015                    close_pinned: false,
14016                },
14017                window,
14018                cx,
14019            )
14020        });
14021        cx.background_executor.run_until_parked();
14022        assert!(
14023            !cx.has_pending_prompt(),
14024            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
14025        );
14026        close_multi_buffer_task
14027            .await
14028            .expect("Closing multi buffer failed");
14029        pane.update(cx, |pane, cx| {
14030            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
14031            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
14032            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
14033            assert_eq!(
14034                pane.items()
14035                    .map(|item| item.item_id())
14036                    .sorted()
14037                    .collect::<Vec<_>>(),
14038                vec![
14039                    dirty_regular_buffer.item_id(),
14040                    dirty_regular_buffer_2.item_id(),
14041                ],
14042                "Should have no multi buffer left in the pane"
14043            );
14044            assert!(dirty_regular_buffer.read(cx).is_dirty);
14045            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
14046        });
14047    }
14048
14049    #[gpui::test]
14050    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
14051        init_test(cx);
14052        let fs = FakeFs::new(cx.executor());
14053        let project = Project::test(fs, [], cx).await;
14054        let (multi_workspace, cx) =
14055            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14056        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14057
14058        // Add a new panel to the right dock, opening the dock and setting the
14059        // focus to the new panel.
14060        let panel = workspace.update_in(cx, |workspace, window, cx| {
14061            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14062            workspace.add_panel(panel.clone(), window, cx);
14063
14064            workspace
14065                .right_dock()
14066                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14067
14068            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14069
14070            panel
14071        });
14072
14073        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
14074        // panel to the next valid position which, in this case, is the left
14075        // dock.
14076        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14077        workspace.update(cx, |workspace, cx| {
14078            assert!(workspace.left_dock().read(cx).is_open());
14079            assert_eq!(panel.read(cx).position, DockPosition::Left);
14080        });
14081
14082        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
14083        // panel to the next valid position which, in this case, is the bottom
14084        // dock.
14085        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14086        workspace.update(cx, |workspace, cx| {
14087            assert!(workspace.bottom_dock().read(cx).is_open());
14088            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
14089        });
14090
14091        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
14092        // around moving the panel to its initial position, the right dock.
14093        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14094        workspace.update(cx, |workspace, cx| {
14095            assert!(workspace.right_dock().read(cx).is_open());
14096            assert_eq!(panel.read(cx).position, DockPosition::Right);
14097        });
14098
14099        // Remove focus from the panel, ensuring that, if the panel is not
14100        // focused, the `MoveFocusedPanelToNextPosition` action does not update
14101        // the panel's position, so the panel is still in the right dock.
14102        workspace.update_in(cx, |workspace, window, cx| {
14103            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14104        });
14105
14106        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14107        workspace.update(cx, |workspace, cx| {
14108            assert!(workspace.right_dock().read(cx).is_open());
14109            assert_eq!(panel.read(cx).position, DockPosition::Right);
14110        });
14111    }
14112
14113    #[gpui::test]
14114    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
14115        init_test(cx);
14116
14117        let fs = FakeFs::new(cx.executor());
14118        let project = Project::test(fs, [], cx).await;
14119        let (workspace, cx) =
14120            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14121
14122        let item_1 = cx.new(|cx| {
14123            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14124        });
14125        workspace.update_in(cx, |workspace, window, cx| {
14126            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14127            workspace.move_item_to_pane_in_direction(
14128                &MoveItemToPaneInDirection {
14129                    direction: SplitDirection::Right,
14130                    focus: true,
14131                    clone: false,
14132                },
14133                window,
14134                cx,
14135            );
14136            workspace.move_item_to_pane_at_index(
14137                &MoveItemToPane {
14138                    destination: 3,
14139                    focus: true,
14140                    clone: false,
14141                },
14142                window,
14143                cx,
14144            );
14145
14146            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
14147            assert_eq!(
14148                pane_items_paths(&workspace.active_pane, cx),
14149                vec!["first.txt".to_string()],
14150                "Single item was not moved anywhere"
14151            );
14152        });
14153
14154        let item_2 = cx.new(|cx| {
14155            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
14156        });
14157        workspace.update_in(cx, |workspace, window, cx| {
14158            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
14159            assert_eq!(
14160                pane_items_paths(&workspace.panes[0], cx),
14161                vec!["first.txt".to_string(), "second.txt".to_string()],
14162            );
14163            workspace.move_item_to_pane_in_direction(
14164                &MoveItemToPaneInDirection {
14165                    direction: SplitDirection::Right,
14166                    focus: true,
14167                    clone: false,
14168                },
14169                window,
14170                cx,
14171            );
14172
14173            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
14174            assert_eq!(
14175                pane_items_paths(&workspace.panes[0], cx),
14176                vec!["first.txt".to_string()],
14177                "After moving, one item should be left in the original pane"
14178            );
14179            assert_eq!(
14180                pane_items_paths(&workspace.panes[1], cx),
14181                vec!["second.txt".to_string()],
14182                "New item should have been moved to the new pane"
14183            );
14184        });
14185
14186        let item_3 = cx.new(|cx| {
14187            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
14188        });
14189        workspace.update_in(cx, |workspace, window, cx| {
14190            let original_pane = workspace.panes[0].clone();
14191            workspace.set_active_pane(&original_pane, window, cx);
14192            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
14193            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
14194            assert_eq!(
14195                pane_items_paths(&workspace.active_pane, cx),
14196                vec!["first.txt".to_string(), "third.txt".to_string()],
14197                "New pane should be ready to move one item out"
14198            );
14199
14200            workspace.move_item_to_pane_at_index(
14201                &MoveItemToPane {
14202                    destination: 3,
14203                    focus: true,
14204                    clone: false,
14205                },
14206                window,
14207                cx,
14208            );
14209            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
14210            assert_eq!(
14211                pane_items_paths(&workspace.active_pane, cx),
14212                vec!["first.txt".to_string()],
14213                "After moving, one item should be left in the original pane"
14214            );
14215            assert_eq!(
14216                pane_items_paths(&workspace.panes[1], cx),
14217                vec!["second.txt".to_string()],
14218                "Previously created pane should be unchanged"
14219            );
14220            assert_eq!(
14221                pane_items_paths(&workspace.panes[2], cx),
14222                vec!["third.txt".to_string()],
14223                "New item should have been moved to the new pane"
14224            );
14225        });
14226    }
14227
14228    #[gpui::test]
14229    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
14230        init_test(cx);
14231
14232        let fs = FakeFs::new(cx.executor());
14233        let project = Project::test(fs, [], cx).await;
14234        let (workspace, cx) =
14235            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14236
14237        let item_1 = cx.new(|cx| {
14238            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14239        });
14240        workspace.update_in(cx, |workspace, window, cx| {
14241            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14242            workspace.move_item_to_pane_in_direction(
14243                &MoveItemToPaneInDirection {
14244                    direction: SplitDirection::Right,
14245                    focus: true,
14246                    clone: true,
14247                },
14248                window,
14249                cx,
14250            );
14251        });
14252        cx.run_until_parked();
14253        workspace.update_in(cx, |workspace, window, cx| {
14254            workspace.move_item_to_pane_at_index(
14255                &MoveItemToPane {
14256                    destination: 3,
14257                    focus: true,
14258                    clone: true,
14259                },
14260                window,
14261                cx,
14262            );
14263        });
14264        cx.run_until_parked();
14265
14266        workspace.update(cx, |workspace, cx| {
14267            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
14268            for pane in workspace.panes() {
14269                assert_eq!(
14270                    pane_items_paths(pane, cx),
14271                    vec!["first.txt".to_string()],
14272                    "Single item exists in all panes"
14273                );
14274            }
14275        });
14276
14277        // verify that the active pane has been updated after waiting for the
14278        // pane focus event to fire and resolve
14279        workspace.read_with(cx, |workspace, _app| {
14280            assert_eq!(
14281                workspace.active_pane(),
14282                &workspace.panes[2],
14283                "The third pane should be the active one: {:?}",
14284                workspace.panes
14285            );
14286        })
14287    }
14288
14289    #[gpui::test]
14290    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
14291        init_test(cx);
14292
14293        let fs = FakeFs::new(cx.executor());
14294        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
14295
14296        let project = Project::test(fs, ["root".as_ref()], cx).await;
14297        let (workspace, cx) =
14298            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14299
14300        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14301        // Add item to pane A with project path
14302        let item_a = cx.new(|cx| {
14303            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14304        });
14305        workspace.update_in(cx, |workspace, window, cx| {
14306            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14307        });
14308
14309        // Split to create pane B
14310        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14311            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14312        });
14313
14314        // Add item with SAME project path to pane B, and pin it
14315        let item_b = cx.new(|cx| {
14316            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14317        });
14318        pane_b.update_in(cx, |pane, window, cx| {
14319            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14320            pane.set_pinned_count(1);
14321        });
14322
14323        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14324        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14325
14326        // close_pinned: false should only close the unpinned copy
14327        workspace.update_in(cx, |workspace, window, cx| {
14328            workspace.close_item_in_all_panes(
14329                &CloseItemInAllPanes {
14330                    save_intent: Some(SaveIntent::Close),
14331                    close_pinned: false,
14332                },
14333                window,
14334                cx,
14335            )
14336        });
14337        cx.executor().run_until_parked();
14338
14339        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14340        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14341        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14342        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14343
14344        // Split again, seeing as closing the previous item also closed its
14345        // pane, so only pane remains, which does not allow us to properly test
14346        // that both items close when `close_pinned: true`.
14347        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14348            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14349        });
14350
14351        // Add an item with the same project path to pane C so that
14352        // close_item_in_all_panes can determine what to close across all panes
14353        // (it reads the active item from the active pane, and split_pane
14354        // creates an empty pane).
14355        let item_c = cx.new(|cx| {
14356            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14357        });
14358        pane_c.update_in(cx, |pane, window, cx| {
14359            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14360        });
14361
14362        // close_pinned: true should close the pinned copy too
14363        workspace.update_in(cx, |workspace, window, cx| {
14364            let panes_count = workspace.panes().len();
14365            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14366
14367            workspace.close_item_in_all_panes(
14368                &CloseItemInAllPanes {
14369                    save_intent: Some(SaveIntent::Close),
14370                    close_pinned: true,
14371                },
14372                window,
14373                cx,
14374            )
14375        });
14376        cx.executor().run_until_parked();
14377
14378        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14379        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14380        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14381        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14382    }
14383
14384    mod register_project_item_tests {
14385
14386        use super::*;
14387
14388        // View
14389        struct TestPngItemView {
14390            focus_handle: FocusHandle,
14391        }
14392        // Model
14393        struct TestPngItem {}
14394
14395        impl project::ProjectItem for TestPngItem {
14396            fn try_open(
14397                _project: &Entity<Project>,
14398                path: &ProjectPath,
14399                cx: &mut App,
14400            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14401                if path.path.extension().unwrap() == "png" {
14402                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14403                } else {
14404                    None
14405                }
14406            }
14407
14408            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14409                None
14410            }
14411
14412            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14413                None
14414            }
14415
14416            fn is_dirty(&self) -> bool {
14417                false
14418            }
14419        }
14420
14421        impl Item for TestPngItemView {
14422            type Event = ();
14423            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14424                "".into()
14425            }
14426        }
14427        impl EventEmitter<()> for TestPngItemView {}
14428        impl Focusable for TestPngItemView {
14429            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14430                self.focus_handle.clone()
14431            }
14432        }
14433
14434        impl Render for TestPngItemView {
14435            fn render(
14436                &mut self,
14437                _window: &mut Window,
14438                _cx: &mut Context<Self>,
14439            ) -> impl IntoElement {
14440                Empty
14441            }
14442        }
14443
14444        impl ProjectItem for TestPngItemView {
14445            type Item = TestPngItem;
14446
14447            fn for_project_item(
14448                _project: Entity<Project>,
14449                _pane: Option<&Pane>,
14450                _item: Entity<Self::Item>,
14451                _: &mut Window,
14452                cx: &mut Context<Self>,
14453            ) -> Self
14454            where
14455                Self: Sized,
14456            {
14457                Self {
14458                    focus_handle: cx.focus_handle(),
14459                }
14460            }
14461        }
14462
14463        // View
14464        struct TestIpynbItemView {
14465            focus_handle: FocusHandle,
14466        }
14467        // Model
14468        struct TestIpynbItem {}
14469
14470        impl project::ProjectItem for TestIpynbItem {
14471            fn try_open(
14472                _project: &Entity<Project>,
14473                path: &ProjectPath,
14474                cx: &mut App,
14475            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14476                if path.path.extension().unwrap() == "ipynb" {
14477                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14478                } else {
14479                    None
14480                }
14481            }
14482
14483            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14484                None
14485            }
14486
14487            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14488                None
14489            }
14490
14491            fn is_dirty(&self) -> bool {
14492                false
14493            }
14494        }
14495
14496        impl Item for TestIpynbItemView {
14497            type Event = ();
14498            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14499                "".into()
14500            }
14501        }
14502        impl EventEmitter<()> for TestIpynbItemView {}
14503        impl Focusable for TestIpynbItemView {
14504            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14505                self.focus_handle.clone()
14506            }
14507        }
14508
14509        impl Render for TestIpynbItemView {
14510            fn render(
14511                &mut self,
14512                _window: &mut Window,
14513                _cx: &mut Context<Self>,
14514            ) -> impl IntoElement {
14515                Empty
14516            }
14517        }
14518
14519        impl ProjectItem for TestIpynbItemView {
14520            type Item = TestIpynbItem;
14521
14522            fn for_project_item(
14523                _project: Entity<Project>,
14524                _pane: Option<&Pane>,
14525                _item: Entity<Self::Item>,
14526                _: &mut Window,
14527                cx: &mut Context<Self>,
14528            ) -> Self
14529            where
14530                Self: Sized,
14531            {
14532                Self {
14533                    focus_handle: cx.focus_handle(),
14534                }
14535            }
14536        }
14537
14538        struct TestAlternatePngItemView {
14539            focus_handle: FocusHandle,
14540        }
14541
14542        impl Item for TestAlternatePngItemView {
14543            type Event = ();
14544            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14545                "".into()
14546            }
14547        }
14548
14549        impl EventEmitter<()> for TestAlternatePngItemView {}
14550        impl Focusable for TestAlternatePngItemView {
14551            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14552                self.focus_handle.clone()
14553            }
14554        }
14555
14556        impl Render for TestAlternatePngItemView {
14557            fn render(
14558                &mut self,
14559                _window: &mut Window,
14560                _cx: &mut Context<Self>,
14561            ) -> impl IntoElement {
14562                Empty
14563            }
14564        }
14565
14566        impl ProjectItem for TestAlternatePngItemView {
14567            type Item = TestPngItem;
14568
14569            fn for_project_item(
14570                _project: Entity<Project>,
14571                _pane: Option<&Pane>,
14572                _item: Entity<Self::Item>,
14573                _: &mut Window,
14574                cx: &mut Context<Self>,
14575            ) -> Self
14576            where
14577                Self: Sized,
14578            {
14579                Self {
14580                    focus_handle: cx.focus_handle(),
14581                }
14582            }
14583        }
14584
14585        #[gpui::test]
14586        async fn test_register_project_item(cx: &mut TestAppContext) {
14587            init_test(cx);
14588
14589            cx.update(|cx| {
14590                register_project_item::<TestPngItemView>(cx);
14591                register_project_item::<TestIpynbItemView>(cx);
14592            });
14593
14594            let fs = FakeFs::new(cx.executor());
14595            fs.insert_tree(
14596                "/root1",
14597                json!({
14598                    "one.png": "BINARYDATAHERE",
14599                    "two.ipynb": "{ totally a notebook }",
14600                    "three.txt": "editing text, sure why not?"
14601                }),
14602            )
14603            .await;
14604
14605            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14606            let (workspace, cx) =
14607                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14608
14609            let worktree_id = project.update(cx, |project, cx| {
14610                project.worktrees(cx).next().unwrap().read(cx).id()
14611            });
14612
14613            let handle = workspace
14614                .update_in(cx, |workspace, window, cx| {
14615                    let project_path = (worktree_id, rel_path("one.png"));
14616                    workspace.open_path(project_path, None, true, window, cx)
14617                })
14618                .await
14619                .unwrap();
14620
14621            // Now we can check if the handle we got back errored or not
14622            assert_eq!(
14623                handle.to_any_view().entity_type(),
14624                TypeId::of::<TestPngItemView>()
14625            );
14626
14627            let handle = workspace
14628                .update_in(cx, |workspace, window, cx| {
14629                    let project_path = (worktree_id, rel_path("two.ipynb"));
14630                    workspace.open_path(project_path, None, true, window, cx)
14631                })
14632                .await
14633                .unwrap();
14634
14635            assert_eq!(
14636                handle.to_any_view().entity_type(),
14637                TypeId::of::<TestIpynbItemView>()
14638            );
14639
14640            let handle = workspace
14641                .update_in(cx, |workspace, window, cx| {
14642                    let project_path = (worktree_id, rel_path("three.txt"));
14643                    workspace.open_path(project_path, None, true, window, cx)
14644                })
14645                .await;
14646            assert!(handle.is_err());
14647        }
14648
14649        #[gpui::test]
14650        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14651            init_test(cx);
14652
14653            cx.update(|cx| {
14654                register_project_item::<TestPngItemView>(cx);
14655                register_project_item::<TestAlternatePngItemView>(cx);
14656            });
14657
14658            let fs = FakeFs::new(cx.executor());
14659            fs.insert_tree(
14660                "/root1",
14661                json!({
14662                    "one.png": "BINARYDATAHERE",
14663                    "two.ipynb": "{ totally a notebook }",
14664                    "three.txt": "editing text, sure why not?"
14665                }),
14666            )
14667            .await;
14668            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14669            let (workspace, cx) =
14670                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14671            let worktree_id = project.update(cx, |project, cx| {
14672                project.worktrees(cx).next().unwrap().read(cx).id()
14673            });
14674
14675            let handle = workspace
14676                .update_in(cx, |workspace, window, cx| {
14677                    let project_path = (worktree_id, rel_path("one.png"));
14678                    workspace.open_path(project_path, None, true, window, cx)
14679                })
14680                .await
14681                .unwrap();
14682
14683            // This _must_ be the second item registered
14684            assert_eq!(
14685                handle.to_any_view().entity_type(),
14686                TypeId::of::<TestAlternatePngItemView>()
14687            );
14688
14689            let handle = workspace
14690                .update_in(cx, |workspace, window, cx| {
14691                    let project_path = (worktree_id, rel_path("three.txt"));
14692                    workspace.open_path(project_path, None, true, window, cx)
14693                })
14694                .await;
14695            assert!(handle.is_err());
14696        }
14697    }
14698
14699    #[gpui::test]
14700    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14701        init_test(cx);
14702
14703        let fs = FakeFs::new(cx.executor());
14704        let project = Project::test(fs, [], cx).await;
14705        let (workspace, _cx) =
14706            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14707
14708        // Test with status bar shown (default)
14709        workspace.read_with(cx, |workspace, cx| {
14710            let visible = workspace.status_bar_visible(cx);
14711            assert!(visible, "Status bar should be visible by default");
14712        });
14713
14714        // Test with status bar hidden
14715        cx.update_global(|store: &mut SettingsStore, cx| {
14716            store.update_user_settings(cx, |settings| {
14717                settings.status_bar.get_or_insert_default().show = Some(false);
14718            });
14719        });
14720
14721        workspace.read_with(cx, |workspace, cx| {
14722            let visible = workspace.status_bar_visible(cx);
14723            assert!(!visible, "Status bar should be hidden when show is false");
14724        });
14725
14726        // Test with status bar shown explicitly
14727        cx.update_global(|store: &mut SettingsStore, cx| {
14728            store.update_user_settings(cx, |settings| {
14729                settings.status_bar.get_or_insert_default().show = Some(true);
14730            });
14731        });
14732
14733        workspace.read_with(cx, |workspace, cx| {
14734            let visible = workspace.status_bar_visible(cx);
14735            assert!(visible, "Status bar should be visible when show is true");
14736        });
14737    }
14738
14739    #[gpui::test]
14740    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14741        init_test(cx);
14742
14743        let fs = FakeFs::new(cx.executor());
14744        let project = Project::test(fs, [], cx).await;
14745        let (multi_workspace, cx) =
14746            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14747        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14748        let panel = workspace.update_in(cx, |workspace, window, cx| {
14749            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14750            workspace.add_panel(panel.clone(), window, cx);
14751
14752            workspace
14753                .right_dock()
14754                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14755
14756            panel
14757        });
14758
14759        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14760        let item_a = cx.new(TestItem::new);
14761        let item_b = cx.new(TestItem::new);
14762        let item_a_id = item_a.entity_id();
14763        let item_b_id = item_b.entity_id();
14764
14765        pane.update_in(cx, |pane, window, cx| {
14766            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14767            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14768        });
14769
14770        pane.read_with(cx, |pane, _| {
14771            assert_eq!(pane.items_len(), 2);
14772            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14773        });
14774
14775        workspace.update_in(cx, |workspace, window, cx| {
14776            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14777        });
14778
14779        workspace.update_in(cx, |_, window, cx| {
14780            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14781        });
14782
14783        // Assert that the `pane::CloseActiveItem` action is handled at the
14784        // workspace level when one of the dock panels is focused and, in that
14785        // case, the center pane's active item is closed but the focus is not
14786        // moved.
14787        cx.dispatch_action(pane::CloseActiveItem::default());
14788        cx.run_until_parked();
14789
14790        pane.read_with(cx, |pane, _| {
14791            assert_eq!(pane.items_len(), 1);
14792            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14793        });
14794
14795        workspace.update_in(cx, |workspace, window, cx| {
14796            assert!(workspace.right_dock().read(cx).is_open());
14797            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14798        });
14799    }
14800
14801    #[gpui::test]
14802    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14803        init_test(cx);
14804        let fs = FakeFs::new(cx.executor());
14805
14806        let project_a = Project::test(fs.clone(), [], cx).await;
14807        let project_b = Project::test(fs, [], cx).await;
14808
14809        let multi_workspace_handle =
14810            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14811        cx.run_until_parked();
14812
14813        multi_workspace_handle
14814            .update(cx, |mw, _window, cx| {
14815                mw.open_sidebar(cx);
14816            })
14817            .unwrap();
14818
14819        let workspace_a = multi_workspace_handle
14820            .read_with(cx, |mw, _| mw.workspace().clone())
14821            .unwrap();
14822
14823        let _workspace_b = multi_workspace_handle
14824            .update(cx, |mw, window, cx| {
14825                mw.test_add_workspace(project_b, window, cx)
14826            })
14827            .unwrap();
14828
14829        // Switch to workspace A
14830        multi_workspace_handle
14831            .update(cx, |mw, window, cx| {
14832                let workspace = mw.workspaces().next().unwrap().clone();
14833                mw.activate(workspace, window, cx);
14834            })
14835            .unwrap();
14836
14837        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14838
14839        // Add a panel to workspace A's right dock and open the dock
14840        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14841            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14842            workspace.add_panel(panel.clone(), window, cx);
14843            workspace
14844                .right_dock()
14845                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14846            panel
14847        });
14848
14849        // Focus the panel through the workspace (matching existing test pattern)
14850        workspace_a.update_in(cx, |workspace, window, cx| {
14851            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14852        });
14853
14854        // Zoom the panel
14855        panel.update_in(cx, |panel, window, cx| {
14856            panel.set_zoomed(true, window, cx);
14857        });
14858
14859        // Verify the panel is zoomed and the dock is open
14860        workspace_a.update_in(cx, |workspace, window, cx| {
14861            assert!(
14862                workspace.right_dock().read(cx).is_open(),
14863                "dock should be open before switch"
14864            );
14865            assert!(
14866                panel.is_zoomed(window, cx),
14867                "panel should be zoomed before switch"
14868            );
14869            assert!(
14870                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14871                "panel should be focused before switch"
14872            );
14873        });
14874
14875        // Switch to workspace B
14876        multi_workspace_handle
14877            .update(cx, |mw, window, cx| {
14878                let workspace = mw.workspaces().nth(1).unwrap().clone();
14879                mw.activate(workspace, window, cx);
14880            })
14881            .unwrap();
14882        cx.run_until_parked();
14883
14884        // Switch back to workspace A
14885        multi_workspace_handle
14886            .update(cx, |mw, window, cx| {
14887                let workspace = mw.workspaces().next().unwrap().clone();
14888                mw.activate(workspace, window, cx);
14889            })
14890            .unwrap();
14891        cx.run_until_parked();
14892
14893        // Verify the panel is still zoomed and the dock is still open
14894        workspace_a.update_in(cx, |workspace, window, cx| {
14895            assert!(
14896                workspace.right_dock().read(cx).is_open(),
14897                "dock should still be open after switching back"
14898            );
14899            assert!(
14900                panel.is_zoomed(window, cx),
14901                "panel should still be zoomed after switching back"
14902            );
14903        });
14904    }
14905
14906    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14907        pane.read(cx)
14908            .items()
14909            .flat_map(|item| {
14910                item.project_paths(cx)
14911                    .into_iter()
14912                    .map(|path| path.path.display(PathStyle::local()).into_owned())
14913            })
14914            .collect()
14915    }
14916
14917    pub fn init_test(cx: &mut TestAppContext) {
14918        cx.update(|cx| {
14919            let settings_store = SettingsStore::test(cx);
14920            cx.set_global(settings_store);
14921            cx.set_global(db::AppDatabase::test_new());
14922            theme_settings::init(theme::LoadThemes::JustBase, cx);
14923        });
14924    }
14925
14926    #[gpui::test]
14927    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14928        use settings::{ThemeName, ThemeSelection};
14929        use theme::SystemAppearance;
14930        use zed_actions::theme::ToggleMode;
14931
14932        init_test(cx);
14933
14934        let fs = FakeFs::new(cx.executor());
14935        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14936
14937        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14938            .await;
14939
14940        // Build a test project and workspace view so the test can invoke
14941        // the workspace action handler the same way the UI would.
14942        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14943        let (workspace, cx) =
14944            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14945
14946        // Seed the settings file with a plain static light theme so the
14947        // first toggle always starts from a known persisted state.
14948        workspace.update_in(cx, |_workspace, _window, cx| {
14949            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14950            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14951                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14952            });
14953        });
14954        cx.executor().advance_clock(Duration::from_millis(200));
14955        cx.run_until_parked();
14956
14957        // Confirm the initial persisted settings contain the static theme
14958        // we just wrote before any toggling happens.
14959        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14960        assert!(settings_text.contains(r#""theme": "One Light""#));
14961
14962        // Toggle once. This should migrate the persisted theme settings
14963        // into light/dark slots and enable system mode.
14964        workspace.update_in(cx, |workspace, window, cx| {
14965            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14966        });
14967        cx.executor().advance_clock(Duration::from_millis(200));
14968        cx.run_until_parked();
14969
14970        // 1. Static -> Dynamic
14971        // this assertion checks theme changed from static to dynamic.
14972        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14973        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14974        assert_eq!(
14975            parsed["theme"],
14976            serde_json::json!({
14977                "mode": "system",
14978                "light": "One Light",
14979                "dark": "One Dark"
14980            })
14981        );
14982
14983        // 2. Toggle again, suppose it will change the mode to light
14984        workspace.update_in(cx, |workspace, window, cx| {
14985            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14986        });
14987        cx.executor().advance_clock(Duration::from_millis(200));
14988        cx.run_until_parked();
14989
14990        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14991        assert!(settings_text.contains(r#""mode": "light""#));
14992    }
14993
14994    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14995        let item = TestProjectItem::new(id, path, cx);
14996        item.update(cx, |item, _| {
14997            item.is_dirty = true;
14998        });
14999        item
15000    }
15001
15002    #[gpui::test]
15003    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
15004        cx: &mut gpui::TestAppContext,
15005    ) {
15006        init_test(cx);
15007        let fs = FakeFs::new(cx.executor());
15008
15009        let project = Project::test(fs, [], cx).await;
15010        let (workspace, cx) =
15011            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
15012
15013        let panel = workspace.update_in(cx, |workspace, window, cx| {
15014            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
15015            workspace.add_panel(panel.clone(), window, cx);
15016            workspace
15017                .right_dock()
15018                .update(cx, |dock, cx| dock.set_open(true, window, cx));
15019            panel
15020        });
15021
15022        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
15023        pane.update_in(cx, |pane, window, cx| {
15024            let item = cx.new(TestItem::new);
15025            pane.add_item(Box::new(item), true, true, None, window, cx);
15026        });
15027
15028        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
15029        // mirrors the real-world flow and avoids side effects from directly
15030        // focusing the panel while the center pane is active.
15031        workspace.update_in(cx, |workspace, window, cx| {
15032            workspace.toggle_panel_focus::<TestPanel>(window, cx);
15033        });
15034
15035        panel.update_in(cx, |panel, window, cx| {
15036            panel.set_zoomed(true, window, cx);
15037        });
15038
15039        workspace.update_in(cx, |workspace, window, cx| {
15040            assert!(workspace.right_dock().read(cx).is_open());
15041            assert!(panel.is_zoomed(window, cx));
15042            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
15043        });
15044
15045        // Simulate a spurious pane::Event::Focus on the center pane while the
15046        // panel still has focus. This mirrors what happens during macOS window
15047        // activation: the center pane fires a focus event even though actual
15048        // focus remains on the dock panel.
15049        pane.update_in(cx, |_, _, cx| {
15050            cx.emit(pane::Event::Focus);
15051        });
15052
15053        // The dock must remain open because the panel had focus at the time the
15054        // event was processed. Before the fix, dock_to_preserve was None for
15055        // panels that don't implement pane(), causing the dock to close.
15056        workspace.update_in(cx, |workspace, window, cx| {
15057            assert!(
15058                workspace.right_dock().read(cx).is_open(),
15059                "Dock should stay open when its zoomed panel (without pane()) still has focus"
15060            );
15061            assert!(panel.is_zoomed(window, cx));
15062        });
15063    }
15064
15065    #[gpui::test]
15066    async fn test_panels_stay_open_after_position_change_and_settings_update(
15067        cx: &mut gpui::TestAppContext,
15068    ) {
15069        init_test(cx);
15070        let fs = FakeFs::new(cx.executor());
15071        let project = Project::test(fs, [], cx).await;
15072        let (workspace, cx) =
15073            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
15074
15075        // Add two panels to the left dock and open it.
15076        let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
15077            let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
15078            let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
15079            workspace.add_panel(panel_a.clone(), window, cx);
15080            workspace.add_panel(panel_b.clone(), window, cx);
15081            workspace.left_dock().update(cx, |dock, cx| {
15082                dock.set_open(true, window, cx);
15083                dock.activate_panel(0, window, cx);
15084            });
15085            (panel_a, panel_b)
15086        });
15087
15088        workspace.update_in(cx, |workspace, _, cx| {
15089            assert!(workspace.left_dock().read(cx).is_open());
15090        });
15091
15092        // Simulate a feature flag changing default dock positions: both panels
15093        // move from Left to Right.
15094        workspace.update_in(cx, |_workspace, _window, cx| {
15095            panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
15096            panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
15097            cx.update_global::<SettingsStore, _>(|_, _| {});
15098        });
15099
15100        // Both panels should now be in the right dock.
15101        workspace.update_in(cx, |workspace, _, cx| {
15102            let right_dock = workspace.right_dock().read(cx);
15103            assert_eq!(right_dock.panels_len(), 2);
15104        });
15105
15106        // Open the right dock and activate panel_b (simulating the user
15107        // opening the panel after it moved).
15108        workspace.update_in(cx, |workspace, window, cx| {
15109            workspace.right_dock().update(cx, |dock, cx| {
15110                dock.set_open(true, window, cx);
15111                dock.activate_panel(1, window, cx);
15112            });
15113        });
15114
15115        // Now trigger another SettingsStore change
15116        workspace.update_in(cx, |_workspace, _window, cx| {
15117            cx.update_global::<SettingsStore, _>(|_, _| {});
15118        });
15119
15120        workspace.update_in(cx, |workspace, _, cx| {
15121            assert!(
15122                workspace.right_dock().read(cx).is_open(),
15123                "Right dock should still be open after a settings change"
15124            );
15125            assert_eq!(
15126                workspace.right_dock().read(cx).panels_len(),
15127                2,
15128                "Both panels should still be in the right dock"
15129            );
15130        });
15131    }
15132}