workspace.rs

    1pub mod active_file_name;
    2pub mod dock;
    3pub mod history_manager;
    4pub mod invalid_item_view;
    5pub mod item;
    6mod modal_layer;
    7mod multi_workspace;
    8#[cfg(test)]
    9mod multi_workspace_tests;
   10pub mod notifications;
   11pub mod pane;
   12pub mod pane_group;
   13pub mod path_list {
   14    pub use util::path_list::{PathList, SerializedPathList};
   15}
   16mod persistence;
   17pub mod searchable;
   18mod security_modal;
   19pub mod shared_screen;
   20use db::smol::future::yield_now;
   21pub use shared_screen::SharedScreen;
   22pub mod focus_follows_mouse;
   23mod status_bar;
   24pub mod tasks;
   25mod theme_preview;
   26mod toast_layer;
   27mod toolbar;
   28pub mod welcome;
   29mod workspace_settings;
   30
   31pub use crate::notifications::NotificationFrame;
   32pub use dock::Panel;
   33pub use multi_workspace::{
   34    CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MoveProjectToNewWindow,
   35    MultiWorkspace, MultiWorkspaceEvent, NewThread, NextProject, NextThread, PreviousProject,
   36    PreviousThread, ProjectGroup, ProjectGroupKey, SerializedProjectGroupState, ShowFewerThreads,
   37    ShowMoreThreads, Sidebar, SidebarEvent, SidebarHandle, SidebarRenderState, SidebarSide,
   38    ToggleWorkspaceSidebar, sidebar_side_context_menu,
   39};
   40pub use path_list::{PathList, SerializedPathList};
   41pub use remote::{
   42    RemoteConnectionIdentity, remote_connection_identity, same_remote_connection_identity,
   43};
   44pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   45
   46use anyhow::{Context as _, Result, anyhow};
   47use client::{
   48    ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
   49    proto::{self, ErrorCode, PanelId, PeerId},
   50};
   51use collections::{HashMap, HashSet, hash_map};
   52use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   53use fs::Fs;
   54use futures::{
   55    Future, FutureExt, StreamExt,
   56    channel::{
   57        mpsc::{self, UnboundedReceiver, UnboundedSender},
   58        oneshot,
   59    },
   60    future::{Shared, try_join_all},
   61};
   62use gpui::{
   63    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
   64    Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   65    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   66    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   67    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   68    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   69};
   70pub use history_manager::*;
   71pub use item::{
   72    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   73    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   74};
   75use itertools::Itertools;
   76use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   77pub use modal_layer::*;
   78use node_runtime::NodeRuntime;
   79use notifications::{
   80    DetachAndPromptErr, Notifications, dismiss_app_notification,
   81    simple_message_notification::MessageNotification,
   82};
   83pub use pane::*;
   84pub use pane_group::{
   85    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   86    SplitDirection,
   87};
   88use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
   89pub use persistence::{
   90    WorkspaceDb, delete_unloaded_items,
   91    model::{
   92        DockData, DockStructure, ItemId, MultiWorkspaceState, SerializedMultiWorkspace,
   93        SerializedProjectGroup, SerializedWorkspaceLocation, SessionWorkspace,
   94    },
   95    read_serialized_multi_workspaces, resolve_worktree_workspaces,
   96};
   97use postage::stream::Stream;
   98use project::{
   99    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
  100    WorktreeSettings,
  101    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
  102    project_settings::ProjectSettings,
  103    toolchain_store::ToolchainStoreEvent,
  104    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
  105};
  106use remote::{
  107    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
  108    remote_client::ConnectionIdentifier,
  109};
  110use schemars::JsonSchema;
  111use serde::Deserialize;
  112use session::AppSession;
  113use settings::{
  114    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  115};
  116
  117use sqlez::{
  118    bindable::{Bind, Column, StaticColumnCount},
  119    statement::Statement,
  120};
  121use status_bar::StatusBar;
  122pub use status_bar::StatusItemView;
  123use std::{
  124    any::TypeId,
  125    borrow::Cow,
  126    cell::RefCell,
  127    cmp,
  128    collections::VecDeque,
  129    env,
  130    hash::Hash,
  131    path::{Path, PathBuf},
  132    process::ExitStatus,
  133    rc::Rc,
  134    sync::{
  135        Arc, LazyLock,
  136        atomic::{AtomicBool, AtomicUsize},
  137    },
  138    time::Duration,
  139};
  140use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  141use theme::{ActiveTheme, SystemAppearance};
  142use theme_settings::ThemeSettings;
  143pub use toolbar::{
  144    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  145};
  146pub use ui;
  147use ui::{Window, prelude::*};
  148use util::{
  149    ResultExt, TryFutureExt,
  150    paths::{PathStyle, SanitizedPath},
  151    rel_path::RelPath,
  152    serde::default_true,
  153};
  154use uuid::Uuid;
  155pub use workspace_settings::{
  156    AutosaveSetting, BottomDockLayout, FocusFollowsMouse, RestoreOnStartupBehavior,
  157    StatusBarSettings, TabBarSettings, WorkspaceSettings,
  158};
  159use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
  160
  161use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::NotificationId};
  162use crate::{
  163    persistence::{
  164        SerializedAxis,
  165        model::{SerializedItem, SerializedPane, SerializedPaneGroup},
  166    },
  167    security_modal::SecurityModal,
  168};
  169
  170pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  171
  172static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  173    env::var("ZED_WINDOW_SIZE")
  174        .ok()
  175        .as_deref()
  176        .and_then(parse_pixel_size_env_var)
  177});
  178
  179static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  180    env::var("ZED_WINDOW_POSITION")
  181        .ok()
  182        .as_deref()
  183        .and_then(parse_pixel_position_env_var)
  184});
  185
  186pub trait TerminalProvider {
  187    fn spawn(
  188        &self,
  189        task: SpawnInTerminal,
  190        window: &mut Window,
  191        cx: &mut App,
  192    ) -> Task<Option<Result<ExitStatus>>>;
  193}
  194
  195pub trait DebuggerProvider {
  196    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  197    fn start_session(
  198        &self,
  199        definition: DebugScenario,
  200        task_context: SharedTaskContext,
  201        active_buffer: Option<Entity<Buffer>>,
  202        worktree_id: Option<WorktreeId>,
  203        window: &mut Window,
  204        cx: &mut App,
  205    );
  206
  207    fn spawn_task_or_modal(
  208        &self,
  209        workspace: &mut Workspace,
  210        action: &Spawn,
  211        window: &mut Window,
  212        cx: &mut Context<Workspace>,
  213    );
  214
  215    fn task_scheduled(&self, cx: &mut App);
  216    fn debug_scenario_scheduled(&self, cx: &mut App);
  217    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  218
  219    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  220}
  221
  222/// Opens a file or directory.
  223#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  224#[action(namespace = workspace)]
  225pub struct Open {
  226    /// When true, opens in a new window. When false, adds to the current
  227    /// window as a new workspace (multi-workspace).
  228    #[serde(default = "Open::default_create_new_window")]
  229    pub create_new_window: bool,
  230}
  231
  232impl Open {
  233    pub const DEFAULT: Self = Self {
  234        create_new_window: true,
  235    };
  236
  237    /// Used by `#[serde(default)]` on the `create_new_window` field so that
  238    /// the serde default and `Open::DEFAULT` stay in sync.
  239    fn default_create_new_window() -> bool {
  240        Self::DEFAULT.create_new_window
  241    }
  242}
  243
  244impl Default for Open {
  245    fn default() -> Self {
  246        Self::DEFAULT
  247    }
  248}
  249
  250actions!(
  251    workspace,
  252    [
  253        /// Activates the next pane in the workspace.
  254        ActivateNextPane,
  255        /// Activates the previous pane in the workspace.
  256        ActivatePreviousPane,
  257        /// Activates the last pane in the workspace.
  258        ActivateLastPane,
  259        /// Switches to the next window.
  260        ActivateNextWindow,
  261        /// Switches to the previous window.
  262        ActivatePreviousWindow,
  263        /// Adds a folder to the current project.
  264        AddFolderToProject,
  265        /// Clears all notifications.
  266        ClearAllNotifications,
  267        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  268        ClearNavigationHistory,
  269        /// Closes the active dock.
  270        CloseActiveDock,
  271        /// Closes all docks.
  272        CloseAllDocks,
  273        /// Toggles all docks.
  274        ToggleAllDocks,
  275        /// Closes the current window.
  276        CloseWindow,
  277        /// Closes the current project.
  278        CloseProject,
  279        /// Opens the feedback dialog.
  280        Feedback,
  281        /// Follows the next collaborator in the session.
  282        FollowNextCollaborator,
  283        /// Moves the focused panel to the next position.
  284        MoveFocusedPanelToNextPosition,
  285        /// Creates a new file.
  286        NewFile,
  287        /// Creates a new file in a vertical split.
  288        NewFileSplitVertical,
  289        /// Creates a new file in a horizontal split.
  290        NewFileSplitHorizontal,
  291        /// Opens a new search.
  292        NewSearch,
  293        /// Opens a new window.
  294        NewWindow,
  295        /// Opens multiple files.
  296        OpenFiles,
  297        /// Opens the current location in terminal.
  298        OpenInTerminal,
  299        /// Opens the component preview.
  300        OpenComponentPreview,
  301        /// Reloads the active item.
  302        ReloadActiveItem,
  303        /// Resets the active dock to its default size.
  304        ResetActiveDockSize,
  305        /// Resets all open docks to their default sizes.
  306        ResetOpenDocksSize,
  307        /// Reloads the application
  308        Reload,
  309        /// Formats and saves the current file, regardless of the format_on_save setting.
  310        FormatAndSave,
  311        /// Saves the current file with a new name.
  312        SaveAs,
  313        /// Saves without formatting.
  314        SaveWithoutFormat,
  315        /// Shuts down all debug adapters.
  316        ShutdownDebugAdapters,
  317        /// Suppresses the current notification.
  318        SuppressNotification,
  319        /// Toggles the bottom dock.
  320        ToggleBottomDock,
  321        /// Toggles centered layout mode.
  322        ToggleCenteredLayout,
  323        /// Toggles edit prediction feature globally for all files.
  324        ToggleEditPrediction,
  325        /// Toggles the left dock.
  326        ToggleLeftDock,
  327        /// Toggles the right dock.
  328        ToggleRightDock,
  329        /// Toggles zoom on the active pane.
  330        ToggleZoom,
  331        /// Toggles read-only mode for the active item (if supported by that item).
  332        ToggleReadOnlyFile,
  333        /// Zooms in on the active pane.
  334        ZoomIn,
  335        /// Zooms out of the active pane.
  336        ZoomOut,
  337        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  338        /// If the modal is shown already, closes it without trusting any worktree.
  339        ToggleWorktreeSecurity,
  340        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  341        /// Requires restart to take effect on already opened projects.
  342        ClearTrustedWorktrees,
  343        /// Stops following a collaborator.
  344        Unfollow,
  345        /// Restores the banner.
  346        RestoreBanner,
  347        /// Toggles expansion of the selected item.
  348        ToggleExpandItem,
  349    ]
  350);
  351
  352/// Activates a specific pane by its index.
  353#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  354#[action(namespace = workspace)]
  355pub struct ActivatePane(pub usize);
  356
  357/// Moves an item to a specific pane by index.
  358#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  359#[action(namespace = workspace)]
  360#[serde(deny_unknown_fields)]
  361pub struct MoveItemToPane {
  362    #[serde(default = "default_1")]
  363    pub destination: usize,
  364    #[serde(default = "default_true")]
  365    pub focus: bool,
  366    #[serde(default)]
  367    pub clone: bool,
  368}
  369
  370fn default_1() -> usize {
  371    1
  372}
  373
  374/// Moves an item to a pane in the specified direction.
  375#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  376#[action(namespace = workspace)]
  377#[serde(deny_unknown_fields)]
  378pub struct MoveItemToPaneInDirection {
  379    #[serde(default = "default_right")]
  380    pub direction: SplitDirection,
  381    #[serde(default = "default_true")]
  382    pub focus: bool,
  383    #[serde(default)]
  384    pub clone: bool,
  385}
  386
  387/// Creates a new file in a split of the desired direction.
  388#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  389#[action(namespace = workspace)]
  390#[serde(deny_unknown_fields)]
  391pub struct NewFileSplit(pub SplitDirection);
  392
  393fn default_right() -> SplitDirection {
  394    SplitDirection::Right
  395}
  396
  397/// Saves all open files in the workspace.
  398#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  399#[action(namespace = workspace)]
  400#[serde(deny_unknown_fields)]
  401pub struct SaveAll {
  402    #[serde(default)]
  403    pub save_intent: Option<SaveIntent>,
  404}
  405
  406/// Saves the current file with the specified options.
  407#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  408#[action(namespace = workspace)]
  409#[serde(deny_unknown_fields)]
  410pub struct Save {
  411    #[serde(default)]
  412    pub save_intent: Option<SaveIntent>,
  413}
  414
  415/// Moves Focus to the central panes in the workspace.
  416#[derive(Clone, Debug, PartialEq, Eq, Action)]
  417#[action(namespace = workspace)]
  418pub struct FocusCenterPane;
  419
  420///  Closes all items and panes in the workspace.
  421#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  422#[action(namespace = workspace)]
  423#[serde(deny_unknown_fields)]
  424pub struct CloseAllItemsAndPanes {
  425    #[serde(default)]
  426    pub save_intent: Option<SaveIntent>,
  427}
  428
  429/// Closes all inactive tabs and panes in the workspace.
  430#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  431#[action(namespace = workspace)]
  432#[serde(deny_unknown_fields)]
  433pub struct CloseInactiveTabsAndPanes {
  434    #[serde(default)]
  435    pub save_intent: Option<SaveIntent>,
  436}
  437
  438/// Closes the active item across all panes.
  439#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  440#[action(namespace = workspace)]
  441#[serde(deny_unknown_fields)]
  442pub struct CloseItemInAllPanes {
  443    #[serde(default)]
  444    pub save_intent: Option<SaveIntent>,
  445    #[serde(default)]
  446    pub close_pinned: bool,
  447}
  448
  449/// Sends a sequence of keystrokes to the active element.
  450#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  451#[action(namespace = workspace)]
  452pub struct SendKeystrokes(pub String);
  453
  454actions!(
  455    project_symbols,
  456    [
  457        /// Toggles the project symbols search.
  458        #[action(name = "Toggle")]
  459        ToggleProjectSymbols
  460    ]
  461);
  462
  463/// Toggles the file finder interface.
  464#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  465#[action(namespace = file_finder, name = "Toggle")]
  466#[serde(deny_unknown_fields)]
  467pub struct ToggleFileFinder {
  468    #[serde(default)]
  469    pub separate_history: bool,
  470}
  471
  472/// Opens a new terminal in the center.
  473#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  474#[action(namespace = workspace)]
  475#[serde(deny_unknown_fields)]
  476pub struct NewCenterTerminal {
  477    /// If true, creates a local terminal even in remote projects.
  478    #[serde(default)]
  479    pub local: bool,
  480}
  481
  482/// Opens a new terminal.
  483#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  484#[action(namespace = workspace)]
  485#[serde(deny_unknown_fields)]
  486pub struct NewTerminal {
  487    /// If true, creates a local terminal even in remote projects.
  488    #[serde(default)]
  489    pub local: bool,
  490}
  491
  492/// Increases size of a currently focused dock by a given amount of pixels.
  493#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  494#[action(namespace = workspace)]
  495#[serde(deny_unknown_fields)]
  496pub struct IncreaseActiveDockSize {
  497    /// For 0px parameter, uses UI font size value.
  498    #[serde(default)]
  499    pub px: u32,
  500}
  501
  502/// Decreases size of a currently focused dock by a given amount of pixels.
  503#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  504#[action(namespace = workspace)]
  505#[serde(deny_unknown_fields)]
  506pub struct DecreaseActiveDockSize {
  507    /// For 0px parameter, uses UI font size value.
  508    #[serde(default)]
  509    pub px: u32,
  510}
  511
  512/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  513#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  514#[action(namespace = workspace)]
  515#[serde(deny_unknown_fields)]
  516pub struct IncreaseOpenDocksSize {
  517    /// For 0px parameter, uses UI font size value.
  518    #[serde(default)]
  519    pub px: u32,
  520}
  521
  522/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  523#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  524#[action(namespace = workspace)]
  525#[serde(deny_unknown_fields)]
  526pub struct DecreaseOpenDocksSize {
  527    /// For 0px parameter, uses UI font size value.
  528    #[serde(default)]
  529    pub px: u32,
  530}
  531
  532actions!(
  533    workspace,
  534    [
  535        /// Activates the pane to the left.
  536        ActivatePaneLeft,
  537        /// Activates the pane to the right.
  538        ActivatePaneRight,
  539        /// Activates the pane above.
  540        ActivatePaneUp,
  541        /// Activates the pane below.
  542        ActivatePaneDown,
  543        /// Swaps the current pane with the one to the left.
  544        SwapPaneLeft,
  545        /// Swaps the current pane with the one to the right.
  546        SwapPaneRight,
  547        /// Swaps the current pane with the one above.
  548        SwapPaneUp,
  549        /// Swaps the current pane with the one below.
  550        SwapPaneDown,
  551        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  552        SwapPaneAdjacent,
  553        /// Move the current pane to be at the far left.
  554        MovePaneLeft,
  555        /// Move the current pane to be at the far right.
  556        MovePaneRight,
  557        /// Move the current pane to be at the very top.
  558        MovePaneUp,
  559        /// Move the current pane to be at the very bottom.
  560        MovePaneDown,
  561    ]
  562);
  563
  564#[derive(PartialEq, Eq, Debug)]
  565pub enum CloseIntent {
  566    /// Quit the program entirely.
  567    Quit,
  568    /// Close a window.
  569    CloseWindow,
  570    /// Replace the workspace in an existing window.
  571    ReplaceWindow,
  572}
  573
  574#[derive(Clone)]
  575pub struct Toast {
  576    id: NotificationId,
  577    msg: Cow<'static, str>,
  578    autohide: bool,
  579    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  580}
  581
  582impl Toast {
  583    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  584        Toast {
  585            id,
  586            msg: msg.into(),
  587            on_click: None,
  588            autohide: false,
  589        }
  590    }
  591
  592    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  593    where
  594        M: Into<Cow<'static, str>>,
  595        F: Fn(&mut Window, &mut App) + 'static,
  596    {
  597        self.on_click = Some((message.into(), Arc::new(on_click)));
  598        self
  599    }
  600
  601    pub fn autohide(mut self) -> Self {
  602        self.autohide = true;
  603        self
  604    }
  605}
  606
  607impl PartialEq for Toast {
  608    fn eq(&self, other: &Self) -> bool {
  609        self.id == other.id
  610            && self.msg == other.msg
  611            && self.on_click.is_some() == other.on_click.is_some()
  612    }
  613}
  614
  615/// Opens a new terminal with the specified working directory.
  616#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  617#[action(namespace = workspace)]
  618#[serde(deny_unknown_fields)]
  619pub struct OpenTerminal {
  620    pub working_directory: PathBuf,
  621    /// If true, creates a local terminal even in remote projects.
  622    #[serde(default)]
  623    pub local: bool,
  624}
  625
  626#[derive(
  627    Clone,
  628    Copy,
  629    Debug,
  630    Default,
  631    Hash,
  632    PartialEq,
  633    Eq,
  634    PartialOrd,
  635    Ord,
  636    serde::Serialize,
  637    serde::Deserialize,
  638)]
  639pub struct WorkspaceId(i64);
  640
  641impl WorkspaceId {
  642    pub fn from_i64(value: i64) -> Self {
  643        Self(value)
  644    }
  645}
  646
  647impl StaticColumnCount for WorkspaceId {}
  648impl Bind for WorkspaceId {
  649    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  650        self.0.bind(statement, start_index)
  651    }
  652}
  653impl Column for WorkspaceId {
  654    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  655        i64::column(statement, start_index)
  656            .map(|(i, next_index)| (Self(i), next_index))
  657            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  658    }
  659}
  660impl From<WorkspaceId> for i64 {
  661    fn from(val: WorkspaceId) -> Self {
  662        val.0
  663    }
  664}
  665
  666fn prompt_and_open_paths(
  667    app_state: Arc<AppState>,
  668    options: PathPromptOptions,
  669    create_new_window: bool,
  670    cx: &mut App,
  671) {
  672    if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
  673        workspace_window
  674            .update(cx, |multi_workspace, window, cx| {
  675                let workspace = multi_workspace.workspace().clone();
  676                workspace.update(cx, |workspace, cx| {
  677                    prompt_for_open_path_and_open(
  678                        workspace,
  679                        app_state,
  680                        options,
  681                        create_new_window,
  682                        window,
  683                        cx,
  684                    );
  685                });
  686            })
  687            .ok();
  688    } else {
  689        let task = Workspace::new_local(
  690            Vec::new(),
  691            app_state.clone(),
  692            None,
  693            None,
  694            None,
  695            OpenMode::Activate,
  696            cx,
  697        );
  698        cx.spawn(async move |cx| {
  699            let OpenResult { window, .. } = task.await?;
  700            window.update(cx, |multi_workspace, window, cx| {
  701                window.activate_window();
  702                let workspace = multi_workspace.workspace().clone();
  703                workspace.update(cx, |workspace, cx| {
  704                    prompt_for_open_path_and_open(
  705                        workspace,
  706                        app_state,
  707                        options,
  708                        create_new_window,
  709                        window,
  710                        cx,
  711                    );
  712                });
  713            })?;
  714            anyhow::Ok(())
  715        })
  716        .detach_and_log_err(cx);
  717    }
  718}
  719
  720pub fn prompt_for_open_path_and_open(
  721    workspace: &mut Workspace,
  722    app_state: Arc<AppState>,
  723    options: PathPromptOptions,
  724    create_new_window: bool,
  725    window: &mut Window,
  726    cx: &mut Context<Workspace>,
  727) {
  728    let paths = workspace.prompt_for_open_path(
  729        options,
  730        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  731        window,
  732        cx,
  733    );
  734    let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
  735    cx.spawn_in(window, async move |this, cx| {
  736        let Some(paths) = paths.await.log_err().flatten() else {
  737            return;
  738        };
  739        if !create_new_window {
  740            if let Some(handle) = multi_workspace_handle {
  741                if let Some(task) = handle
  742                    .update(cx, |multi_workspace, window, cx| {
  743                        multi_workspace.open_project(paths, OpenMode::Activate, window, cx)
  744                    })
  745                    .log_err()
  746                {
  747                    task.await.log_err();
  748                }
  749                return;
  750            }
  751        }
  752        if let Some(task) = this
  753            .update_in(cx, |this, window, cx| {
  754                this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
  755            })
  756            .log_err()
  757        {
  758            task.await.log_err();
  759        }
  760    })
  761    .detach();
  762}
  763
  764pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  765    component::init();
  766    theme_preview::init(cx);
  767    toast_layer::init(cx);
  768    history_manager::init(app_state.fs.clone(), cx);
  769
  770    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  771        .on_action(|_: &Reload, cx| reload(cx))
  772        .on_action(|action: &Open, cx: &mut App| {
  773            let app_state = AppState::global(cx);
  774            prompt_and_open_paths(
  775                app_state,
  776                PathPromptOptions {
  777                    files: true,
  778                    directories: true,
  779                    multiple: true,
  780                    prompt: None,
  781                },
  782                action.create_new_window,
  783                cx,
  784            );
  785        })
  786        .on_action(|_: &OpenFiles, cx: &mut App| {
  787            let directories = cx.can_select_mixed_files_and_dirs();
  788            let app_state = AppState::global(cx);
  789            prompt_and_open_paths(
  790                app_state,
  791                PathPromptOptions {
  792                    files: true,
  793                    directories,
  794                    multiple: true,
  795                    prompt: None,
  796                },
  797                true,
  798                cx,
  799            );
  800        });
  801}
  802
  803type BuildProjectItemFn =
  804    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  805
  806type BuildProjectItemForPathFn =
  807    fn(
  808        &Entity<Project>,
  809        &ProjectPath,
  810        &mut Window,
  811        &mut App,
  812    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  813
  814#[derive(Clone, Default)]
  815struct ProjectItemRegistry {
  816    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  817    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  818}
  819
  820impl ProjectItemRegistry {
  821    fn register<T: ProjectItem>(&mut self) {
  822        self.build_project_item_fns_by_type.insert(
  823            TypeId::of::<T::Item>(),
  824            |item, project, pane, window, cx| {
  825                let item = item.downcast().unwrap();
  826                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  827                    as Box<dyn ItemHandle>
  828            },
  829        );
  830        self.build_project_item_for_path_fns
  831            .push(|project, project_path, window, cx| {
  832                let project_path = project_path.clone();
  833                let is_file = project
  834                    .read(cx)
  835                    .entry_for_path(&project_path, cx)
  836                    .is_some_and(|entry| entry.is_file());
  837                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  838                let is_local = project.read(cx).is_local();
  839                let project_item =
  840                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  841                let project = project.clone();
  842                Some(window.spawn(cx, async move |cx| {
  843                    match project_item.await.with_context(|| {
  844                        format!(
  845                            "opening project path {:?}",
  846                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  847                        )
  848                    }) {
  849                        Ok(project_item) => {
  850                            let project_item = project_item;
  851                            let project_entry_id: Option<ProjectEntryId> =
  852                                project_item.read_with(cx, project::ProjectItem::entry_id);
  853                            let build_workspace_item = Box::new(
  854                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  855                                    Box::new(cx.new(|cx| {
  856                                        T::for_project_item(
  857                                            project,
  858                                            Some(pane),
  859                                            project_item,
  860                                            window,
  861                                            cx,
  862                                        )
  863                                    })) as Box<dyn ItemHandle>
  864                                },
  865                            ) as Box<_>;
  866                            Ok((project_entry_id, build_workspace_item))
  867                        }
  868                        Err(e) => {
  869                            log::warn!("Failed to open a project item: {e:#}");
  870                            if e.error_code() == ErrorCode::Internal {
  871                                if let Some(abs_path) =
  872                                    entry_abs_path.as_deref().filter(|_| is_file)
  873                                {
  874                                    if let Some(broken_project_item_view) =
  875                                        cx.update(|window, cx| {
  876                                            T::for_broken_project_item(
  877                                                abs_path, is_local, &e, window, cx,
  878                                            )
  879                                        })?
  880                                    {
  881                                        let build_workspace_item = Box::new(
  882                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  883                                                cx.new(|_| broken_project_item_view).boxed_clone()
  884                                            },
  885                                        )
  886                                        as Box<_>;
  887                                        return Ok((None, build_workspace_item));
  888                                    }
  889                                }
  890                            }
  891                            Err(e)
  892                        }
  893                    }
  894                }))
  895            });
  896    }
  897
  898    fn open_path(
  899        &self,
  900        project: &Entity<Project>,
  901        path: &ProjectPath,
  902        window: &mut Window,
  903        cx: &mut App,
  904    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  905        let Some(open_project_item) = self
  906            .build_project_item_for_path_fns
  907            .iter()
  908            .rev()
  909            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  910        else {
  911            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  912        };
  913        open_project_item
  914    }
  915
  916    fn build_item<T: project::ProjectItem>(
  917        &self,
  918        item: Entity<T>,
  919        project: Entity<Project>,
  920        pane: Option<&Pane>,
  921        window: &mut Window,
  922        cx: &mut App,
  923    ) -> Option<Box<dyn ItemHandle>> {
  924        let build = self
  925            .build_project_item_fns_by_type
  926            .get(&TypeId::of::<T>())?;
  927        Some(build(item.into_any(), project, pane, window, cx))
  928    }
  929}
  930
  931type WorkspaceItemBuilder =
  932    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  933
  934impl Global for ProjectItemRegistry {}
  935
  936/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  937/// items will get a chance to open the file, starting from the project item that
  938/// was added last.
  939pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  940    cx.default_global::<ProjectItemRegistry>().register::<I>();
  941}
  942
  943#[derive(Default)]
  944pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  945
  946struct FollowableViewDescriptor {
  947    from_state_proto: fn(
  948        Entity<Workspace>,
  949        ViewId,
  950        &mut Option<proto::view::Variant>,
  951        &mut Window,
  952        &mut App,
  953    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  954    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  955}
  956
  957impl Global for FollowableViewRegistry {}
  958
  959impl FollowableViewRegistry {
  960    pub fn register<I: FollowableItem>(cx: &mut App) {
  961        cx.default_global::<Self>().0.insert(
  962            TypeId::of::<I>(),
  963            FollowableViewDescriptor {
  964                from_state_proto: |workspace, id, state, window, cx| {
  965                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  966                        cx.foreground_executor()
  967                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  968                    })
  969                },
  970                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  971            },
  972        );
  973    }
  974
  975    pub fn from_state_proto(
  976        workspace: Entity<Workspace>,
  977        view_id: ViewId,
  978        mut state: Option<proto::view::Variant>,
  979        window: &mut Window,
  980        cx: &mut App,
  981    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  982        cx.update_default_global(|this: &mut Self, cx| {
  983            this.0.values().find_map(|descriptor| {
  984                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  985            })
  986        })
  987    }
  988
  989    pub fn to_followable_view(
  990        view: impl Into<AnyView>,
  991        cx: &App,
  992    ) -> Option<Box<dyn FollowableItemHandle>> {
  993        let this = cx.try_global::<Self>()?;
  994        let view = view.into();
  995        let descriptor = this.0.get(&view.entity_type())?;
  996        Some((descriptor.to_followable_view)(&view))
  997    }
  998}
  999
 1000#[derive(Copy, Clone)]
 1001struct SerializableItemDescriptor {
 1002    deserialize: fn(
 1003        Entity<Project>,
 1004        WeakEntity<Workspace>,
 1005        WorkspaceId,
 1006        ItemId,
 1007        &mut Window,
 1008        &mut Context<Pane>,
 1009    ) -> Task<Result<Box<dyn ItemHandle>>>,
 1010    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
 1011    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
 1012}
 1013
 1014#[derive(Default)]
 1015struct SerializableItemRegistry {
 1016    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
 1017    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
 1018}
 1019
 1020impl Global for SerializableItemRegistry {}
 1021
 1022impl SerializableItemRegistry {
 1023    fn deserialize(
 1024        item_kind: &str,
 1025        project: Entity<Project>,
 1026        workspace: WeakEntity<Workspace>,
 1027        workspace_id: WorkspaceId,
 1028        item_item: ItemId,
 1029        window: &mut Window,
 1030        cx: &mut Context<Pane>,
 1031    ) -> Task<Result<Box<dyn ItemHandle>>> {
 1032        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1033            return Task::ready(Err(anyhow!(
 1034                "cannot deserialize {}, descriptor not found",
 1035                item_kind
 1036            )));
 1037        };
 1038
 1039        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
 1040    }
 1041
 1042    fn cleanup(
 1043        item_kind: &str,
 1044        workspace_id: WorkspaceId,
 1045        loaded_items: Vec<ItemId>,
 1046        window: &mut Window,
 1047        cx: &mut App,
 1048    ) -> Task<Result<()>> {
 1049        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1050            return Task::ready(Err(anyhow!(
 1051                "cannot cleanup {}, descriptor not found",
 1052                item_kind
 1053            )));
 1054        };
 1055
 1056        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
 1057    }
 1058
 1059    fn view_to_serializable_item_handle(
 1060        view: AnyView,
 1061        cx: &App,
 1062    ) -> Option<Box<dyn SerializableItemHandle>> {
 1063        let this = cx.try_global::<Self>()?;
 1064        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
 1065        Some((descriptor.view_to_serializable_item)(view))
 1066    }
 1067
 1068    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
 1069        let this = cx.try_global::<Self>()?;
 1070        this.descriptors_by_kind.get(item_kind).copied()
 1071    }
 1072}
 1073
 1074pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
 1075    let serialized_item_kind = I::serialized_item_kind();
 1076
 1077    let registry = cx.default_global::<SerializableItemRegistry>();
 1078    let descriptor = SerializableItemDescriptor {
 1079        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
 1080            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
 1081            cx.foreground_executor()
 1082                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 1083        },
 1084        cleanup: |workspace_id, loaded_items, window, cx| {
 1085            I::cleanup(workspace_id, loaded_items, window, cx)
 1086        },
 1087        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1088    };
 1089    registry
 1090        .descriptors_by_kind
 1091        .insert(Arc::from(serialized_item_kind), descriptor);
 1092    registry
 1093        .descriptors_by_type
 1094        .insert(TypeId::of::<I>(), descriptor);
 1095}
 1096
 1097pub struct AppState {
 1098    pub languages: Arc<LanguageRegistry>,
 1099    pub client: Arc<Client>,
 1100    pub user_store: Entity<UserStore>,
 1101    pub workspace_store: Entity<WorkspaceStore>,
 1102    pub fs: Arc<dyn fs::Fs>,
 1103    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1104    pub node_runtime: NodeRuntime,
 1105    pub session: Entity<AppSession>,
 1106}
 1107
 1108struct GlobalAppState(Arc<AppState>);
 1109
 1110impl Global for GlobalAppState {}
 1111
 1112pub struct WorkspaceStore {
 1113    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1114    client: Arc<Client>,
 1115    _subscriptions: Vec<client::Subscription>,
 1116}
 1117
 1118#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1119pub enum CollaboratorId {
 1120    PeerId(PeerId),
 1121    Agent,
 1122}
 1123
 1124impl From<PeerId> for CollaboratorId {
 1125    fn from(peer_id: PeerId) -> Self {
 1126        CollaboratorId::PeerId(peer_id)
 1127    }
 1128}
 1129
 1130impl From<&PeerId> for CollaboratorId {
 1131    fn from(peer_id: &PeerId) -> Self {
 1132        CollaboratorId::PeerId(*peer_id)
 1133    }
 1134}
 1135
 1136#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1137struct Follower {
 1138    project_id: Option<u64>,
 1139    peer_id: PeerId,
 1140}
 1141
 1142impl AppState {
 1143    #[track_caller]
 1144    pub fn global(cx: &App) -> Arc<Self> {
 1145        cx.global::<GlobalAppState>().0.clone()
 1146    }
 1147    pub fn try_global(cx: &App) -> Option<Arc<Self>> {
 1148        cx.try_global::<GlobalAppState>()
 1149            .map(|state| state.0.clone())
 1150    }
 1151    pub fn set_global(state: Arc<AppState>, cx: &mut App) {
 1152        cx.set_global(GlobalAppState(state));
 1153    }
 1154
 1155    #[cfg(any(test, feature = "test-support"))]
 1156    pub fn test(cx: &mut App) -> Arc<Self> {
 1157        use fs::Fs;
 1158        use node_runtime::NodeRuntime;
 1159        use session::Session;
 1160        use settings::SettingsStore;
 1161
 1162        if !cx.has_global::<SettingsStore>() {
 1163            let settings_store = SettingsStore::test(cx);
 1164            cx.set_global(settings_store);
 1165        }
 1166
 1167        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1168        <dyn Fs>::set_global(fs.clone(), cx);
 1169        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1170        let clock = Arc::new(clock::FakeSystemClock::new());
 1171        let http_client = http_client::FakeHttpClient::with_404_response();
 1172        let client = Client::new(clock, http_client, cx);
 1173        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1174        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1175        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1176
 1177        theme_settings::init(theme::LoadThemes::JustBase, cx);
 1178        client::init(&client, cx);
 1179
 1180        Arc::new(Self {
 1181            client,
 1182            fs,
 1183            languages,
 1184            user_store,
 1185            workspace_store,
 1186            node_runtime: NodeRuntime::unavailable(),
 1187            build_window_options: |_, _| Default::default(),
 1188            session,
 1189        })
 1190    }
 1191}
 1192
 1193struct DelayedDebouncedEditAction {
 1194    task: Option<Task<()>>,
 1195    cancel_channel: Option<oneshot::Sender<()>>,
 1196}
 1197
 1198impl DelayedDebouncedEditAction {
 1199    fn new() -> DelayedDebouncedEditAction {
 1200        DelayedDebouncedEditAction {
 1201            task: None,
 1202            cancel_channel: None,
 1203        }
 1204    }
 1205
 1206    fn fire_new<F>(
 1207        &mut self,
 1208        delay: Duration,
 1209        window: &mut Window,
 1210        cx: &mut Context<Workspace>,
 1211        func: F,
 1212    ) where
 1213        F: 'static
 1214            + Send
 1215            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1216    {
 1217        if let Some(channel) = self.cancel_channel.take() {
 1218            _ = channel.send(());
 1219        }
 1220
 1221        let (sender, mut receiver) = oneshot::channel::<()>();
 1222        self.cancel_channel = Some(sender);
 1223
 1224        let previous_task = self.task.take();
 1225        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1226            let mut timer = cx.background_executor().timer(delay).fuse();
 1227            if let Some(previous_task) = previous_task {
 1228                previous_task.await;
 1229            }
 1230
 1231            futures::select_biased! {
 1232                _ = receiver => return,
 1233                    _ = timer => {}
 1234            }
 1235
 1236            if let Some(result) = workspace
 1237                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1238                .log_err()
 1239            {
 1240                result.await.log_err();
 1241            }
 1242        }));
 1243    }
 1244}
 1245
 1246pub enum Event {
 1247    PaneAdded(Entity<Pane>),
 1248    PaneRemoved,
 1249    ItemAdded {
 1250        item: Box<dyn ItemHandle>,
 1251    },
 1252    ActiveItemChanged,
 1253    ItemRemoved {
 1254        item_id: EntityId,
 1255    },
 1256    UserSavedItem {
 1257        pane: WeakEntity<Pane>,
 1258        item: Box<dyn WeakItemHandle>,
 1259        save_intent: SaveIntent,
 1260    },
 1261    ContactRequestedJoin(u64),
 1262    WorkspaceCreated(WeakEntity<Workspace>),
 1263    OpenBundledFile {
 1264        text: Cow<'static, str>,
 1265        title: &'static str,
 1266        language: &'static str,
 1267    },
 1268    ZoomChanged,
 1269    ModalOpened,
 1270    Activate,
 1271    PanelAdded(AnyView),
 1272}
 1273
 1274#[derive(Debug, Clone)]
 1275pub enum OpenVisible {
 1276    All,
 1277    None,
 1278    OnlyFiles,
 1279    OnlyDirectories,
 1280}
 1281
 1282enum WorkspaceLocation {
 1283    // Valid local paths or SSH project to serialize
 1284    Location(SerializedWorkspaceLocation, PathList),
 1285    // No valid location found hence clear session id
 1286    DetachFromSession,
 1287    // No valid location found to serialize
 1288    None,
 1289}
 1290
 1291type PromptForNewPath = Box<
 1292    dyn Fn(
 1293        &mut Workspace,
 1294        DirectoryLister,
 1295        Option<String>,
 1296        &mut Window,
 1297        &mut Context<Workspace>,
 1298    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1299>;
 1300
 1301type PromptForOpenPath = Box<
 1302    dyn Fn(
 1303        &mut Workspace,
 1304        DirectoryLister,
 1305        &mut Window,
 1306        &mut Context<Workspace>,
 1307    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1308>;
 1309
 1310#[derive(Default)]
 1311struct DispatchingKeystrokes {
 1312    dispatched: HashSet<Vec<Keystroke>>,
 1313    queue: VecDeque<Keystroke>,
 1314    task: Option<Shared<Task<()>>>,
 1315}
 1316
 1317/// Collects everything project-related for a certain window opened.
 1318/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1319///
 1320/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1321/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1322/// that can be used to register a global action to be triggered from any place in the window.
 1323pub struct Workspace {
 1324    weak_self: WeakEntity<Self>,
 1325    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1326    zoomed: Option<AnyWeakView>,
 1327    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1328    zoomed_position: Option<DockPosition>,
 1329    center: PaneGroup,
 1330    left_dock: Entity<Dock>,
 1331    bottom_dock: Entity<Dock>,
 1332    right_dock: Entity<Dock>,
 1333    panes: Vec<Entity<Pane>>,
 1334    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1335    active_pane: Entity<Pane>,
 1336    last_active_center_pane: Option<WeakEntity<Pane>>,
 1337    last_active_view_id: Option<proto::ViewId>,
 1338    status_bar: Entity<StatusBar>,
 1339    pub(crate) modal_layer: Entity<ModalLayer>,
 1340    toast_layer: Entity<ToastLayer>,
 1341    titlebar_item: Option<AnyView>,
 1342    notifications: Notifications,
 1343    suppressed_notifications: HashSet<NotificationId>,
 1344    project: Entity<Project>,
 1345    follower_states: HashMap<CollaboratorId, FollowerState>,
 1346    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1347    window_edited: bool,
 1348    last_window_title: Option<String>,
 1349    dirty_items: HashMap<EntityId, Subscription>,
 1350    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1351    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1352    database_id: Option<WorkspaceId>,
 1353    app_state: Arc<AppState>,
 1354    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1355    _subscriptions: Vec<Subscription>,
 1356    _apply_leader_updates: Task<Result<()>>,
 1357    _observe_current_user: Task<Result<()>>,
 1358    _schedule_serialize_workspace: Option<Task<()>>,
 1359    _serialize_workspace_task: Option<Task<()>>,
 1360    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1361    pane_history_timestamp: Arc<AtomicUsize>,
 1362    bounds: Bounds<Pixels>,
 1363    pub centered_layout: bool,
 1364    bounds_save_task_queued: Option<Task<()>>,
 1365    on_prompt_for_new_path: Option<PromptForNewPath>,
 1366    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1367    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1368    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1369    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1370    _items_serializer: Task<Result<()>>,
 1371    session_id: Option<String>,
 1372    scheduled_tasks: Vec<Task<()>>,
 1373    last_open_dock_positions: Vec<DockPosition>,
 1374    removing: bool,
 1375    open_in_dev_container: bool,
 1376    _dev_container_task: Option<Task<Result<()>>>,
 1377    _panels_task: Option<Task<Result<()>>>,
 1378    sidebar_focus_handle: Option<FocusHandle>,
 1379    multi_workspace: Option<WeakEntity<MultiWorkspace>>,
 1380}
 1381
 1382impl EventEmitter<Event> for Workspace {}
 1383
 1384#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1385pub struct ViewId {
 1386    pub creator: CollaboratorId,
 1387    pub id: u64,
 1388}
 1389
 1390pub struct FollowerState {
 1391    center_pane: Entity<Pane>,
 1392    dock_pane: Option<Entity<Pane>>,
 1393    active_view_id: Option<ViewId>,
 1394    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1395}
 1396
 1397struct FollowerView {
 1398    view: Box<dyn FollowableItemHandle>,
 1399    location: Option<proto::PanelId>,
 1400}
 1401
 1402#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
 1403pub enum OpenMode {
 1404    /// Open the workspace in a new window.
 1405    NewWindow,
 1406    /// Add to the window's multi workspace without activating it (used during deserialization).
 1407    Add,
 1408    /// Add to the window's multi workspace and activate it.
 1409    #[default]
 1410    Activate,
 1411}
 1412
 1413impl Workspace {
 1414    pub fn new(
 1415        workspace_id: Option<WorkspaceId>,
 1416        project: Entity<Project>,
 1417        app_state: Arc<AppState>,
 1418        window: &mut Window,
 1419        cx: &mut Context<Self>,
 1420    ) -> Self {
 1421        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1422            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1423                if let TrustedWorktreesEvent::Trusted(..) = e {
 1424                    // Do not persist auto trusted worktrees
 1425                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1426                        worktrees_store.update(cx, |worktrees_store, cx| {
 1427                            worktrees_store.schedule_serialization(
 1428                                cx,
 1429                                |new_trusted_worktrees, cx| {
 1430                                    let timeout =
 1431                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1432                                    let db = WorkspaceDb::global(cx);
 1433                                    cx.background_spawn(async move {
 1434                                        timeout.await;
 1435                                        db.save_trusted_worktrees(new_trusted_worktrees)
 1436                                            .await
 1437                                            .log_err();
 1438                                    })
 1439                                },
 1440                            )
 1441                        });
 1442                    }
 1443                }
 1444            })
 1445            .detach();
 1446
 1447            cx.observe_global::<SettingsStore>(|_, cx| {
 1448                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1449                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1450                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1451                            trusted_worktrees.auto_trust_all(cx);
 1452                        })
 1453                    }
 1454                }
 1455            })
 1456            .detach();
 1457        }
 1458
 1459        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1460            match event {
 1461                project::Event::RemoteIdChanged(_) => {
 1462                    this.update_window_title(window, cx);
 1463                }
 1464
 1465                project::Event::CollaboratorLeft(peer_id) => {
 1466                    this.collaborator_left(*peer_id, window, cx);
 1467                }
 1468
 1469                &project::Event::WorktreeRemoved(_) => {
 1470                    this.update_window_title(window, cx);
 1471                    this.serialize_workspace(window, cx);
 1472                    this.update_history(cx);
 1473                }
 1474
 1475                &project::Event::WorktreeAdded(id) => {
 1476                    this.update_window_title(window, cx);
 1477                    if this
 1478                        .project()
 1479                        .read(cx)
 1480                        .worktree_for_id(id, cx)
 1481                        .is_some_and(|wt| wt.read(cx).is_visible())
 1482                    {
 1483                        this.serialize_workspace(window, cx);
 1484                        this.update_history(cx);
 1485                    }
 1486                }
 1487                project::Event::WorktreeUpdatedEntries(..) => {
 1488                    this.update_window_title(window, cx);
 1489                    this.serialize_workspace(window, cx);
 1490                }
 1491
 1492                project::Event::DisconnectedFromHost => {
 1493                    this.update_window_edited(window, cx);
 1494                    let leaders_to_unfollow =
 1495                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1496                    for leader_id in leaders_to_unfollow {
 1497                        this.unfollow(leader_id, window, cx);
 1498                    }
 1499                }
 1500
 1501                project::Event::DisconnectedFromRemote {
 1502                    server_not_running: _,
 1503                } => {
 1504                    this.update_window_edited(window, cx);
 1505                }
 1506
 1507                project::Event::Closed => {
 1508                    window.remove_window();
 1509                }
 1510
 1511                project::Event::DeletedEntry(_, entry_id) => {
 1512                    for pane in this.panes.iter() {
 1513                        pane.update(cx, |pane, cx| {
 1514                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1515                        });
 1516                    }
 1517                }
 1518
 1519                project::Event::Toast {
 1520                    notification_id,
 1521                    message,
 1522                    link,
 1523                } => this.show_notification(
 1524                    NotificationId::named(notification_id.clone()),
 1525                    cx,
 1526                    |cx| {
 1527                        let mut notification = MessageNotification::new(message.clone(), cx);
 1528                        if let Some(link) = link {
 1529                            notification = notification
 1530                                .more_info_message(link.label)
 1531                                .more_info_url(link.url);
 1532                        }
 1533
 1534                        cx.new(|_| notification)
 1535                    },
 1536                ),
 1537
 1538                project::Event::HideToast { notification_id } => {
 1539                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1540                }
 1541
 1542                project::Event::LanguageServerPrompt(request) => {
 1543                    struct LanguageServerPrompt;
 1544
 1545                    this.show_notification(
 1546                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1547                        cx,
 1548                        |cx| {
 1549                            cx.new(|cx| {
 1550                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1551                            })
 1552                        },
 1553                    );
 1554                }
 1555
 1556                project::Event::AgentLocationChanged => {
 1557                    this.handle_agent_location_changed(window, cx)
 1558                }
 1559
 1560                _ => {}
 1561            }
 1562            cx.notify()
 1563        })
 1564        .detach();
 1565
 1566        cx.subscribe_in(
 1567            &project.read(cx).breakpoint_store(),
 1568            window,
 1569            |workspace, _, event, window, cx| match event {
 1570                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1571                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1572                    workspace.serialize_workspace(window, cx);
 1573                }
 1574                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1575            },
 1576        )
 1577        .detach();
 1578        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1579            cx.subscribe_in(
 1580                &toolchain_store,
 1581                window,
 1582                |workspace, _, event, window, cx| match event {
 1583                    ToolchainStoreEvent::CustomToolchainsModified => {
 1584                        workspace.serialize_workspace(window, cx);
 1585                    }
 1586                    _ => {}
 1587                },
 1588            )
 1589            .detach();
 1590        }
 1591
 1592        cx.on_focus_lost(window, |this, window, cx| {
 1593            let focus_handle = this.focus_handle(cx);
 1594            window.focus(&focus_handle, cx);
 1595        })
 1596        .detach();
 1597
 1598        let weak_handle = cx.entity().downgrade();
 1599        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1600
 1601        let center_pane = cx.new(|cx| {
 1602            let mut center_pane = Pane::new(
 1603                weak_handle.clone(),
 1604                project.clone(),
 1605                pane_history_timestamp.clone(),
 1606                None,
 1607                NewFile.boxed_clone(),
 1608                true,
 1609                window,
 1610                cx,
 1611            );
 1612            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1613            center_pane.set_should_display_welcome_page(true);
 1614            center_pane
 1615        });
 1616        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1617            .detach();
 1618
 1619        window.focus(&center_pane.focus_handle(cx), cx);
 1620
 1621        cx.emit(Event::PaneAdded(center_pane.clone()));
 1622
 1623        let any_window_handle = window.window_handle();
 1624        app_state.workspace_store.update(cx, |store, _| {
 1625            store
 1626                .workspaces
 1627                .insert((any_window_handle, weak_handle.clone()));
 1628        });
 1629
 1630        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1631        let mut connection_status = app_state.client.status();
 1632        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1633            current_user.next().await;
 1634            connection_status.next().await;
 1635            let mut stream =
 1636                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1637
 1638            while stream.recv().await.is_some() {
 1639                this.update(cx, |_, cx| cx.notify())?;
 1640            }
 1641            anyhow::Ok(())
 1642        });
 1643
 1644        // All leader updates are enqueued and then processed in a single task, so
 1645        // that each asynchronous operation can be run in order.
 1646        let (leader_updates_tx, mut leader_updates_rx) =
 1647            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1648        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1649            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1650                Self::process_leader_update(&this, leader_id, update, cx)
 1651                    .await
 1652                    .log_err();
 1653            }
 1654
 1655            Ok(())
 1656        });
 1657
 1658        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1659        let modal_layer = cx.new(|_| ModalLayer::new());
 1660        let toast_layer = cx.new(|_| ToastLayer::new());
 1661        cx.subscribe(
 1662            &modal_layer,
 1663            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1664                cx.emit(Event::ModalOpened);
 1665            },
 1666        )
 1667        .detach();
 1668
 1669        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1670        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1671        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1672        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1673        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1674        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1675        let multi_workspace = window
 1676            .root::<MultiWorkspace>()
 1677            .flatten()
 1678            .map(|mw| mw.downgrade());
 1679        let status_bar = cx.new(|cx| {
 1680            let mut status_bar =
 1681                StatusBar::new(&center_pane.clone(), multi_workspace.clone(), window, cx);
 1682            status_bar.add_left_item(left_dock_buttons, window, cx);
 1683            status_bar.add_right_item(right_dock_buttons, window, cx);
 1684            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1685            status_bar
 1686        });
 1687
 1688        let session_id = app_state.session.read(cx).id().to_owned();
 1689
 1690        let mut active_call = None;
 1691        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1692            let subscriptions =
 1693                vec![
 1694                    call.0
 1695                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1696                ];
 1697            active_call = Some((call, subscriptions));
 1698        }
 1699
 1700        let (serializable_items_tx, serializable_items_rx) =
 1701            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1702        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1703            Self::serialize_items(&this, serializable_items_rx, cx).await
 1704        });
 1705
 1706        let subscriptions = vec![
 1707            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1708            cx.observe_window_bounds(window, move |this, window, cx| {
 1709                if this.bounds_save_task_queued.is_some() {
 1710                    return;
 1711                }
 1712                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1713                    cx.background_executor()
 1714                        .timer(Duration::from_millis(100))
 1715                        .await;
 1716                    this.update_in(cx, |this, window, cx| {
 1717                        this.save_window_bounds(window, cx).detach();
 1718                        this.bounds_save_task_queued.take();
 1719                    })
 1720                    .ok();
 1721                }));
 1722                cx.notify();
 1723            }),
 1724            cx.observe_window_appearance(window, |_, window, cx| {
 1725                let window_appearance = window.appearance();
 1726
 1727                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1728
 1729                theme_settings::reload_theme(cx);
 1730                theme_settings::reload_icon_theme(cx);
 1731            }),
 1732            cx.on_release({
 1733                let weak_handle = weak_handle.clone();
 1734                move |this, cx| {
 1735                    this.app_state.workspace_store.update(cx, move |store, _| {
 1736                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1737                    })
 1738                }
 1739            }),
 1740        ];
 1741
 1742        cx.defer_in(window, move |this, window, cx| {
 1743            this.update_window_title(window, cx);
 1744            this.show_initial_notifications(cx);
 1745        });
 1746
 1747        let mut center = PaneGroup::new(center_pane.clone());
 1748        center.set_is_center(true);
 1749        center.mark_positions(cx);
 1750
 1751        Workspace {
 1752            weak_self: weak_handle.clone(),
 1753            zoomed: None,
 1754            zoomed_position: None,
 1755            previous_dock_drag_coordinates: None,
 1756            center,
 1757            panes: vec![center_pane.clone()],
 1758            panes_by_item: Default::default(),
 1759            active_pane: center_pane.clone(),
 1760            last_active_center_pane: Some(center_pane.downgrade()),
 1761            last_active_view_id: None,
 1762            status_bar,
 1763            modal_layer,
 1764            toast_layer,
 1765            titlebar_item: None,
 1766            notifications: Notifications::default(),
 1767            suppressed_notifications: HashSet::default(),
 1768            left_dock,
 1769            bottom_dock,
 1770            right_dock,
 1771            _panels_task: None,
 1772            project: project.clone(),
 1773            follower_states: Default::default(),
 1774            last_leaders_by_pane: Default::default(),
 1775            dispatching_keystrokes: Default::default(),
 1776            window_edited: false,
 1777            last_window_title: None,
 1778            dirty_items: Default::default(),
 1779            active_call,
 1780            database_id: workspace_id,
 1781            app_state,
 1782            _observe_current_user,
 1783            _apply_leader_updates,
 1784            _schedule_serialize_workspace: None,
 1785            _serialize_workspace_task: None,
 1786            _schedule_serialize_ssh_paths: None,
 1787            leader_updates_tx,
 1788            _subscriptions: subscriptions,
 1789            pane_history_timestamp,
 1790            workspace_actions: Default::default(),
 1791            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1792            bounds: Default::default(),
 1793            centered_layout: false,
 1794            bounds_save_task_queued: None,
 1795            on_prompt_for_new_path: None,
 1796            on_prompt_for_open_path: None,
 1797            terminal_provider: None,
 1798            debugger_provider: None,
 1799            serializable_items_tx,
 1800            _items_serializer,
 1801            session_id: Some(session_id),
 1802
 1803            scheduled_tasks: Vec::new(),
 1804            last_open_dock_positions: Vec::new(),
 1805            removing: false,
 1806            sidebar_focus_handle: None,
 1807            multi_workspace,
 1808            open_in_dev_container: false,
 1809            _dev_container_task: None,
 1810        }
 1811    }
 1812
 1813    pub fn new_local(
 1814        abs_paths: Vec<PathBuf>,
 1815        app_state: Arc<AppState>,
 1816        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1817        env: Option<HashMap<String, String>>,
 1818        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1819        open_mode: OpenMode,
 1820        cx: &mut App,
 1821    ) -> Task<anyhow::Result<OpenResult>> {
 1822        let project_handle = Project::local(
 1823            app_state.client.clone(),
 1824            app_state.node_runtime.clone(),
 1825            app_state.user_store.clone(),
 1826            app_state.languages.clone(),
 1827            app_state.fs.clone(),
 1828            env,
 1829            Default::default(),
 1830            cx,
 1831        );
 1832
 1833        let db = WorkspaceDb::global(cx);
 1834        let kvp = db::kvp::KeyValueStore::global(cx);
 1835        cx.spawn(async move |cx| {
 1836            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1837            for path in abs_paths.into_iter() {
 1838                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1839                    paths_to_open.push(canonical)
 1840                } else {
 1841                    paths_to_open.push(path)
 1842                }
 1843            }
 1844
 1845            let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
 1846
 1847            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1848                paths_to_open = paths.ordered_paths().cloned().collect();
 1849                if !paths.is_lexicographically_ordered() {
 1850                    project_handle.update(cx, |project, cx| {
 1851                        project.set_worktrees_reordered(true, cx);
 1852                    });
 1853                }
 1854            }
 1855
 1856            // Get project paths for all of the abs_paths
 1857            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1858                Vec::with_capacity(paths_to_open.len());
 1859
 1860            for path in paths_to_open.into_iter() {
 1861                if let Some((_, project_entry)) = cx
 1862                    .update(|cx| {
 1863                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1864                    })
 1865                    .await
 1866                    .log_err()
 1867                {
 1868                    project_paths.push((path, Some(project_entry)));
 1869                } else {
 1870                    project_paths.push((path, None));
 1871                }
 1872            }
 1873
 1874            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1875                serialized_workspace.id
 1876            } else {
 1877                db.next_id().await.unwrap_or_else(|_| Default::default())
 1878            };
 1879
 1880            let toolchains = db.toolchains(workspace_id).await?;
 1881
 1882            for (toolchain, worktree_path, path) in toolchains {
 1883                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1884                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1885                    this.find_worktree(&worktree_path, cx)
 1886                        .and_then(|(worktree, rel_path)| {
 1887                            if rel_path.is_empty() {
 1888                                Some(worktree.read(cx).id())
 1889                            } else {
 1890                                None
 1891                            }
 1892                        })
 1893                }) else {
 1894                    // We did not find a worktree with a given path, but that's whatever.
 1895                    continue;
 1896                };
 1897                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1898                    continue;
 1899                }
 1900
 1901                project_handle
 1902                    .update(cx, |this, cx| {
 1903                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1904                    })
 1905                    .await;
 1906            }
 1907            if let Some(workspace) = serialized_workspace.as_ref() {
 1908                project_handle.update(cx, |this, cx| {
 1909                    for (scope, toolchains) in &workspace.user_toolchains {
 1910                        for toolchain in toolchains {
 1911                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1912                        }
 1913                    }
 1914                });
 1915            }
 1916
 1917            let window_to_replace = match open_mode {
 1918                OpenMode::NewWindow => None,
 1919                _ => requesting_window,
 1920            };
 1921
 1922            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1923                if let Some(window) = window_to_replace {
 1924                    let centered_layout = serialized_workspace
 1925                        .as_ref()
 1926                        .map(|w| w.centered_layout)
 1927                        .unwrap_or(false);
 1928
 1929                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1930                        let workspace = cx.new(|cx| {
 1931                            let mut workspace = Workspace::new(
 1932                                Some(workspace_id),
 1933                                project_handle.clone(),
 1934                                app_state.clone(),
 1935                                window,
 1936                                cx,
 1937                            );
 1938
 1939                            workspace.centered_layout = centered_layout;
 1940
 1941                            // Call init callback to add items before window renders
 1942                            if let Some(init) = init {
 1943                                init(&mut workspace, window, cx);
 1944                            }
 1945
 1946                            workspace
 1947                        });
 1948                        match open_mode {
 1949                            OpenMode::Activate => {
 1950                                multi_workspace.activate(workspace.clone(), window, cx);
 1951                            }
 1952                            OpenMode::Add => {
 1953                                multi_workspace.add(workspace.clone(), &*window, cx);
 1954                            }
 1955                            OpenMode::NewWindow => {
 1956                                unreachable!()
 1957                            }
 1958                        }
 1959                        workspace
 1960                    })?;
 1961                    (window, workspace)
 1962                } else {
 1963                    let window_bounds_override = window_bounds_env_override();
 1964
 1965                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1966                        (Some(WindowBounds::Windowed(bounds)), None)
 1967                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1968                        && let Some(display) = workspace.display
 1969                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1970                    {
 1971                        // Reopening an existing workspace - restore its saved bounds
 1972                        (Some(bounds.0), Some(display))
 1973                    } else if let Some((display, bounds)) =
 1974                        persistence::read_default_window_bounds(&kvp)
 1975                    {
 1976                        // New or empty workspace - use the last known window bounds
 1977                        (Some(bounds), Some(display))
 1978                    } else {
 1979                        // New window - let GPUI's default_bounds() handle cascading
 1980                        (None, None)
 1981                    };
 1982
 1983                    // Use the serialized workspace to construct the new window
 1984                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1985                    options.window_bounds = window_bounds;
 1986                    let centered_layout = serialized_workspace
 1987                        .as_ref()
 1988                        .map(|w| w.centered_layout)
 1989                        .unwrap_or(false);
 1990                    let window = cx.open_window(options, {
 1991                        let app_state = app_state.clone();
 1992                        let project_handle = project_handle.clone();
 1993                        move |window, cx| {
 1994                            let workspace = cx.new(|cx| {
 1995                                let mut workspace = Workspace::new(
 1996                                    Some(workspace_id),
 1997                                    project_handle,
 1998                                    app_state,
 1999                                    window,
 2000                                    cx,
 2001                                );
 2002                                workspace.centered_layout = centered_layout;
 2003
 2004                                // Call init callback to add items before window renders
 2005                                if let Some(init) = init {
 2006                                    init(&mut workspace, window, cx);
 2007                                }
 2008
 2009                                workspace
 2010                            });
 2011                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 2012                        }
 2013                    })?;
 2014                    let workspace =
 2015                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 2016                            multi_workspace.workspace().clone()
 2017                        })?;
 2018                    (window, workspace)
 2019                };
 2020
 2021            notify_if_database_failed(window, cx);
 2022            // Check if this is an empty workspace (no paths to open)
 2023            // An empty workspace is one where project_paths is empty
 2024            let is_empty_workspace = project_paths.is_empty();
 2025            // Check if serialized workspace has paths before it's moved
 2026            let serialized_workspace_has_paths = serialized_workspace
 2027                .as_ref()
 2028                .map(|ws| !ws.paths.is_empty())
 2029                .unwrap_or(false);
 2030
 2031            let opened_items = window
 2032                .update(cx, |_, window, cx| {
 2033                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 2034                        open_items(serialized_workspace, project_paths, window, cx)
 2035                    })
 2036                })?
 2037                .await
 2038                .unwrap_or_default();
 2039
 2040            // Restore default dock state for empty workspaces
 2041            // Only restore if:
 2042            // 1. This is an empty workspace (no paths), AND
 2043            // 2. The serialized workspace either doesn't exist or has no paths
 2044            if is_empty_workspace && !serialized_workspace_has_paths {
 2045                if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
 2046                    window
 2047                        .update(cx, |_, window, cx| {
 2048                            workspace.update(cx, |workspace, cx| {
 2049                                for (dock, serialized_dock) in [
 2050                                    (&workspace.right_dock, &default_docks.right),
 2051                                    (&workspace.left_dock, &default_docks.left),
 2052                                    (&workspace.bottom_dock, &default_docks.bottom),
 2053                                ] {
 2054                                    dock.update(cx, |dock, cx| {
 2055                                        dock.serialized_dock = Some(serialized_dock.clone());
 2056                                        dock.restore_state(window, cx);
 2057                                    });
 2058                                }
 2059                                cx.notify();
 2060                            });
 2061                        })
 2062                        .log_err();
 2063                }
 2064            }
 2065
 2066            window
 2067                .update(cx, |_, _window, cx| {
 2068                    workspace.update(cx, |this: &mut Workspace, cx| {
 2069                        this.update_history(cx);
 2070                    });
 2071                })
 2072                .log_err();
 2073            Ok(OpenResult {
 2074                window,
 2075                workspace,
 2076                opened_items,
 2077            })
 2078        })
 2079    }
 2080
 2081    pub fn project_group_key(&self, cx: &App) -> ProjectGroupKey {
 2082        self.project.read(cx).project_group_key(cx)
 2083    }
 2084
 2085    pub fn weak_handle(&self) -> WeakEntity<Self> {
 2086        self.weak_self.clone()
 2087    }
 2088
 2089    pub fn left_dock(&self) -> &Entity<Dock> {
 2090        &self.left_dock
 2091    }
 2092
 2093    pub fn bottom_dock(&self) -> &Entity<Dock> {
 2094        &self.bottom_dock
 2095    }
 2096
 2097    pub fn set_bottom_dock_layout(
 2098        &mut self,
 2099        layout: BottomDockLayout,
 2100        window: &mut Window,
 2101        cx: &mut Context<Self>,
 2102    ) {
 2103        let fs = self.project().read(cx).fs();
 2104        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 2105            content.workspace.bottom_dock_layout = Some(layout);
 2106        });
 2107
 2108        cx.notify();
 2109        self.serialize_workspace(window, cx);
 2110    }
 2111
 2112    pub fn right_dock(&self) -> &Entity<Dock> {
 2113        &self.right_dock
 2114    }
 2115
 2116    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 2117        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 2118    }
 2119
 2120    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 2121        let left_dock = self.left_dock.read(cx);
 2122        let left_visible = left_dock.is_open();
 2123        let left_active_panel = left_dock
 2124            .active_panel()
 2125            .map(|panel| panel.persistent_name().to_string());
 2126        // `zoomed_position` is kept in sync with individual panel zoom state
 2127        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2128        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2129
 2130        let right_dock = self.right_dock.read(cx);
 2131        let right_visible = right_dock.is_open();
 2132        let right_active_panel = right_dock
 2133            .active_panel()
 2134            .map(|panel| panel.persistent_name().to_string());
 2135        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2136
 2137        let bottom_dock = self.bottom_dock.read(cx);
 2138        let bottom_visible = bottom_dock.is_open();
 2139        let bottom_active_panel = bottom_dock
 2140            .active_panel()
 2141            .map(|panel| panel.persistent_name().to_string());
 2142        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2143
 2144        DockStructure {
 2145            left: DockData {
 2146                visible: left_visible,
 2147                active_panel: left_active_panel,
 2148                zoom: left_dock_zoom,
 2149            },
 2150            right: DockData {
 2151                visible: right_visible,
 2152                active_panel: right_active_panel,
 2153                zoom: right_dock_zoom,
 2154            },
 2155            bottom: DockData {
 2156                visible: bottom_visible,
 2157                active_panel: bottom_active_panel,
 2158                zoom: bottom_dock_zoom,
 2159            },
 2160        }
 2161    }
 2162
 2163    pub fn set_dock_structure(
 2164        &self,
 2165        docks: DockStructure,
 2166        window: &mut Window,
 2167        cx: &mut Context<Self>,
 2168    ) {
 2169        for (dock, data) in [
 2170            (&self.left_dock, docks.left),
 2171            (&self.bottom_dock, docks.bottom),
 2172            (&self.right_dock, docks.right),
 2173        ] {
 2174            dock.update(cx, |dock, cx| {
 2175                dock.serialized_dock = Some(data);
 2176                dock.restore_state(window, cx);
 2177            });
 2178        }
 2179    }
 2180
 2181    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2182        self.items(cx)
 2183            .filter_map(|item| {
 2184                let project_path = item.project_path(cx)?;
 2185                self.project.read(cx).absolute_path(&project_path, cx)
 2186            })
 2187            .collect()
 2188    }
 2189
 2190    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2191        match position {
 2192            DockPosition::Left => &self.left_dock,
 2193            DockPosition::Bottom => &self.bottom_dock,
 2194            DockPosition::Right => &self.right_dock,
 2195        }
 2196    }
 2197
 2198    pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
 2199        self.all_docks().into_iter().find_map(|dock| {
 2200            let dock = dock.read(cx);
 2201            dock.has_agent_panel(cx).then_some(dock.position())
 2202        })
 2203    }
 2204
 2205    pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
 2206        self.all_docks().into_iter().find_map(|dock| {
 2207            let dock = dock.read(cx);
 2208            let panel = dock.panel::<T>()?;
 2209            dock.stored_panel_size_state(&panel)
 2210        })
 2211    }
 2212
 2213    pub fn persisted_panel_size_state(
 2214        &self,
 2215        panel_key: &'static str,
 2216        cx: &App,
 2217    ) -> Option<dock::PanelSizeState> {
 2218        dock::Dock::load_persisted_size_state(self, panel_key, cx)
 2219    }
 2220
 2221    pub fn persist_panel_size_state(
 2222        &self,
 2223        panel_key: &str,
 2224        size_state: dock::PanelSizeState,
 2225        cx: &mut App,
 2226    ) {
 2227        let Some(workspace_id) = self
 2228            .database_id()
 2229            .map(|id| i64::from(id).to_string())
 2230            .or(self.session_id())
 2231        else {
 2232            return;
 2233        };
 2234
 2235        let kvp = db::kvp::KeyValueStore::global(cx);
 2236        let panel_key = panel_key.to_string();
 2237        cx.background_spawn(async move {
 2238            let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
 2239            scope
 2240                .write(
 2241                    format!("{workspace_id}:{panel_key}"),
 2242                    serde_json::to_string(&size_state)?,
 2243                )
 2244                .await
 2245        })
 2246        .detach_and_log_err(cx);
 2247    }
 2248
 2249    pub fn set_panel_size_state<T: Panel>(
 2250        &mut self,
 2251        size_state: dock::PanelSizeState,
 2252        window: &mut Window,
 2253        cx: &mut Context<Self>,
 2254    ) -> bool {
 2255        let Some(panel) = self.panel::<T>(cx) else {
 2256            return false;
 2257        };
 2258
 2259        let dock = self.dock_at_position(panel.position(window, cx));
 2260        let did_set = dock.update(cx, |dock, cx| {
 2261            dock.set_panel_size_state(&panel, size_state, cx)
 2262        });
 2263
 2264        if did_set {
 2265            self.persist_panel_size_state(T::panel_key(), size_state, cx);
 2266        }
 2267
 2268        did_set
 2269    }
 2270
 2271    pub fn toggle_dock_panel_flexible_size(
 2272        &self,
 2273        dock: &Entity<Dock>,
 2274        panel: &dyn PanelHandle,
 2275        window: &mut Window,
 2276        cx: &mut App,
 2277    ) {
 2278        let position = dock.read(cx).position();
 2279        let current_size = self.dock_size(&dock.read(cx), window, cx);
 2280        let current_flex =
 2281            current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
 2282        dock.update(cx, |dock, cx| {
 2283            dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
 2284        });
 2285    }
 2286
 2287    fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
 2288        let panel = dock.active_panel()?;
 2289        let size_state = dock
 2290            .stored_panel_size_state(panel.as_ref())
 2291            .unwrap_or_default();
 2292        let position = dock.position();
 2293
 2294        let use_flex = panel.has_flexible_size(window, cx);
 2295
 2296        if position.axis() == Axis::Horizontal
 2297            && use_flex
 2298            && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
 2299        {
 2300            let workspace_width = self.bounds.size.width;
 2301            if workspace_width <= Pixels::ZERO {
 2302                return None;
 2303            }
 2304            let flex = flex.max(0.001);
 2305            let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2306            if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2307                // Both docks are flex items sharing the full workspace width.
 2308                let total_flex = flex + 1.0 + opposite_flex;
 2309                return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
 2310            } else {
 2311                // Opposite dock is fixed-width; flex items share (W - fixed).
 2312                let opposite_fixed = opposite
 2313                    .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2314                    .unwrap_or_default();
 2315                let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
 2316                return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
 2317            }
 2318        }
 2319
 2320        Some(
 2321            size_state
 2322                .size
 2323                .unwrap_or_else(|| panel.default_size(window, cx)),
 2324        )
 2325    }
 2326
 2327    pub fn dock_flex_for_size(
 2328        &self,
 2329        position: DockPosition,
 2330        size: Pixels,
 2331        window: &Window,
 2332        cx: &App,
 2333    ) -> Option<f32> {
 2334        if position.axis() != Axis::Horizontal {
 2335            return None;
 2336        }
 2337
 2338        let workspace_width = self.bounds.size.width;
 2339        if workspace_width <= Pixels::ZERO {
 2340            return None;
 2341        }
 2342
 2343        let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2344        if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2345            let size = size.clamp(px(0.), workspace_width - px(1.));
 2346            Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
 2347        } else {
 2348            let opposite_width = opposite
 2349                .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2350                .unwrap_or_default();
 2351            let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
 2352            let remaining = (available - size).max(px(1.));
 2353            Some((size / remaining).max(0.0))
 2354        }
 2355    }
 2356
 2357    fn opposite_dock_panel_and_size_state(
 2358        &self,
 2359        position: DockPosition,
 2360        window: &Window,
 2361        cx: &App,
 2362    ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
 2363        let opposite_position = match position {
 2364            DockPosition::Left => DockPosition::Right,
 2365            DockPosition::Right => DockPosition::Left,
 2366            DockPosition::Bottom => return None,
 2367        };
 2368
 2369        let opposite_dock = self.dock_at_position(opposite_position).read(cx);
 2370        let panel = opposite_dock.visible_panel()?;
 2371        let mut size_state = opposite_dock
 2372            .stored_panel_size_state(panel.as_ref())
 2373            .unwrap_or_default();
 2374        if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
 2375            size_state.flex = self.default_dock_flex(opposite_position);
 2376        }
 2377        Some((panel.clone(), size_state))
 2378    }
 2379
 2380    pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
 2381        if position.axis() != Axis::Horizontal {
 2382            return None;
 2383        }
 2384
 2385        let pane = self.last_active_center_pane.clone()?.upgrade()?;
 2386        Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
 2387    }
 2388
 2389    pub fn is_edited(&self) -> bool {
 2390        self.window_edited
 2391    }
 2392
 2393    pub fn add_panel<T: Panel>(
 2394        &mut self,
 2395        panel: Entity<T>,
 2396        window: &mut Window,
 2397        cx: &mut Context<Self>,
 2398    ) {
 2399        let focus_handle = panel.panel_focus_handle(cx);
 2400        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2401            .detach();
 2402
 2403        let dock_position = panel.position(window, cx);
 2404        let dock = self.dock_at_position(dock_position);
 2405        let any_panel = panel.to_any();
 2406        let persisted_size_state =
 2407            self.persisted_panel_size_state(T::panel_key(), cx)
 2408                .or_else(|| {
 2409                    load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
 2410                        let state = dock::PanelSizeState {
 2411                            size: Some(size),
 2412                            flex: None,
 2413                        };
 2414                        self.persist_panel_size_state(T::panel_key(), state, cx);
 2415                        state
 2416                    })
 2417                });
 2418
 2419        dock.update(cx, |dock, cx| {
 2420            let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
 2421            if let Some(size_state) = persisted_size_state {
 2422                dock.set_panel_size_state(&panel, size_state, cx);
 2423            }
 2424            index
 2425        });
 2426
 2427        cx.emit(Event::PanelAdded(any_panel));
 2428    }
 2429
 2430    pub fn remove_panel<T: Panel>(
 2431        &mut self,
 2432        panel: &Entity<T>,
 2433        window: &mut Window,
 2434        cx: &mut Context<Self>,
 2435    ) {
 2436        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2437            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2438        }
 2439    }
 2440
 2441    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2442        &self.status_bar
 2443    }
 2444
 2445    pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
 2446        self.sidebar_focus_handle = handle;
 2447    }
 2448
 2449    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2450        StatusBarSettings::get_global(cx).show
 2451    }
 2452
 2453    pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
 2454        self.multi_workspace.as_ref()
 2455    }
 2456
 2457    pub fn set_multi_workspace(
 2458        &mut self,
 2459        multi_workspace: WeakEntity<MultiWorkspace>,
 2460        cx: &mut App,
 2461    ) {
 2462        self.status_bar.update(cx, |status_bar, cx| {
 2463            status_bar.set_multi_workspace(multi_workspace.clone(), cx);
 2464        });
 2465        self.multi_workspace = Some(multi_workspace);
 2466    }
 2467
 2468    pub fn app_state(&self) -> &Arc<AppState> {
 2469        &self.app_state
 2470    }
 2471
 2472    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2473        self._panels_task = Some(task);
 2474    }
 2475
 2476    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2477        self._panels_task.take()
 2478    }
 2479
 2480    pub fn user_store(&self) -> &Entity<UserStore> {
 2481        &self.app_state.user_store
 2482    }
 2483
 2484    pub fn project(&self) -> &Entity<Project> {
 2485        &self.project
 2486    }
 2487
 2488    pub fn path_style(&self, cx: &App) -> PathStyle {
 2489        self.project.read(cx).path_style(cx)
 2490    }
 2491
 2492    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2493        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2494
 2495        for pane_handle in &self.panes {
 2496            let pane = pane_handle.read(cx);
 2497
 2498            for entry in pane.activation_history() {
 2499                history.insert(
 2500                    entry.entity_id,
 2501                    history
 2502                        .get(&entry.entity_id)
 2503                        .cloned()
 2504                        .unwrap_or(0)
 2505                        .max(entry.timestamp),
 2506                );
 2507            }
 2508        }
 2509
 2510        history
 2511    }
 2512
 2513    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2514        let mut recent_item: Option<Entity<T>> = None;
 2515        let mut recent_timestamp = 0;
 2516        for pane_handle in &self.panes {
 2517            let pane = pane_handle.read(cx);
 2518            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2519                pane.items().map(|item| (item.item_id(), item)).collect();
 2520            for entry in pane.activation_history() {
 2521                if entry.timestamp > recent_timestamp
 2522                    && let Some(&item) = item_map.get(&entry.entity_id)
 2523                    && let Some(typed_item) = item.act_as::<T>(cx)
 2524                {
 2525                    recent_timestamp = entry.timestamp;
 2526                    recent_item = Some(typed_item);
 2527                }
 2528            }
 2529        }
 2530        recent_item
 2531    }
 2532
 2533    pub fn recent_navigation_history_iter(
 2534        &self,
 2535        cx: &App,
 2536    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2537        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2538        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2539
 2540        for pane in &self.panes {
 2541            let pane = pane.read(cx);
 2542
 2543            pane.nav_history()
 2544                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2545                    if let Some(fs_path) = &fs_path {
 2546                        abs_paths_opened
 2547                            .entry(fs_path.clone())
 2548                            .or_default()
 2549                            .insert(project_path.clone());
 2550                    }
 2551                    let timestamp = entry.timestamp;
 2552                    match history.entry(project_path) {
 2553                        hash_map::Entry::Occupied(mut entry) => {
 2554                            let (_, old_timestamp) = entry.get();
 2555                            if &timestamp > old_timestamp {
 2556                                entry.insert((fs_path, timestamp));
 2557                            }
 2558                        }
 2559                        hash_map::Entry::Vacant(entry) => {
 2560                            entry.insert((fs_path, timestamp));
 2561                        }
 2562                    }
 2563                });
 2564
 2565            if let Some(item) = pane.active_item()
 2566                && let Some(project_path) = item.project_path(cx)
 2567            {
 2568                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2569
 2570                if let Some(fs_path) = &fs_path {
 2571                    abs_paths_opened
 2572                        .entry(fs_path.clone())
 2573                        .or_default()
 2574                        .insert(project_path.clone());
 2575                }
 2576
 2577                history.insert(project_path, (fs_path, std::usize::MAX));
 2578            }
 2579        }
 2580
 2581        history
 2582            .into_iter()
 2583            .sorted_by_key(|(_, (_, order))| *order)
 2584            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2585            .rev()
 2586            .filter(move |(history_path, abs_path)| {
 2587                let latest_project_path_opened = abs_path
 2588                    .as_ref()
 2589                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2590                    .and_then(|project_paths| {
 2591                        project_paths
 2592                            .iter()
 2593                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2594                    });
 2595
 2596                latest_project_path_opened.is_none_or(|path| path == history_path)
 2597            })
 2598    }
 2599
 2600    pub fn recent_navigation_history(
 2601        &self,
 2602        limit: Option<usize>,
 2603        cx: &App,
 2604    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2605        self.recent_navigation_history_iter(cx)
 2606            .take(limit.unwrap_or(usize::MAX))
 2607            .collect()
 2608    }
 2609
 2610    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2611        for pane in &self.panes {
 2612            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2613        }
 2614    }
 2615
 2616    fn navigate_history(
 2617        &mut self,
 2618        pane: WeakEntity<Pane>,
 2619        mode: NavigationMode,
 2620        window: &mut Window,
 2621        cx: &mut Context<Workspace>,
 2622    ) -> Task<Result<()>> {
 2623        self.navigate_history_impl(
 2624            pane,
 2625            mode,
 2626            window,
 2627            &mut |history, cx| history.pop(mode, cx),
 2628            cx,
 2629        )
 2630    }
 2631
 2632    fn navigate_tag_history(
 2633        &mut self,
 2634        pane: WeakEntity<Pane>,
 2635        mode: TagNavigationMode,
 2636        window: &mut Window,
 2637        cx: &mut Context<Workspace>,
 2638    ) -> Task<Result<()>> {
 2639        self.navigate_history_impl(
 2640            pane,
 2641            NavigationMode::Normal,
 2642            window,
 2643            &mut |history, _cx| history.pop_tag(mode),
 2644            cx,
 2645        )
 2646    }
 2647
 2648    fn navigate_history_impl(
 2649        &mut self,
 2650        pane: WeakEntity<Pane>,
 2651        mode: NavigationMode,
 2652        window: &mut Window,
 2653        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2654        cx: &mut Context<Workspace>,
 2655    ) -> Task<Result<()>> {
 2656        let to_load = if let Some(pane) = pane.upgrade() {
 2657            pane.update(cx, |pane, cx| {
 2658                window.focus(&pane.focus_handle(cx), cx);
 2659                loop {
 2660                    // Retrieve the weak item handle from the history.
 2661                    let entry = cb(pane.nav_history_mut(), cx)?;
 2662
 2663                    // If the item is still present in this pane, then activate it.
 2664                    if let Some(index) = entry
 2665                        .item
 2666                        .upgrade()
 2667                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2668                    {
 2669                        let prev_active_item_index = pane.active_item_index();
 2670                        pane.nav_history_mut().set_mode(mode);
 2671                        pane.activate_item(index, true, true, window, cx);
 2672                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2673
 2674                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2675                        if let Some(data) = entry.data {
 2676                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2677                        }
 2678
 2679                        if navigated {
 2680                            break None;
 2681                        }
 2682                    } else {
 2683                        // If the item is no longer present in this pane, then retrieve its
 2684                        // path info in order to reopen it.
 2685                        break pane
 2686                            .nav_history()
 2687                            .path_for_item(entry.item.id())
 2688                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2689                    }
 2690                }
 2691            })
 2692        } else {
 2693            None
 2694        };
 2695
 2696        if let Some((project_path, abs_path, entry)) = to_load {
 2697            // If the item was no longer present, then load it again from its previous path, first try the local path
 2698            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2699
 2700            cx.spawn_in(window, async move  |workspace, cx| {
 2701                let open_by_project_path = open_by_project_path.await;
 2702                let mut navigated = false;
 2703                match open_by_project_path
 2704                    .with_context(|| format!("Navigating to {project_path:?}"))
 2705                {
 2706                    Ok((project_entry_id, build_item)) => {
 2707                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2708                            pane.nav_history_mut().set_mode(mode);
 2709                            pane.active_item().map(|p| p.item_id())
 2710                        })?;
 2711
 2712                        pane.update_in(cx, |pane, window, cx| {
 2713                            let item = pane.open_item(
 2714                                project_entry_id,
 2715                                project_path,
 2716                                true,
 2717                                entry.is_preview,
 2718                                true,
 2719                                None,
 2720                                window, cx,
 2721                                build_item,
 2722                            );
 2723                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2724                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2725                            if let Some(data) = entry.data {
 2726                                navigated |= item.navigate(data, window, cx);
 2727                            }
 2728                        })?;
 2729                    }
 2730                    Err(open_by_project_path_e) => {
 2731                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2732                        // and its worktree is now dropped
 2733                        if let Some(abs_path) = abs_path {
 2734                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2735                                pane.nav_history_mut().set_mode(mode);
 2736                                pane.active_item().map(|p| p.item_id())
 2737                            })?;
 2738                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2739                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2740                            })?;
 2741                            match open_by_abs_path
 2742                                .await
 2743                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2744                            {
 2745                                Ok(item) => {
 2746                                    pane.update_in(cx, |pane, window, cx| {
 2747                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2748                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2749                                        if let Some(data) = entry.data {
 2750                                            navigated |= item.navigate(data, window, cx);
 2751                                        }
 2752                                    })?;
 2753                                }
 2754                                Err(open_by_abs_path_e) => {
 2755                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2756                                }
 2757                            }
 2758                        }
 2759                    }
 2760                }
 2761
 2762                if !navigated {
 2763                    workspace
 2764                        .update_in(cx, |workspace, window, cx| {
 2765                            Self::navigate_history(workspace, pane, mode, window, cx)
 2766                        })?
 2767                        .await?;
 2768                }
 2769
 2770                Ok(())
 2771            })
 2772        } else {
 2773            Task::ready(Ok(()))
 2774        }
 2775    }
 2776
 2777    pub fn go_back(
 2778        &mut self,
 2779        pane: WeakEntity<Pane>,
 2780        window: &mut Window,
 2781        cx: &mut Context<Workspace>,
 2782    ) -> Task<Result<()>> {
 2783        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2784    }
 2785
 2786    pub fn go_forward(
 2787        &mut self,
 2788        pane: WeakEntity<Pane>,
 2789        window: &mut Window,
 2790        cx: &mut Context<Workspace>,
 2791    ) -> Task<Result<()>> {
 2792        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2793    }
 2794
 2795    pub fn reopen_closed_item(
 2796        &mut self,
 2797        window: &mut Window,
 2798        cx: &mut Context<Workspace>,
 2799    ) -> Task<Result<()>> {
 2800        self.navigate_history(
 2801            self.active_pane().downgrade(),
 2802            NavigationMode::ReopeningClosedItem,
 2803            window,
 2804            cx,
 2805        )
 2806    }
 2807
 2808    pub fn client(&self) -> &Arc<Client> {
 2809        &self.app_state.client
 2810    }
 2811
 2812    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2813        self.titlebar_item = Some(item);
 2814        cx.notify();
 2815    }
 2816
 2817    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2818        self.on_prompt_for_new_path = Some(prompt)
 2819    }
 2820
 2821    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2822        self.on_prompt_for_open_path = Some(prompt)
 2823    }
 2824
 2825    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2826        self.terminal_provider = Some(Box::new(provider));
 2827    }
 2828
 2829    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2830        self.debugger_provider = Some(Arc::new(provider));
 2831    }
 2832
 2833    pub fn set_open_in_dev_container(&mut self, value: bool) {
 2834        self.open_in_dev_container = value;
 2835    }
 2836
 2837    pub fn open_in_dev_container(&self) -> bool {
 2838        self.open_in_dev_container
 2839    }
 2840
 2841    pub fn set_dev_container_task(&mut self, task: Task<Result<()>>) {
 2842        self._dev_container_task = Some(task);
 2843    }
 2844
 2845    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2846        self.debugger_provider.clone()
 2847    }
 2848
 2849    pub fn prompt_for_open_path(
 2850        &mut self,
 2851        path_prompt_options: PathPromptOptions,
 2852        lister: DirectoryLister,
 2853        window: &mut Window,
 2854        cx: &mut Context<Self>,
 2855    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2856        // TODO: If `on_prompt_for_open_path` is set, we should always use it
 2857        // rather than gating on `use_system_path_prompts`. This would let tests
 2858        // inject a mock without also having to disable the setting.
 2859        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2860            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2861            let rx = prompt(self, lister, window, cx);
 2862            self.on_prompt_for_open_path = Some(prompt);
 2863            rx
 2864        } else {
 2865            let (tx, rx) = oneshot::channel();
 2866            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2867
 2868            cx.spawn_in(window, async move |workspace, cx| {
 2869                let Ok(result) = abs_path.await else {
 2870                    return Ok(());
 2871                };
 2872
 2873                match result {
 2874                    Ok(result) => {
 2875                        tx.send(result).ok();
 2876                    }
 2877                    Err(err) => {
 2878                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2879                            workspace.show_portal_error(err.to_string(), cx);
 2880                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2881                            let rx = prompt(workspace, lister, window, cx);
 2882                            workspace.on_prompt_for_open_path = Some(prompt);
 2883                            rx
 2884                        })?;
 2885                        if let Ok(path) = rx.await {
 2886                            tx.send(path).ok();
 2887                        }
 2888                    }
 2889                };
 2890                anyhow::Ok(())
 2891            })
 2892            .detach();
 2893
 2894            rx
 2895        }
 2896    }
 2897
 2898    pub fn prompt_for_new_path(
 2899        &mut self,
 2900        lister: DirectoryLister,
 2901        suggested_name: Option<String>,
 2902        window: &mut Window,
 2903        cx: &mut Context<Self>,
 2904    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2905        if self.project.read(cx).is_via_collab()
 2906            || self.project.read(cx).is_via_remote_server()
 2907            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2908        {
 2909            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2910            let rx = prompt(self, lister, suggested_name, window, cx);
 2911            self.on_prompt_for_new_path = Some(prompt);
 2912            return rx;
 2913        }
 2914
 2915        let (tx, rx) = oneshot::channel();
 2916        cx.spawn_in(window, async move |workspace, cx| {
 2917            let abs_path = workspace.update(cx, |workspace, cx| {
 2918                let relative_to = workspace
 2919                    .most_recent_active_path(cx)
 2920                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2921                    .or_else(|| {
 2922                        let project = workspace.project.read(cx);
 2923                        project.visible_worktrees(cx).find_map(|worktree| {
 2924                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2925                        })
 2926                    })
 2927                    .or_else(std::env::home_dir)
 2928                    .unwrap_or_else(|| PathBuf::from(""));
 2929                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2930            })?;
 2931            let abs_path = match abs_path.await? {
 2932                Ok(path) => path,
 2933                Err(err) => {
 2934                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2935                        workspace.show_portal_error(err.to_string(), cx);
 2936
 2937                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2938                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2939                        workspace.on_prompt_for_new_path = Some(prompt);
 2940                        rx
 2941                    })?;
 2942                    if let Ok(path) = rx.await {
 2943                        tx.send(path).ok();
 2944                    }
 2945                    return anyhow::Ok(());
 2946                }
 2947            };
 2948
 2949            tx.send(abs_path.map(|path| vec![path])).ok();
 2950            anyhow::Ok(())
 2951        })
 2952        .detach();
 2953
 2954        rx
 2955    }
 2956
 2957    pub fn titlebar_item(&self) -> Option<AnyView> {
 2958        self.titlebar_item.clone()
 2959    }
 2960
 2961    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2962    ///
 2963    /// If the given workspace has a local project, then it will be passed
 2964    /// to the callback. Otherwise, a new empty window will be created.
 2965    pub fn with_local_workspace<T, F>(
 2966        &mut self,
 2967        window: &mut Window,
 2968        cx: &mut Context<Self>,
 2969        callback: F,
 2970    ) -> Task<Result<T>>
 2971    where
 2972        T: 'static,
 2973        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2974    {
 2975        if self.project.read(cx).is_local() {
 2976            Task::ready(Ok(callback(self, window, cx)))
 2977        } else {
 2978            let env = self.project.read(cx).cli_environment(cx);
 2979            let task = Self::new_local(
 2980                Vec::new(),
 2981                self.app_state.clone(),
 2982                None,
 2983                env,
 2984                None,
 2985                OpenMode::Activate,
 2986                cx,
 2987            );
 2988            cx.spawn_in(window, async move |_vh, cx| {
 2989                let OpenResult {
 2990                    window: multi_workspace_window,
 2991                    ..
 2992                } = task.await?;
 2993                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2994                    let workspace = multi_workspace.workspace().clone();
 2995                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2996                })
 2997            })
 2998        }
 2999    }
 3000
 3001    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 3002    ///
 3003    /// If the given workspace has a local project, then it will be passed
 3004    /// to the callback. Otherwise, a new empty window will be created.
 3005    pub fn with_local_or_wsl_workspace<T, F>(
 3006        &mut self,
 3007        window: &mut Window,
 3008        cx: &mut Context<Self>,
 3009        callback: F,
 3010    ) -> Task<Result<T>>
 3011    where
 3012        T: 'static,
 3013        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 3014    {
 3015        let project = self.project.read(cx);
 3016        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 3017            Task::ready(Ok(callback(self, window, cx)))
 3018        } else {
 3019            let env = self.project.read(cx).cli_environment(cx);
 3020            let task = Self::new_local(
 3021                Vec::new(),
 3022                self.app_state.clone(),
 3023                None,
 3024                env,
 3025                None,
 3026                OpenMode::Activate,
 3027                cx,
 3028            );
 3029            cx.spawn_in(window, async move |_vh, cx| {
 3030                let OpenResult {
 3031                    window: multi_workspace_window,
 3032                    ..
 3033                } = task.await?;
 3034                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 3035                    let workspace = multi_workspace.workspace().clone();
 3036                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 3037                })
 3038            })
 3039        }
 3040    }
 3041
 3042    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3043        self.project.read(cx).worktrees(cx)
 3044    }
 3045
 3046    pub fn visible_worktrees<'a>(
 3047        &self,
 3048        cx: &'a App,
 3049    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3050        self.project.read(cx).visible_worktrees(cx)
 3051    }
 3052
 3053    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 3054        let futures = self
 3055            .worktrees(cx)
 3056            .filter_map(|worktree| worktree.read(cx).as_local())
 3057            .map(|worktree| worktree.scan_complete())
 3058            .collect::<Vec<_>>();
 3059        async move {
 3060            for future in futures {
 3061                future.await;
 3062            }
 3063        }
 3064    }
 3065
 3066    pub fn close_global(cx: &mut App) {
 3067        cx.defer(|cx| {
 3068            cx.windows().iter().find(|window| {
 3069                window
 3070                    .update(cx, |_, window, _| {
 3071                        if window.is_window_active() {
 3072                            //This can only get called when the window's project connection has been lost
 3073                            //so we don't need to prompt the user for anything and instead just close the window
 3074                            window.remove_window();
 3075                            true
 3076                        } else {
 3077                            false
 3078                        }
 3079                    })
 3080                    .unwrap_or(false)
 3081            });
 3082        });
 3083    }
 3084
 3085    pub fn move_focused_panel_to_next_position(
 3086        &mut self,
 3087        _: &MoveFocusedPanelToNextPosition,
 3088        window: &mut Window,
 3089        cx: &mut Context<Self>,
 3090    ) {
 3091        let docks = self.all_docks();
 3092        let active_dock = docks
 3093            .into_iter()
 3094            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 3095
 3096        if let Some(dock) = active_dock {
 3097            dock.update(cx, |dock, cx| {
 3098                let active_panel = dock
 3099                    .active_panel()
 3100                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 3101
 3102                if let Some(panel) = active_panel {
 3103                    panel.move_to_next_position(window, cx);
 3104                }
 3105            })
 3106        }
 3107    }
 3108
 3109    pub fn prepare_to_close(
 3110        &mut self,
 3111        close_intent: CloseIntent,
 3112        window: &mut Window,
 3113        cx: &mut Context<Self>,
 3114    ) -> Task<Result<bool>> {
 3115        let active_call = self.active_global_call();
 3116
 3117        cx.spawn_in(window, async move |this, cx| {
 3118            this.update(cx, |this, _| {
 3119                if close_intent == CloseIntent::CloseWindow {
 3120                    this.removing = true;
 3121                }
 3122            })?;
 3123
 3124            let workspace_count = cx.update(|_window, cx| {
 3125                cx.windows()
 3126                    .iter()
 3127                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 3128                    .count()
 3129            })?;
 3130
 3131            #[cfg(target_os = "macos")]
 3132            let save_last_workspace = false;
 3133
 3134            // On Linux and Windows, closing the last window should restore the last workspace.
 3135            #[cfg(not(target_os = "macos"))]
 3136            let save_last_workspace = {
 3137                let remaining_workspaces = cx.update(|_window, cx| {
 3138                    cx.windows()
 3139                        .iter()
 3140                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 3141                        .filter_map(|multi_workspace| {
 3142                            multi_workspace
 3143                                .update(cx, |multi_workspace, _, cx| {
 3144                                    multi_workspace.workspace().read(cx).removing
 3145                                })
 3146                                .ok()
 3147                        })
 3148                        .filter(|removing| !removing)
 3149                        .count()
 3150                })?;
 3151
 3152                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 3153            };
 3154
 3155            if let Some(active_call) = active_call
 3156                && workspace_count == 1
 3157                && cx
 3158                    .update(|_window, cx| active_call.0.is_in_room(cx))
 3159                    .unwrap_or(false)
 3160            {
 3161                if close_intent == CloseIntent::CloseWindow {
 3162                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3163                    let answer = cx.update(|window, cx| {
 3164                        window.prompt(
 3165                            PromptLevel::Warning,
 3166                            "Do you want to leave the current call?",
 3167                            None,
 3168                            &["Close window and hang up", "Cancel"],
 3169                            cx,
 3170                        )
 3171                    })?;
 3172
 3173                    if answer.await.log_err() == Some(1) {
 3174                        return anyhow::Ok(false);
 3175                    } else {
 3176                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 3177                            task.await.log_err();
 3178                        }
 3179                    }
 3180                }
 3181                if close_intent == CloseIntent::ReplaceWindow {
 3182                    _ = cx.update(|_window, cx| {
 3183                        let multi_workspace = cx
 3184                            .windows()
 3185                            .iter()
 3186                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 3187                            .next()
 3188                            .unwrap();
 3189                        let project = multi_workspace
 3190                            .read(cx)?
 3191                            .workspace()
 3192                            .read(cx)
 3193                            .project
 3194                            .clone();
 3195                        if project.read(cx).is_shared() {
 3196                            active_call.0.unshare_project(project, cx)?;
 3197                        }
 3198                        Ok::<_, anyhow::Error>(())
 3199                    });
 3200                }
 3201            }
 3202
 3203            let save_result = this
 3204                .update_in(cx, |this, window, cx| {
 3205                    this.save_all_internal(SaveIntent::Close, window, cx)
 3206                })?
 3207                .await;
 3208
 3209            // If we're not quitting, but closing, we remove the workspace from
 3210            // the current session.
 3211            if close_intent != CloseIntent::Quit
 3212                && !save_last_workspace
 3213                && save_result.as_ref().is_ok_and(|&res| res)
 3214            {
 3215                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 3216                    .await;
 3217            }
 3218
 3219            save_result
 3220        })
 3221    }
 3222
 3223    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 3224        self.save_all_internal(
 3225            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 3226            window,
 3227            cx,
 3228        )
 3229        .detach_and_log_err(cx);
 3230    }
 3231
 3232    fn send_keystrokes(
 3233        &mut self,
 3234        action: &SendKeystrokes,
 3235        window: &mut Window,
 3236        cx: &mut Context<Self>,
 3237    ) {
 3238        let keystrokes: Vec<Keystroke> = action
 3239            .0
 3240            .split(' ')
 3241            .flat_map(|k| Keystroke::parse(k).log_err())
 3242            .map(|k| {
 3243                cx.keyboard_mapper()
 3244                    .map_key_equivalent(k, false)
 3245                    .inner()
 3246                    .clone()
 3247            })
 3248            .collect();
 3249        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 3250    }
 3251
 3252    pub fn send_keystrokes_impl(
 3253        &mut self,
 3254        keystrokes: Vec<Keystroke>,
 3255        window: &mut Window,
 3256        cx: &mut Context<Self>,
 3257    ) -> Shared<Task<()>> {
 3258        let mut state = self.dispatching_keystrokes.borrow_mut();
 3259        if !state.dispatched.insert(keystrokes.clone()) {
 3260            cx.propagate();
 3261            return state.task.clone().unwrap();
 3262        }
 3263
 3264        state.queue.extend(keystrokes);
 3265
 3266        let keystrokes = self.dispatching_keystrokes.clone();
 3267        if state.task.is_none() {
 3268            state.task = Some(
 3269                window
 3270                    .spawn(cx, async move |cx| {
 3271                        // limit to 100 keystrokes to avoid infinite recursion.
 3272                        for _ in 0..100 {
 3273                            let keystroke = {
 3274                                let mut state = keystrokes.borrow_mut();
 3275                                let Some(keystroke) = state.queue.pop_front() else {
 3276                                    state.dispatched.clear();
 3277                                    state.task.take();
 3278                                    return;
 3279                                };
 3280                                keystroke
 3281                            };
 3282                            cx.update(|window, cx| {
 3283                                let focused = window.focused(cx);
 3284                                window.dispatch_keystroke(keystroke.clone(), cx);
 3285                                if window.focused(cx) != focused {
 3286                                    // dispatch_keystroke may cause the focus to change.
 3287                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3288                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 3289                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 3290                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3291                                    // )
 3292                                    window.draw(cx).clear();
 3293                                }
 3294                            })
 3295                            .ok();
 3296
 3297                            // Yield between synthetic keystrokes so deferred focus and
 3298                            // other effects can settle before dispatching the next key.
 3299                            yield_now().await;
 3300                        }
 3301
 3302                        *keystrokes.borrow_mut() = Default::default();
 3303                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3304                    })
 3305                    .shared(),
 3306            );
 3307        }
 3308        state.task.clone().unwrap()
 3309    }
 3310
 3311    /// Prompts the user to save or discard each dirty item, returning
 3312    /// `true` if they confirmed (saved/discarded everything) or `false`
 3313    /// if they cancelled. Used before removing worktree roots during
 3314    /// thread archival.
 3315    pub fn prompt_to_save_or_discard_dirty_items(
 3316        &mut self,
 3317        window: &mut Window,
 3318        cx: &mut Context<Self>,
 3319    ) -> Task<Result<bool>> {
 3320        self.save_all_internal(SaveIntent::Close, window, cx)
 3321    }
 3322
 3323    fn save_all_internal(
 3324        &mut self,
 3325        mut save_intent: SaveIntent,
 3326        window: &mut Window,
 3327        cx: &mut Context<Self>,
 3328    ) -> Task<Result<bool>> {
 3329        if self.project.read(cx).is_disconnected(cx) {
 3330            return Task::ready(Ok(true));
 3331        }
 3332        let dirty_items = self
 3333            .panes
 3334            .iter()
 3335            .flat_map(|pane| {
 3336                pane.read(cx).items().filter_map(|item| {
 3337                    if item.is_dirty(cx) {
 3338                        item.tab_content_text(0, cx);
 3339                        Some((pane.downgrade(), item.boxed_clone()))
 3340                    } else {
 3341                        None
 3342                    }
 3343                })
 3344            })
 3345            .collect::<Vec<_>>();
 3346
 3347        let project = self.project.clone();
 3348        cx.spawn_in(window, async move |workspace, cx| {
 3349            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3350                let (serialize_tasks, remaining_dirty_items) =
 3351                    workspace.update_in(cx, |workspace, window, cx| {
 3352                        let mut remaining_dirty_items = Vec::new();
 3353                        let mut serialize_tasks = Vec::new();
 3354                        for (pane, item) in dirty_items {
 3355                            if let Some(task) = item
 3356                                .to_serializable_item_handle(cx)
 3357                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3358                            {
 3359                                serialize_tasks.push(task);
 3360                            } else {
 3361                                remaining_dirty_items.push((pane, item));
 3362                            }
 3363                        }
 3364                        (serialize_tasks, remaining_dirty_items)
 3365                    })?;
 3366
 3367                futures::future::try_join_all(serialize_tasks).await?;
 3368
 3369                if !remaining_dirty_items.is_empty() {
 3370                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3371                }
 3372
 3373                if remaining_dirty_items.len() > 1 {
 3374                    let answer = workspace.update_in(cx, |_, window, cx| {
 3375                        cx.emit(Event::Activate);
 3376                        let detail = Pane::file_names_for_prompt(
 3377                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3378                            cx,
 3379                        );
 3380                        window.prompt(
 3381                            PromptLevel::Warning,
 3382                            "Do you want to save all changes in the following files?",
 3383                            Some(&detail),
 3384                            &["Save all", "Discard all", "Cancel"],
 3385                            cx,
 3386                        )
 3387                    })?;
 3388                    match answer.await.log_err() {
 3389                        Some(0) => save_intent = SaveIntent::SaveAll,
 3390                        Some(1) => save_intent = SaveIntent::Skip,
 3391                        Some(2) => return Ok(false),
 3392                        _ => {}
 3393                    }
 3394                }
 3395
 3396                remaining_dirty_items
 3397            } else {
 3398                dirty_items
 3399            };
 3400
 3401            for (pane, item) in dirty_items {
 3402                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3403                    (
 3404                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3405                        item.project_entry_ids(cx),
 3406                    )
 3407                })?;
 3408                if (singleton || !project_entry_ids.is_empty())
 3409                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3410                {
 3411                    return Ok(false);
 3412                }
 3413            }
 3414            Ok(true)
 3415        })
 3416    }
 3417
 3418    pub fn open_workspace_for_paths(
 3419        &mut self,
 3420        // replace_current_window: bool,
 3421        mut open_mode: OpenMode,
 3422        paths: Vec<PathBuf>,
 3423        window: &mut Window,
 3424        cx: &mut Context<Self>,
 3425    ) -> Task<Result<Entity<Workspace>>> {
 3426        let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
 3427        let is_remote = self.project.read(cx).is_via_collab();
 3428        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3429        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3430
 3431        let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
 3432        if workspace_is_empty {
 3433            open_mode = OpenMode::Activate;
 3434        }
 3435
 3436        let app_state = self.app_state.clone();
 3437
 3438        cx.spawn(async move |_, cx| {
 3439            let OpenResult { workspace, .. } = cx
 3440                .update(|cx| {
 3441                    open_paths(
 3442                        &paths,
 3443                        app_state,
 3444                        OpenOptions {
 3445                            requesting_window,
 3446                            open_mode,
 3447                            ..Default::default()
 3448                        },
 3449                        cx,
 3450                    )
 3451                })
 3452                .await?;
 3453            Ok(workspace)
 3454        })
 3455    }
 3456
 3457    #[allow(clippy::type_complexity)]
 3458    pub fn open_paths(
 3459        &mut self,
 3460        mut abs_paths: Vec<PathBuf>,
 3461        options: OpenOptions,
 3462        pane: Option<WeakEntity<Pane>>,
 3463        window: &mut Window,
 3464        cx: &mut Context<Self>,
 3465    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3466        let fs = self.app_state.fs.clone();
 3467
 3468        let caller_ordered_abs_paths = abs_paths.clone();
 3469
 3470        // Sort the paths to ensure we add worktrees for parents before their children.
 3471        abs_paths.sort_unstable();
 3472        cx.spawn_in(window, async move |this, cx| {
 3473            let mut tasks = Vec::with_capacity(abs_paths.len());
 3474
 3475            for abs_path in &abs_paths {
 3476                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3477                    OpenVisible::All => Some(true),
 3478                    OpenVisible::None => Some(false),
 3479                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3480                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3481                        Some(None) => Some(true),
 3482                        None => None,
 3483                    },
 3484                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3485                        Some(Some(metadata)) => Some(metadata.is_dir),
 3486                        Some(None) => Some(false),
 3487                        None => None,
 3488                    },
 3489                };
 3490                let project_path = match visible {
 3491                    Some(visible) => match this
 3492                        .update(cx, |this, cx| {
 3493                            Workspace::project_path_for_path(
 3494                                this.project.clone(),
 3495                                abs_path,
 3496                                visible,
 3497                                cx,
 3498                            )
 3499                        })
 3500                        .log_err()
 3501                    {
 3502                        Some(project_path) => project_path.await.log_err(),
 3503                        None => None,
 3504                    },
 3505                    None => None,
 3506                };
 3507
 3508                let this = this.clone();
 3509                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3510                let fs = fs.clone();
 3511                let pane = pane.clone();
 3512                let task = cx.spawn(async move |cx| {
 3513                    let (_worktree, project_path) = project_path?;
 3514                    if fs.is_dir(&abs_path).await {
 3515                        // Opening a directory should not race to update the active entry.
 3516                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3517                        None
 3518                    } else {
 3519                        Some(
 3520                            this.update_in(cx, |this, window, cx| {
 3521                                this.open_path(
 3522                                    project_path,
 3523                                    pane,
 3524                                    options.focus.unwrap_or(true),
 3525                                    window,
 3526                                    cx,
 3527                                )
 3528                            })
 3529                            .ok()?
 3530                            .await,
 3531                        )
 3532                    }
 3533                });
 3534                tasks.push(task);
 3535            }
 3536
 3537            let results = futures::future::join_all(tasks).await;
 3538
 3539            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3540            let mut winner: Option<(PathBuf, bool)> = None;
 3541            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3542                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3543                    if !metadata.is_dir {
 3544                        winner = Some((abs_path, false));
 3545                        break;
 3546                    }
 3547                    if winner.is_none() {
 3548                        winner = Some((abs_path, true));
 3549                    }
 3550                } else if winner.is_none() {
 3551                    winner = Some((abs_path, false));
 3552                }
 3553            }
 3554
 3555            // Compute the winner entry id on the foreground thread and emit once, after all
 3556            // paths finish opening. This avoids races between concurrently-opening paths
 3557            // (directories in particular) and makes the resulting project panel selection
 3558            // deterministic.
 3559            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3560                'emit_winner: {
 3561                    let winner_abs_path: Arc<Path> =
 3562                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3563
 3564                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3565                        OpenVisible::All => true,
 3566                        OpenVisible::None => false,
 3567                        OpenVisible::OnlyFiles => !winner_is_dir,
 3568                        OpenVisible::OnlyDirectories => winner_is_dir,
 3569                    };
 3570
 3571                    let Some(worktree_task) = this
 3572                        .update(cx, |workspace, cx| {
 3573                            workspace.project.update(cx, |project, cx| {
 3574                                project.find_or_create_worktree(
 3575                                    winner_abs_path.as_ref(),
 3576                                    visible,
 3577                                    cx,
 3578                                )
 3579                            })
 3580                        })
 3581                        .ok()
 3582                    else {
 3583                        break 'emit_winner;
 3584                    };
 3585
 3586                    let Ok((worktree, _)) = worktree_task.await else {
 3587                        break 'emit_winner;
 3588                    };
 3589
 3590                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3591                        let worktree = worktree.read(cx);
 3592                        let worktree_abs_path = worktree.abs_path();
 3593                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3594                            worktree.root_entry()
 3595                        } else {
 3596                            winner_abs_path
 3597                                .strip_prefix(worktree_abs_path.as_ref())
 3598                                .ok()
 3599                                .and_then(|relative_path| {
 3600                                    let relative_path =
 3601                                        RelPath::new(relative_path, PathStyle::local())
 3602                                            .log_err()?;
 3603                                    worktree.entry_for_path(&relative_path)
 3604                                })
 3605                        }?;
 3606                        Some(entry.id)
 3607                    }) else {
 3608                        break 'emit_winner;
 3609                    };
 3610
 3611                    this.update(cx, |workspace, cx| {
 3612                        workspace.project.update(cx, |_, cx| {
 3613                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3614                        });
 3615                    })
 3616                    .ok();
 3617                }
 3618            }
 3619
 3620            results
 3621        })
 3622    }
 3623
 3624    pub fn open_resolved_path(
 3625        &mut self,
 3626        path: ResolvedPath,
 3627        window: &mut Window,
 3628        cx: &mut Context<Self>,
 3629    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3630        match path {
 3631            ResolvedPath::ProjectPath { project_path, .. } => {
 3632                self.open_path(project_path, None, true, window, cx)
 3633            }
 3634            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3635                PathBuf::from(path),
 3636                OpenOptions {
 3637                    visible: Some(OpenVisible::None),
 3638                    ..Default::default()
 3639                },
 3640                window,
 3641                cx,
 3642            ),
 3643        }
 3644    }
 3645
 3646    pub fn absolute_path_of_worktree(
 3647        &self,
 3648        worktree_id: WorktreeId,
 3649        cx: &mut Context<Self>,
 3650    ) -> Option<PathBuf> {
 3651        self.project
 3652            .read(cx)
 3653            .worktree_for_id(worktree_id, cx)
 3654            // TODO: use `abs_path` or `root_dir`
 3655            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3656    }
 3657
 3658    pub fn add_folder_to_project(
 3659        &mut self,
 3660        _: &AddFolderToProject,
 3661        window: &mut Window,
 3662        cx: &mut Context<Self>,
 3663    ) {
 3664        let project = self.project.read(cx);
 3665        if project.is_via_collab() {
 3666            self.show_error(
 3667                &anyhow!("You cannot add folders to someone else's project"),
 3668                cx,
 3669            );
 3670            return;
 3671        }
 3672        let paths = self.prompt_for_open_path(
 3673            PathPromptOptions {
 3674                files: false,
 3675                directories: true,
 3676                multiple: true,
 3677                prompt: None,
 3678            },
 3679            DirectoryLister::Project(self.project.clone()),
 3680            window,
 3681            cx,
 3682        );
 3683        cx.spawn_in(window, async move |this, cx| {
 3684            if let Some(paths) = paths.await.log_err().flatten() {
 3685                let results = this
 3686                    .update_in(cx, |this, window, cx| {
 3687                        this.open_paths(
 3688                            paths,
 3689                            OpenOptions {
 3690                                visible: Some(OpenVisible::All),
 3691                                ..Default::default()
 3692                            },
 3693                            None,
 3694                            window,
 3695                            cx,
 3696                        )
 3697                    })?
 3698                    .await;
 3699                for result in results.into_iter().flatten() {
 3700                    result.log_err();
 3701                }
 3702            }
 3703            anyhow::Ok(())
 3704        })
 3705        .detach_and_log_err(cx);
 3706    }
 3707
 3708    pub fn project_path_for_path(
 3709        project: Entity<Project>,
 3710        abs_path: &Path,
 3711        visible: bool,
 3712        cx: &mut App,
 3713    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3714        let entry = project.update(cx, |project, cx| {
 3715            project.find_or_create_worktree(abs_path, visible, cx)
 3716        });
 3717        cx.spawn(async move |cx| {
 3718            let (worktree, path) = entry.await?;
 3719            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3720            Ok((worktree, ProjectPath { worktree_id, path }))
 3721        })
 3722    }
 3723
 3724    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3725        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3726    }
 3727
 3728    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3729        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3730    }
 3731
 3732    pub fn items_of_type<'a, T: Item>(
 3733        &'a self,
 3734        cx: &'a App,
 3735    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3736        self.panes
 3737            .iter()
 3738            .flat_map(|pane| pane.read(cx).items_of_type())
 3739    }
 3740
 3741    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3742        self.active_pane().read(cx).active_item()
 3743    }
 3744
 3745    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3746        let item = self.active_item(cx)?;
 3747        item.to_any_view().downcast::<I>().ok()
 3748    }
 3749
 3750    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3751        self.active_item(cx).and_then(|item| item.project_path(cx))
 3752    }
 3753
 3754    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3755        self.recent_navigation_history_iter(cx)
 3756            .filter_map(|(path, abs_path)| {
 3757                let worktree = self
 3758                    .project
 3759                    .read(cx)
 3760                    .worktree_for_id(path.worktree_id, cx)?;
 3761                if worktree.read(cx).is_visible() {
 3762                    abs_path
 3763                } else {
 3764                    None
 3765                }
 3766            })
 3767            .next()
 3768    }
 3769
 3770    pub fn save_active_item(
 3771        &mut self,
 3772        save_intent: SaveIntent,
 3773        window: &mut Window,
 3774        cx: &mut App,
 3775    ) -> Task<Result<()>> {
 3776        let project = self.project.clone();
 3777        let pane = self.active_pane();
 3778        let item = pane.read(cx).active_item();
 3779        let pane = pane.downgrade();
 3780
 3781        window.spawn(cx, async move |cx| {
 3782            if let Some(item) = item {
 3783                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3784                    .await
 3785                    .map(|_| ())
 3786            } else {
 3787                Ok(())
 3788            }
 3789        })
 3790    }
 3791
 3792    pub fn close_inactive_items_and_panes(
 3793        &mut self,
 3794        action: &CloseInactiveTabsAndPanes,
 3795        window: &mut Window,
 3796        cx: &mut Context<Self>,
 3797    ) {
 3798        if let Some(task) = self.close_all_internal(
 3799            true,
 3800            action.save_intent.unwrap_or(SaveIntent::Close),
 3801            window,
 3802            cx,
 3803        ) {
 3804            task.detach_and_log_err(cx)
 3805        }
 3806    }
 3807
 3808    pub fn close_all_items_and_panes(
 3809        &mut self,
 3810        action: &CloseAllItemsAndPanes,
 3811        window: &mut Window,
 3812        cx: &mut Context<Self>,
 3813    ) {
 3814        if let Some(task) = self.close_all_internal(
 3815            false,
 3816            action.save_intent.unwrap_or(SaveIntent::Close),
 3817            window,
 3818            cx,
 3819        ) {
 3820            task.detach_and_log_err(cx)
 3821        }
 3822    }
 3823
 3824    /// Closes the active item across all panes.
 3825    pub fn close_item_in_all_panes(
 3826        &mut self,
 3827        action: &CloseItemInAllPanes,
 3828        window: &mut Window,
 3829        cx: &mut Context<Self>,
 3830    ) {
 3831        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3832            return;
 3833        };
 3834
 3835        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3836        let close_pinned = action.close_pinned;
 3837
 3838        if let Some(project_path) = active_item.project_path(cx) {
 3839            self.close_items_with_project_path(
 3840                &project_path,
 3841                save_intent,
 3842                close_pinned,
 3843                window,
 3844                cx,
 3845            );
 3846        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3847            let item_id = active_item.item_id();
 3848            self.active_pane().update(cx, |pane, cx| {
 3849                pane.close_item_by_id(item_id, save_intent, window, cx)
 3850                    .detach_and_log_err(cx);
 3851            });
 3852        }
 3853    }
 3854
 3855    /// Closes all items with the given project path across all panes.
 3856    pub fn close_items_with_project_path(
 3857        &mut self,
 3858        project_path: &ProjectPath,
 3859        save_intent: SaveIntent,
 3860        close_pinned: bool,
 3861        window: &mut Window,
 3862        cx: &mut Context<Self>,
 3863    ) {
 3864        let panes = self.panes().to_vec();
 3865        for pane in panes {
 3866            pane.update(cx, |pane, cx| {
 3867                pane.close_items_for_project_path(
 3868                    project_path,
 3869                    save_intent,
 3870                    close_pinned,
 3871                    window,
 3872                    cx,
 3873                )
 3874                .detach_and_log_err(cx);
 3875            });
 3876        }
 3877    }
 3878
 3879    fn close_all_internal(
 3880        &mut self,
 3881        retain_active_pane: bool,
 3882        save_intent: SaveIntent,
 3883        window: &mut Window,
 3884        cx: &mut Context<Self>,
 3885    ) -> Option<Task<Result<()>>> {
 3886        let current_pane = self.active_pane();
 3887
 3888        let mut tasks = Vec::new();
 3889
 3890        if retain_active_pane {
 3891            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3892                pane.close_other_items(
 3893                    &CloseOtherItems {
 3894                        save_intent: None,
 3895                        close_pinned: false,
 3896                    },
 3897                    None,
 3898                    window,
 3899                    cx,
 3900                )
 3901            });
 3902
 3903            tasks.push(current_pane_close);
 3904        }
 3905
 3906        for pane in self.panes() {
 3907            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3908                continue;
 3909            }
 3910
 3911            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3912                pane.close_all_items(
 3913                    &CloseAllItems {
 3914                        save_intent: Some(save_intent),
 3915                        close_pinned: false,
 3916                    },
 3917                    window,
 3918                    cx,
 3919                )
 3920            });
 3921
 3922            tasks.push(close_pane_items)
 3923        }
 3924
 3925        if tasks.is_empty() {
 3926            None
 3927        } else {
 3928            Some(cx.spawn_in(window, async move |_, _| {
 3929                for task in tasks {
 3930                    task.await?
 3931                }
 3932                Ok(())
 3933            }))
 3934        }
 3935    }
 3936
 3937    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3938        self.dock_at_position(position).read(cx).is_open()
 3939    }
 3940
 3941    pub fn toggle_dock(
 3942        &mut self,
 3943        dock_side: DockPosition,
 3944        window: &mut Window,
 3945        cx: &mut Context<Self>,
 3946    ) {
 3947        let mut focus_center = false;
 3948        let mut reveal_dock = false;
 3949
 3950        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3951        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3952
 3953        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3954            telemetry::event!(
 3955                "Panel Button Clicked",
 3956                name = panel.persistent_name(),
 3957                toggle_state = !was_visible
 3958            );
 3959        }
 3960        if was_visible {
 3961            self.save_open_dock_positions(cx);
 3962        }
 3963
 3964        let dock = self.dock_at_position(dock_side);
 3965        dock.update(cx, |dock, cx| {
 3966            dock.set_open(!was_visible, window, cx);
 3967
 3968            if dock.active_panel().is_none() {
 3969                let Some(panel_ix) = dock
 3970                    .first_enabled_panel_idx(cx)
 3971                    .log_with_level(log::Level::Info)
 3972                else {
 3973                    return;
 3974                };
 3975                dock.activate_panel(panel_ix, window, cx);
 3976            }
 3977
 3978            if let Some(active_panel) = dock.active_panel() {
 3979                if was_visible {
 3980                    if active_panel
 3981                        .panel_focus_handle(cx)
 3982                        .contains_focused(window, cx)
 3983                    {
 3984                        focus_center = true;
 3985                    }
 3986                } else {
 3987                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3988                    window.focus(focus_handle, cx);
 3989                    reveal_dock = true;
 3990                }
 3991            }
 3992        });
 3993
 3994        if reveal_dock {
 3995            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3996        }
 3997
 3998        if focus_center {
 3999            self.active_pane
 4000                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4001        }
 4002
 4003        cx.notify();
 4004        self.serialize_workspace(window, cx);
 4005    }
 4006
 4007    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 4008        self.all_docks().into_iter().find(|&dock| {
 4009            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 4010        })
 4011    }
 4012
 4013    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 4014        if let Some(dock) = self.active_dock(window, cx).cloned() {
 4015            self.save_open_dock_positions(cx);
 4016            dock.update(cx, |dock, cx| {
 4017                dock.set_open(false, window, cx);
 4018            });
 4019            return true;
 4020        }
 4021        false
 4022    }
 4023
 4024    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4025        self.save_open_dock_positions(cx);
 4026        for dock in self.all_docks() {
 4027            dock.update(cx, |dock, cx| {
 4028                dock.set_open(false, window, cx);
 4029            });
 4030        }
 4031
 4032        cx.focus_self(window);
 4033        cx.notify();
 4034        self.serialize_workspace(window, cx);
 4035    }
 4036
 4037    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 4038        self.all_docks()
 4039            .into_iter()
 4040            .filter_map(|dock| {
 4041                let dock_ref = dock.read(cx);
 4042                if dock_ref.is_open() {
 4043                    Some(dock_ref.position())
 4044                } else {
 4045                    None
 4046                }
 4047            })
 4048            .collect()
 4049    }
 4050
 4051    /// Saves the positions of currently open docks.
 4052    ///
 4053    /// Updates `last_open_dock_positions` with positions of all currently open
 4054    /// docks, to later be restored by the 'Toggle All Docks' action.
 4055    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 4056        let open_dock_positions = self.get_open_dock_positions(cx);
 4057        if !open_dock_positions.is_empty() {
 4058            self.last_open_dock_positions = open_dock_positions;
 4059        }
 4060    }
 4061
 4062    /// Toggles all docks between open and closed states.
 4063    ///
 4064    /// If any docks are open, closes all and remembers their positions. If all
 4065    /// docks are closed, restores the last remembered dock configuration.
 4066    fn toggle_all_docks(
 4067        &mut self,
 4068        _: &ToggleAllDocks,
 4069        window: &mut Window,
 4070        cx: &mut Context<Self>,
 4071    ) {
 4072        let open_dock_positions = self.get_open_dock_positions(cx);
 4073
 4074        if !open_dock_positions.is_empty() {
 4075            self.close_all_docks(window, cx);
 4076        } else if !self.last_open_dock_positions.is_empty() {
 4077            self.restore_last_open_docks(window, cx);
 4078        }
 4079    }
 4080
 4081    /// Reopens docks from the most recently remembered configuration.
 4082    ///
 4083    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 4084    /// and clears the stored positions.
 4085    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4086        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 4087
 4088        for position in positions_to_open {
 4089            let dock = self.dock_at_position(position);
 4090            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 4091        }
 4092
 4093        cx.focus_self(window);
 4094        cx.notify();
 4095        self.serialize_workspace(window, cx);
 4096    }
 4097
 4098    /// Transfer focus to the panel of the given type.
 4099    pub fn focus_panel<T: Panel>(
 4100        &mut self,
 4101        window: &mut Window,
 4102        cx: &mut Context<Self>,
 4103    ) -> Option<Entity<T>> {
 4104        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 4105        panel.to_any().downcast().ok()
 4106    }
 4107
 4108    /// Focus the panel of the given type if it isn't already focused. If it is
 4109    /// already focused, then transfer focus back to the workspace center.
 4110    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 4111    /// panel when transferring focus back to the center.
 4112    pub fn toggle_panel_focus<T: Panel>(
 4113        &mut self,
 4114        window: &mut Window,
 4115        cx: &mut Context<Self>,
 4116    ) -> bool {
 4117        let mut did_focus_panel = false;
 4118        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 4119            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 4120            did_focus_panel
 4121        });
 4122
 4123        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 4124            self.close_panel::<T>(window, cx);
 4125        }
 4126
 4127        telemetry::event!(
 4128            "Panel Button Clicked",
 4129            name = T::persistent_name(),
 4130            toggle_state = did_focus_panel
 4131        );
 4132
 4133        did_focus_panel
 4134    }
 4135
 4136    pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4137        if let Some(item) = self.active_item(cx) {
 4138            item.item_focus_handle(cx).focus(window, cx);
 4139        } else {
 4140            log::error!("Could not find a focus target when switching focus to the center panes",);
 4141        }
 4142    }
 4143
 4144    pub fn activate_panel_for_proto_id(
 4145        &mut self,
 4146        panel_id: PanelId,
 4147        window: &mut Window,
 4148        cx: &mut Context<Self>,
 4149    ) -> Option<Arc<dyn PanelHandle>> {
 4150        let mut panel = None;
 4151        for dock in self.all_docks() {
 4152            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 4153                panel = dock.update(cx, |dock, cx| {
 4154                    dock.activate_panel(panel_index, window, cx);
 4155                    dock.set_open(true, window, cx);
 4156                    dock.active_panel().cloned()
 4157                });
 4158                break;
 4159            }
 4160        }
 4161
 4162        if panel.is_some() {
 4163            cx.notify();
 4164            self.serialize_workspace(window, cx);
 4165        }
 4166
 4167        panel
 4168    }
 4169
 4170    /// Focus or unfocus the given panel type, depending on the given callback.
 4171    fn focus_or_unfocus_panel<T: Panel>(
 4172        &mut self,
 4173        window: &mut Window,
 4174        cx: &mut Context<Self>,
 4175        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 4176    ) -> Option<Arc<dyn PanelHandle>> {
 4177        let mut result_panel = None;
 4178        let mut serialize = false;
 4179        for dock in self.all_docks() {
 4180            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4181                let mut focus_center = false;
 4182                let panel = dock.update(cx, |dock, cx| {
 4183                    dock.activate_panel(panel_index, window, cx);
 4184
 4185                    let panel = dock.active_panel().cloned();
 4186                    if let Some(panel) = panel.as_ref() {
 4187                        if should_focus(&**panel, window, cx) {
 4188                            dock.set_open(true, window, cx);
 4189                            panel.panel_focus_handle(cx).focus(window, cx);
 4190                        } else {
 4191                            focus_center = true;
 4192                        }
 4193                    }
 4194                    panel
 4195                });
 4196
 4197                if focus_center {
 4198                    self.active_pane
 4199                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4200                }
 4201
 4202                result_panel = panel;
 4203                serialize = true;
 4204                break;
 4205            }
 4206        }
 4207
 4208        if serialize {
 4209            self.serialize_workspace(window, cx);
 4210        }
 4211
 4212        cx.notify();
 4213        result_panel
 4214    }
 4215
 4216    /// Open the panel of the given type
 4217    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4218        for dock in self.all_docks() {
 4219            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4220                dock.update(cx, |dock, cx| {
 4221                    dock.activate_panel(panel_index, window, cx);
 4222                    dock.set_open(true, window, cx);
 4223                });
 4224            }
 4225        }
 4226    }
 4227
 4228    /// Open the panel of the given type, dismissing any zoomed items that
 4229    /// would obscure it (e.g. a zoomed terminal).
 4230    pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4231        let dock_position = self.all_docks().iter().find_map(|dock| {
 4232            let dock = dock.read(cx);
 4233            dock.panel_index_for_type::<T>().map(|_| dock.position())
 4234        });
 4235        self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
 4236        self.open_panel::<T>(window, cx);
 4237    }
 4238
 4239    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 4240        for dock in self.all_docks().iter() {
 4241            dock.update(cx, |dock, cx| {
 4242                if dock.panel::<T>().is_some() {
 4243                    dock.set_open(false, window, cx)
 4244                }
 4245            })
 4246        }
 4247    }
 4248
 4249    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 4250        self.all_docks()
 4251            .iter()
 4252            .find_map(|dock| dock.read(cx).panel::<T>())
 4253    }
 4254
 4255    fn dismiss_zoomed_items_to_reveal(
 4256        &mut self,
 4257        dock_to_reveal: Option<DockPosition>,
 4258        window: &mut Window,
 4259        cx: &mut Context<Self>,
 4260    ) {
 4261        // If a center pane is zoomed, unzoom it.
 4262        for pane in &self.panes {
 4263            if pane != &self.active_pane || dock_to_reveal.is_some() {
 4264                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4265            }
 4266        }
 4267
 4268        // If another dock is zoomed, hide it.
 4269        let mut focus_center = false;
 4270        for dock in self.all_docks() {
 4271            dock.update(cx, |dock, cx| {
 4272                if Some(dock.position()) != dock_to_reveal
 4273                    && let Some(panel) = dock.active_panel()
 4274                    && panel.is_zoomed(window, cx)
 4275                {
 4276                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 4277                    dock.set_open(false, window, cx);
 4278                }
 4279            });
 4280        }
 4281
 4282        if focus_center {
 4283            self.active_pane
 4284                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4285        }
 4286
 4287        if self.zoomed_position != dock_to_reveal {
 4288            self.zoomed = None;
 4289            self.zoomed_position = None;
 4290            cx.emit(Event::ZoomChanged);
 4291        }
 4292
 4293        cx.notify();
 4294    }
 4295
 4296    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4297        let pane = cx.new(|cx| {
 4298            let mut pane = Pane::new(
 4299                self.weak_handle(),
 4300                self.project.clone(),
 4301                self.pane_history_timestamp.clone(),
 4302                None,
 4303                NewFile.boxed_clone(),
 4304                true,
 4305                window,
 4306                cx,
 4307            );
 4308            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4309            pane
 4310        });
 4311        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4312            .detach();
 4313        self.panes.push(pane.clone());
 4314
 4315        window.focus(&pane.focus_handle(cx), cx);
 4316
 4317        cx.emit(Event::PaneAdded(pane.clone()));
 4318        pane
 4319    }
 4320
 4321    pub fn add_item_to_center(
 4322        &mut self,
 4323        item: Box<dyn ItemHandle>,
 4324        window: &mut Window,
 4325        cx: &mut Context<Self>,
 4326    ) -> bool {
 4327        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4328            if let Some(center_pane) = center_pane.upgrade() {
 4329                center_pane.update(cx, |pane, cx| {
 4330                    pane.add_item(item, true, true, None, window, cx)
 4331                });
 4332                true
 4333            } else {
 4334                false
 4335            }
 4336        } else {
 4337            false
 4338        }
 4339    }
 4340
 4341    pub fn add_item_to_active_pane(
 4342        &mut self,
 4343        item: Box<dyn ItemHandle>,
 4344        destination_index: Option<usize>,
 4345        focus_item: bool,
 4346        window: &mut Window,
 4347        cx: &mut App,
 4348    ) {
 4349        self.add_item(
 4350            self.active_pane.clone(),
 4351            item,
 4352            destination_index,
 4353            false,
 4354            focus_item,
 4355            window,
 4356            cx,
 4357        )
 4358    }
 4359
 4360    pub fn add_item(
 4361        &mut self,
 4362        pane: Entity<Pane>,
 4363        item: Box<dyn ItemHandle>,
 4364        destination_index: Option<usize>,
 4365        activate_pane: bool,
 4366        focus_item: bool,
 4367        window: &mut Window,
 4368        cx: &mut App,
 4369    ) {
 4370        pane.update(cx, |pane, cx| {
 4371            pane.add_item(
 4372                item,
 4373                activate_pane,
 4374                focus_item,
 4375                destination_index,
 4376                window,
 4377                cx,
 4378            )
 4379        });
 4380    }
 4381
 4382    pub fn split_item(
 4383        &mut self,
 4384        split_direction: SplitDirection,
 4385        item: Box<dyn ItemHandle>,
 4386        window: &mut Window,
 4387        cx: &mut Context<Self>,
 4388    ) {
 4389        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4390        self.add_item(new_pane, item, None, true, true, window, cx);
 4391    }
 4392
 4393    pub fn open_abs_path(
 4394        &mut self,
 4395        abs_path: PathBuf,
 4396        options: OpenOptions,
 4397        window: &mut Window,
 4398        cx: &mut Context<Self>,
 4399    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4400        cx.spawn_in(window, async move |workspace, cx| {
 4401            let open_paths_task_result = workspace
 4402                .update_in(cx, |workspace, window, cx| {
 4403                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4404                })
 4405                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4406                .await;
 4407            anyhow::ensure!(
 4408                open_paths_task_result.len() == 1,
 4409                "open abs path {abs_path:?} task returned incorrect number of results"
 4410            );
 4411            match open_paths_task_result
 4412                .into_iter()
 4413                .next()
 4414                .expect("ensured single task result")
 4415            {
 4416                Some(open_result) => {
 4417                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4418                }
 4419                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4420            }
 4421        })
 4422    }
 4423
 4424    pub fn split_abs_path(
 4425        &mut self,
 4426        abs_path: PathBuf,
 4427        visible: bool,
 4428        window: &mut Window,
 4429        cx: &mut Context<Self>,
 4430    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4431        let project_path_task =
 4432            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4433        cx.spawn_in(window, async move |this, cx| {
 4434            let (_, path) = project_path_task.await?;
 4435            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4436                .await
 4437        })
 4438    }
 4439
 4440    pub fn open_path(
 4441        &mut self,
 4442        path: impl Into<ProjectPath>,
 4443        pane: Option<WeakEntity<Pane>>,
 4444        focus_item: bool,
 4445        window: &mut Window,
 4446        cx: &mut App,
 4447    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4448        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4449    }
 4450
 4451    pub fn open_path_preview(
 4452        &mut self,
 4453        path: impl Into<ProjectPath>,
 4454        pane: Option<WeakEntity<Pane>>,
 4455        focus_item: bool,
 4456        allow_preview: bool,
 4457        activate: bool,
 4458        window: &mut Window,
 4459        cx: &mut App,
 4460    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4461        let pane = pane.unwrap_or_else(|| {
 4462            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4463                self.panes
 4464                    .first()
 4465                    .expect("There must be an active pane")
 4466                    .downgrade()
 4467            })
 4468        });
 4469
 4470        let project_path = path.into();
 4471        let task = self.load_path(project_path.clone(), window, cx);
 4472        window.spawn(cx, async move |cx| {
 4473            let (project_entry_id, build_item) = task.await?;
 4474
 4475            pane.update_in(cx, |pane, window, cx| {
 4476                pane.open_item(
 4477                    project_entry_id,
 4478                    project_path,
 4479                    focus_item,
 4480                    allow_preview,
 4481                    activate,
 4482                    None,
 4483                    window,
 4484                    cx,
 4485                    build_item,
 4486                )
 4487            })
 4488        })
 4489    }
 4490
 4491    pub fn split_path(
 4492        &mut self,
 4493        path: impl Into<ProjectPath>,
 4494        window: &mut Window,
 4495        cx: &mut Context<Self>,
 4496    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4497        self.split_path_preview(path, false, None, window, cx)
 4498    }
 4499
 4500    pub fn split_path_preview(
 4501        &mut self,
 4502        path: impl Into<ProjectPath>,
 4503        allow_preview: bool,
 4504        split_direction: Option<SplitDirection>,
 4505        window: &mut Window,
 4506        cx: &mut Context<Self>,
 4507    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4508        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4509            self.panes
 4510                .first()
 4511                .expect("There must be an active pane")
 4512                .downgrade()
 4513        });
 4514
 4515        if let Member::Pane(center_pane) = &self.center.root
 4516            && center_pane.read(cx).items_len() == 0
 4517        {
 4518            return self.open_path(path, Some(pane), true, window, cx);
 4519        }
 4520
 4521        let project_path = path.into();
 4522        let task = self.load_path(project_path.clone(), window, cx);
 4523        cx.spawn_in(window, async move |this, cx| {
 4524            let (project_entry_id, build_item) = task.await?;
 4525            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4526                let pane = pane.upgrade()?;
 4527                let new_pane = this.split_pane(
 4528                    pane,
 4529                    split_direction.unwrap_or(SplitDirection::Right),
 4530                    window,
 4531                    cx,
 4532                );
 4533                new_pane.update(cx, |new_pane, cx| {
 4534                    Some(new_pane.open_item(
 4535                        project_entry_id,
 4536                        project_path,
 4537                        true,
 4538                        allow_preview,
 4539                        true,
 4540                        None,
 4541                        window,
 4542                        cx,
 4543                        build_item,
 4544                    ))
 4545                })
 4546            })
 4547            .map(|option| option.context("pane was dropped"))?
 4548        })
 4549    }
 4550
 4551    fn load_path(
 4552        &mut self,
 4553        path: ProjectPath,
 4554        window: &mut Window,
 4555        cx: &mut App,
 4556    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4557        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4558        registry.open_path(self.project(), &path, window, cx)
 4559    }
 4560
 4561    pub fn find_project_item<T>(
 4562        &self,
 4563        pane: &Entity<Pane>,
 4564        project_item: &Entity<T::Item>,
 4565        cx: &App,
 4566    ) -> Option<Entity<T>>
 4567    where
 4568        T: ProjectItem,
 4569    {
 4570        use project::ProjectItem as _;
 4571        let project_item = project_item.read(cx);
 4572        let entry_id = project_item.entry_id(cx);
 4573        let project_path = project_item.project_path(cx);
 4574
 4575        let mut item = None;
 4576        if let Some(entry_id) = entry_id {
 4577            item = pane.read(cx).item_for_entry(entry_id, cx);
 4578        }
 4579        if item.is_none()
 4580            && let Some(project_path) = project_path
 4581        {
 4582            item = pane.read(cx).item_for_path(project_path, cx);
 4583        }
 4584
 4585        item.and_then(|item| item.downcast::<T>())
 4586    }
 4587
 4588    pub fn is_project_item_open<T>(
 4589        &self,
 4590        pane: &Entity<Pane>,
 4591        project_item: &Entity<T::Item>,
 4592        cx: &App,
 4593    ) -> bool
 4594    where
 4595        T: ProjectItem,
 4596    {
 4597        self.find_project_item::<T>(pane, project_item, cx)
 4598            .is_some()
 4599    }
 4600
 4601    pub fn open_project_item<T>(
 4602        &mut self,
 4603        pane: Entity<Pane>,
 4604        project_item: Entity<T::Item>,
 4605        activate_pane: bool,
 4606        focus_item: bool,
 4607        keep_old_preview: bool,
 4608        allow_new_preview: bool,
 4609        window: &mut Window,
 4610        cx: &mut Context<Self>,
 4611    ) -> Entity<T>
 4612    where
 4613        T: ProjectItem,
 4614    {
 4615        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4616
 4617        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4618            if !keep_old_preview
 4619                && let Some(old_id) = old_item_id
 4620                && old_id != item.item_id()
 4621            {
 4622                // switching to a different item, so unpreview old active item
 4623                pane.update(cx, |pane, _| {
 4624                    pane.unpreview_item_if_preview(old_id);
 4625                });
 4626            }
 4627
 4628            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4629            if !allow_new_preview {
 4630                pane.update(cx, |pane, _| {
 4631                    pane.unpreview_item_if_preview(item.item_id());
 4632                });
 4633            }
 4634            return item;
 4635        }
 4636
 4637        let item = pane.update(cx, |pane, cx| {
 4638            cx.new(|cx| {
 4639                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4640            })
 4641        });
 4642        let mut destination_index = None;
 4643        pane.update(cx, |pane, cx| {
 4644            if !keep_old_preview && let Some(old_id) = old_item_id {
 4645                pane.unpreview_item_if_preview(old_id);
 4646            }
 4647            if allow_new_preview {
 4648                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4649            }
 4650        });
 4651
 4652        self.add_item(
 4653            pane,
 4654            Box::new(item.clone()),
 4655            destination_index,
 4656            activate_pane,
 4657            focus_item,
 4658            window,
 4659            cx,
 4660        );
 4661        item
 4662    }
 4663
 4664    pub fn open_shared_screen(
 4665        &mut self,
 4666        peer_id: PeerId,
 4667        window: &mut Window,
 4668        cx: &mut Context<Self>,
 4669    ) {
 4670        if let Some(shared_screen) =
 4671            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4672        {
 4673            self.active_pane.update(cx, |pane, cx| {
 4674                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4675            });
 4676        }
 4677    }
 4678
 4679    pub fn activate_item(
 4680        &mut self,
 4681        item: &dyn ItemHandle,
 4682        activate_pane: bool,
 4683        focus_item: bool,
 4684        window: &mut Window,
 4685        cx: &mut App,
 4686    ) -> bool {
 4687        let result = self.panes.iter().find_map(|pane| {
 4688            pane.read(cx)
 4689                .index_for_item(item)
 4690                .map(|ix| (pane.clone(), ix))
 4691        });
 4692        if let Some((pane, ix)) = result {
 4693            pane.update(cx, |pane, cx| {
 4694                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4695            });
 4696            true
 4697        } else {
 4698            false
 4699        }
 4700    }
 4701
 4702    fn activate_pane_at_index(
 4703        &mut self,
 4704        action: &ActivatePane,
 4705        window: &mut Window,
 4706        cx: &mut Context<Self>,
 4707    ) {
 4708        let panes = self.center.panes();
 4709        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4710            window.focus(&pane.focus_handle(cx), cx);
 4711        } else {
 4712            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4713                .detach();
 4714        }
 4715    }
 4716
 4717    fn move_item_to_pane_at_index(
 4718        &mut self,
 4719        action: &MoveItemToPane,
 4720        window: &mut Window,
 4721        cx: &mut Context<Self>,
 4722    ) {
 4723        let panes = self.center.panes();
 4724        let destination = match panes.get(action.destination) {
 4725            Some(&destination) => destination.clone(),
 4726            None => {
 4727                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4728                    return;
 4729                }
 4730                let direction = SplitDirection::Right;
 4731                let split_off_pane = self
 4732                    .find_pane_in_direction(direction, cx)
 4733                    .unwrap_or_else(|| self.active_pane.clone());
 4734                let new_pane = self.add_pane(window, cx);
 4735                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4736                new_pane
 4737            }
 4738        };
 4739
 4740        if action.clone {
 4741            if self
 4742                .active_pane
 4743                .read(cx)
 4744                .active_item()
 4745                .is_some_and(|item| item.can_split(cx))
 4746            {
 4747                clone_active_item(
 4748                    self.database_id(),
 4749                    &self.active_pane,
 4750                    &destination,
 4751                    action.focus,
 4752                    window,
 4753                    cx,
 4754                );
 4755                return;
 4756            }
 4757        }
 4758        move_active_item(
 4759            &self.active_pane,
 4760            &destination,
 4761            action.focus,
 4762            true,
 4763            window,
 4764            cx,
 4765        )
 4766    }
 4767
 4768    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4769        let panes = self.center.panes();
 4770        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4771            let next_ix = (ix + 1) % panes.len();
 4772            let next_pane = panes[next_ix].clone();
 4773            window.focus(&next_pane.focus_handle(cx), cx);
 4774        }
 4775    }
 4776
 4777    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4778        let panes = self.center.panes();
 4779        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4780            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4781            let prev_pane = panes[prev_ix].clone();
 4782            window.focus(&prev_pane.focus_handle(cx), cx);
 4783        }
 4784    }
 4785
 4786    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4787        let last_pane = self.center.last_pane();
 4788        window.focus(&last_pane.focus_handle(cx), cx);
 4789    }
 4790
 4791    pub fn activate_pane_in_direction(
 4792        &mut self,
 4793        direction: SplitDirection,
 4794        window: &mut Window,
 4795        cx: &mut App,
 4796    ) {
 4797        use ActivateInDirectionTarget as Target;
 4798        enum Origin {
 4799            Sidebar,
 4800            LeftDock,
 4801            RightDock,
 4802            BottomDock,
 4803            Center,
 4804        }
 4805
 4806        let origin: Origin = if self
 4807            .sidebar_focus_handle
 4808            .as_ref()
 4809            .is_some_and(|h| h.contains_focused(window, cx))
 4810        {
 4811            Origin::Sidebar
 4812        } else {
 4813            [
 4814                (&self.left_dock, Origin::LeftDock),
 4815                (&self.right_dock, Origin::RightDock),
 4816                (&self.bottom_dock, Origin::BottomDock),
 4817            ]
 4818            .into_iter()
 4819            .find_map(|(dock, origin)| {
 4820                if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4821                    Some(origin)
 4822                } else {
 4823                    None
 4824                }
 4825            })
 4826            .unwrap_or(Origin::Center)
 4827        };
 4828
 4829        let get_last_active_pane = || {
 4830            let pane = self
 4831                .last_active_center_pane
 4832                .clone()
 4833                .unwrap_or_else(|| {
 4834                    self.panes
 4835                        .first()
 4836                        .expect("There must be an active pane")
 4837                        .downgrade()
 4838                })
 4839                .upgrade()?;
 4840            (pane.read(cx).items_len() != 0).then_some(pane)
 4841        };
 4842
 4843        let try_dock =
 4844            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4845
 4846        let sidebar_target = self
 4847            .sidebar_focus_handle
 4848            .as_ref()
 4849            .map(|h| Target::Sidebar(h.clone()));
 4850
 4851        let sidebar_on_right = self
 4852            .multi_workspace
 4853            .as_ref()
 4854            .and_then(|mw| mw.upgrade())
 4855            .map_or(false, |mw| {
 4856                mw.read(cx).sidebar_side(cx) == SidebarSide::Right
 4857            });
 4858
 4859        let away_from_sidebar = if sidebar_on_right {
 4860            SplitDirection::Left
 4861        } else {
 4862            SplitDirection::Right
 4863        };
 4864
 4865        let (near_dock, far_dock) = if sidebar_on_right {
 4866            (&self.right_dock, &self.left_dock)
 4867        } else {
 4868            (&self.left_dock, &self.right_dock)
 4869        };
 4870
 4871        let target = match (origin, direction) {
 4872            (Origin::Sidebar, dir) if dir == away_from_sidebar => try_dock(near_dock)
 4873                .or_else(|| get_last_active_pane().map(Target::Pane))
 4874                .or_else(|| try_dock(&self.bottom_dock))
 4875                .or_else(|| try_dock(far_dock)),
 4876
 4877            (Origin::Sidebar, _) => None,
 4878
 4879            // We're in the center, so we first try to go to a different pane,
 4880            // otherwise try to go to a dock.
 4881            (Origin::Center, direction) => {
 4882                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4883                    Some(Target::Pane(pane))
 4884                } else {
 4885                    match direction {
 4886                        SplitDirection::Up => None,
 4887                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4888                        SplitDirection::Left => {
 4889                            let dock_target = try_dock(&self.left_dock);
 4890                            if sidebar_on_right {
 4891                                dock_target
 4892                            } else {
 4893                                dock_target.or(sidebar_target)
 4894                            }
 4895                        }
 4896                        SplitDirection::Right => {
 4897                            let dock_target = try_dock(&self.right_dock);
 4898                            if sidebar_on_right {
 4899                                dock_target.or(sidebar_target)
 4900                            } else {
 4901                                dock_target
 4902                            }
 4903                        }
 4904                    }
 4905                }
 4906            }
 4907
 4908            (Origin::LeftDock, SplitDirection::Right) => {
 4909                if let Some(last_active_pane) = get_last_active_pane() {
 4910                    Some(Target::Pane(last_active_pane))
 4911                } else {
 4912                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4913                }
 4914            }
 4915
 4916            (Origin::LeftDock, SplitDirection::Left) => {
 4917                if sidebar_on_right {
 4918                    None
 4919                } else {
 4920                    sidebar_target
 4921                }
 4922            }
 4923
 4924            (Origin::LeftDock, SplitDirection::Down)
 4925            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4926
 4927            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4928            (Origin::BottomDock, SplitDirection::Left) => {
 4929                let dock_target = try_dock(&self.left_dock);
 4930                if sidebar_on_right {
 4931                    dock_target
 4932                } else {
 4933                    dock_target.or(sidebar_target)
 4934                }
 4935            }
 4936            (Origin::BottomDock, SplitDirection::Right) => {
 4937                let dock_target = try_dock(&self.right_dock);
 4938                if sidebar_on_right {
 4939                    dock_target.or(sidebar_target)
 4940                } else {
 4941                    dock_target
 4942                }
 4943            }
 4944
 4945            (Origin::RightDock, SplitDirection::Left) => {
 4946                if let Some(last_active_pane) = get_last_active_pane() {
 4947                    Some(Target::Pane(last_active_pane))
 4948                } else {
 4949                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 4950                }
 4951            }
 4952
 4953            (Origin::RightDock, SplitDirection::Right) => {
 4954                if sidebar_on_right {
 4955                    sidebar_target
 4956                } else {
 4957                    None
 4958                }
 4959            }
 4960
 4961            _ => None,
 4962        };
 4963
 4964        match target {
 4965            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4966                let pane = pane.read(cx);
 4967                if let Some(item) = pane.active_item() {
 4968                    item.item_focus_handle(cx).focus(window, cx);
 4969                } else {
 4970                    log::error!(
 4971                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4972                    );
 4973                }
 4974            }
 4975            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4976                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4977                window.defer(cx, move |window, cx| {
 4978                    let dock = dock.read(cx);
 4979                    if let Some(panel) = dock.active_panel() {
 4980                        panel.panel_focus_handle(cx).focus(window, cx);
 4981                    } else {
 4982                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4983                    }
 4984                })
 4985            }
 4986            Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
 4987                focus_handle.focus(window, cx);
 4988            }
 4989            None => {}
 4990        }
 4991    }
 4992
 4993    pub fn move_item_to_pane_in_direction(
 4994        &mut self,
 4995        action: &MoveItemToPaneInDirection,
 4996        window: &mut Window,
 4997        cx: &mut Context<Self>,
 4998    ) {
 4999        let destination = match self.find_pane_in_direction(action.direction, cx) {
 5000            Some(destination) => destination,
 5001            None => {
 5002                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 5003                    return;
 5004                }
 5005                let new_pane = self.add_pane(window, cx);
 5006                self.center
 5007                    .split(&self.active_pane, &new_pane, action.direction, cx);
 5008                new_pane
 5009            }
 5010        };
 5011
 5012        if action.clone {
 5013            if self
 5014                .active_pane
 5015                .read(cx)
 5016                .active_item()
 5017                .is_some_and(|item| item.can_split(cx))
 5018            {
 5019                clone_active_item(
 5020                    self.database_id(),
 5021                    &self.active_pane,
 5022                    &destination,
 5023                    action.focus,
 5024                    window,
 5025                    cx,
 5026                );
 5027                return;
 5028            }
 5029        }
 5030        move_active_item(
 5031            &self.active_pane,
 5032            &destination,
 5033            action.focus,
 5034            true,
 5035            window,
 5036            cx,
 5037        );
 5038    }
 5039
 5040    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 5041        self.center.bounding_box_for_pane(pane)
 5042    }
 5043
 5044    pub fn find_pane_in_direction(
 5045        &mut self,
 5046        direction: SplitDirection,
 5047        cx: &App,
 5048    ) -> Option<Entity<Pane>> {
 5049        self.center
 5050            .find_pane_in_direction(&self.active_pane, direction, cx)
 5051            .cloned()
 5052    }
 5053
 5054    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 5055        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 5056            self.center.swap(&self.active_pane, &to, cx);
 5057            cx.notify();
 5058        }
 5059    }
 5060
 5061    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 5062        if self
 5063            .center
 5064            .move_to_border(&self.active_pane, direction, cx)
 5065            .unwrap()
 5066        {
 5067            cx.notify();
 5068        }
 5069    }
 5070
 5071    pub fn resize_pane(
 5072        &mut self,
 5073        axis: gpui::Axis,
 5074        amount: Pixels,
 5075        window: &mut Window,
 5076        cx: &mut Context<Self>,
 5077    ) {
 5078        let docks = self.all_docks();
 5079        let active_dock = docks
 5080            .into_iter()
 5081            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 5082
 5083        if let Some(dock_entity) = active_dock {
 5084            let dock = dock_entity.read(cx);
 5085            let Some(panel_size) = self.dock_size(&dock, window, cx) else {
 5086                return;
 5087            };
 5088            match dock.position() {
 5089                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 5090                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 5091                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 5092            }
 5093        } else {
 5094            self.center
 5095                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 5096        }
 5097        cx.notify();
 5098    }
 5099
 5100    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 5101        self.center.reset_pane_sizes(cx);
 5102        cx.notify();
 5103    }
 5104
 5105    fn handle_pane_focused(
 5106        &mut self,
 5107        pane: Entity<Pane>,
 5108        window: &mut Window,
 5109        cx: &mut Context<Self>,
 5110    ) {
 5111        // This is explicitly hoisted out of the following check for pane identity as
 5112        // terminal panel panes are not registered as a center panes.
 5113        self.status_bar.update(cx, |status_bar, cx| {
 5114            status_bar.set_active_pane(&pane, window, cx);
 5115        });
 5116        if self.active_pane != pane {
 5117            self.set_active_pane(&pane, window, cx);
 5118        }
 5119
 5120        if self.last_active_center_pane.is_none() {
 5121            self.last_active_center_pane = Some(pane.downgrade());
 5122        }
 5123
 5124        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 5125        // This prevents the dock from closing when focus events fire during window activation.
 5126        // We also preserve any dock whose active panel itself has focus — this covers
 5127        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 5128        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 5129            let dock_read = dock.read(cx);
 5130            if let Some(panel) = dock_read.active_panel() {
 5131                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 5132                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 5133                {
 5134                    return Some(dock_read.position());
 5135                }
 5136            }
 5137            None
 5138        });
 5139
 5140        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 5141        if pane.read(cx).is_zoomed() {
 5142            self.zoomed = Some(pane.downgrade().into());
 5143        } else {
 5144            self.zoomed = None;
 5145        }
 5146        self.zoomed_position = None;
 5147        cx.emit(Event::ZoomChanged);
 5148        self.update_active_view_for_followers(window, cx);
 5149        pane.update(cx, |pane, _| {
 5150            pane.track_alternate_file_items();
 5151        });
 5152
 5153        cx.notify();
 5154    }
 5155
 5156    fn set_active_pane(
 5157        &mut self,
 5158        pane: &Entity<Pane>,
 5159        window: &mut Window,
 5160        cx: &mut Context<Self>,
 5161    ) {
 5162        self.active_pane = pane.clone();
 5163        self.active_item_path_changed(true, window, cx);
 5164        self.last_active_center_pane = Some(pane.downgrade());
 5165    }
 5166
 5167    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5168        self.update_active_view_for_followers(window, cx);
 5169    }
 5170
 5171    fn handle_pane_event(
 5172        &mut self,
 5173        pane: &Entity<Pane>,
 5174        event: &pane::Event,
 5175        window: &mut Window,
 5176        cx: &mut Context<Self>,
 5177    ) {
 5178        let mut serialize_workspace = true;
 5179        match event {
 5180            pane::Event::AddItem { item } => {
 5181                item.added_to_pane(self, pane.clone(), window, cx);
 5182                cx.emit(Event::ItemAdded {
 5183                    item: item.boxed_clone(),
 5184                });
 5185            }
 5186            pane::Event::Split { direction, mode } => {
 5187                match mode {
 5188                    SplitMode::ClonePane => {
 5189                        self.split_and_clone(pane.clone(), *direction, window, cx)
 5190                            .detach();
 5191                    }
 5192                    SplitMode::EmptyPane => {
 5193                        self.split_pane(pane.clone(), *direction, window, cx);
 5194                    }
 5195                    SplitMode::MovePane => {
 5196                        self.split_and_move(pane.clone(), *direction, window, cx);
 5197                    }
 5198                };
 5199            }
 5200            pane::Event::JoinIntoNext => {
 5201                self.join_pane_into_next(pane.clone(), window, cx);
 5202            }
 5203            pane::Event::JoinAll => {
 5204                self.join_all_panes(window, cx);
 5205            }
 5206            pane::Event::Remove { focus_on_pane } => {
 5207                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 5208            }
 5209            pane::Event::ActivateItem {
 5210                local,
 5211                focus_changed,
 5212            } => {
 5213                window.invalidate_character_coordinates();
 5214
 5215                pane.update(cx, |pane, _| {
 5216                    pane.track_alternate_file_items();
 5217                });
 5218                if *local {
 5219                    self.unfollow_in_pane(pane, window, cx);
 5220                }
 5221                serialize_workspace = *focus_changed || pane != self.active_pane();
 5222                if pane == self.active_pane() {
 5223                    self.active_item_path_changed(*focus_changed, window, cx);
 5224                    self.update_active_view_for_followers(window, cx);
 5225                } else if *local {
 5226                    self.set_active_pane(pane, window, cx);
 5227                }
 5228            }
 5229            pane::Event::UserSavedItem { item, save_intent } => {
 5230                cx.emit(Event::UserSavedItem {
 5231                    pane: pane.downgrade(),
 5232                    item: item.boxed_clone(),
 5233                    save_intent: *save_intent,
 5234                });
 5235                serialize_workspace = false;
 5236            }
 5237            pane::Event::ChangeItemTitle => {
 5238                if *pane == self.active_pane {
 5239                    self.active_item_path_changed(false, window, cx);
 5240                }
 5241                serialize_workspace = false;
 5242            }
 5243            pane::Event::RemovedItem { item } => {
 5244                cx.emit(Event::ActiveItemChanged);
 5245                self.update_window_edited(window, cx);
 5246                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 5247                    && entry.get().entity_id() == pane.entity_id()
 5248                {
 5249                    entry.remove();
 5250                }
 5251                cx.emit(Event::ItemRemoved {
 5252                    item_id: item.item_id(),
 5253                });
 5254            }
 5255            pane::Event::Focus => {
 5256                window.invalidate_character_coordinates();
 5257                self.handle_pane_focused(pane.clone(), window, cx);
 5258            }
 5259            pane::Event::ZoomIn => {
 5260                if *pane == self.active_pane {
 5261                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 5262                    if pane.read(cx).has_focus(window, cx) {
 5263                        self.zoomed = Some(pane.downgrade().into());
 5264                        self.zoomed_position = None;
 5265                        cx.emit(Event::ZoomChanged);
 5266                    }
 5267                    cx.notify();
 5268                }
 5269            }
 5270            pane::Event::ZoomOut => {
 5271                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 5272                if self.zoomed_position.is_none() {
 5273                    self.zoomed = None;
 5274                    cx.emit(Event::ZoomChanged);
 5275                }
 5276                cx.notify();
 5277            }
 5278            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 5279        }
 5280
 5281        if serialize_workspace {
 5282            self.serialize_workspace(window, cx);
 5283        }
 5284    }
 5285
 5286    pub fn unfollow_in_pane(
 5287        &mut self,
 5288        pane: &Entity<Pane>,
 5289        window: &mut Window,
 5290        cx: &mut Context<Workspace>,
 5291    ) -> Option<CollaboratorId> {
 5292        let leader_id = self.leader_for_pane(pane)?;
 5293        self.unfollow(leader_id, window, cx);
 5294        Some(leader_id)
 5295    }
 5296
 5297    pub fn split_pane(
 5298        &mut self,
 5299        pane_to_split: Entity<Pane>,
 5300        split_direction: SplitDirection,
 5301        window: &mut Window,
 5302        cx: &mut Context<Self>,
 5303    ) -> Entity<Pane> {
 5304        let new_pane = self.add_pane(window, cx);
 5305        self.center
 5306            .split(&pane_to_split, &new_pane, split_direction, cx);
 5307        cx.notify();
 5308        new_pane
 5309    }
 5310
 5311    pub fn split_and_move(
 5312        &mut self,
 5313        pane: Entity<Pane>,
 5314        direction: SplitDirection,
 5315        window: &mut Window,
 5316        cx: &mut Context<Self>,
 5317    ) {
 5318        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 5319            return;
 5320        };
 5321        let new_pane = self.add_pane(window, cx);
 5322        new_pane.update(cx, |pane, cx| {
 5323            pane.add_item(item, true, true, None, window, cx)
 5324        });
 5325        self.center.split(&pane, &new_pane, direction, cx);
 5326        cx.notify();
 5327    }
 5328
 5329    pub fn split_and_clone(
 5330        &mut self,
 5331        pane: Entity<Pane>,
 5332        direction: SplitDirection,
 5333        window: &mut Window,
 5334        cx: &mut Context<Self>,
 5335    ) -> Task<Option<Entity<Pane>>> {
 5336        let Some(item) = pane.read(cx).active_item() else {
 5337            return Task::ready(None);
 5338        };
 5339        if !item.can_split(cx) {
 5340            return Task::ready(None);
 5341        }
 5342        let task = item.clone_on_split(self.database_id(), window, cx);
 5343        cx.spawn_in(window, async move |this, cx| {
 5344            if let Some(clone) = task.await {
 5345                this.update_in(cx, |this, window, cx| {
 5346                    let new_pane = this.add_pane(window, cx);
 5347                    let nav_history = pane.read(cx).fork_nav_history();
 5348                    new_pane.update(cx, |pane, cx| {
 5349                        pane.set_nav_history(nav_history, cx);
 5350                        pane.add_item(clone, true, true, None, window, cx)
 5351                    });
 5352                    this.center.split(&pane, &new_pane, direction, cx);
 5353                    cx.notify();
 5354                    new_pane
 5355                })
 5356                .ok()
 5357            } else {
 5358                None
 5359            }
 5360        })
 5361    }
 5362
 5363    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5364        let active_item = self.active_pane.read(cx).active_item();
 5365        for pane in &self.panes {
 5366            join_pane_into_active(&self.active_pane, pane, window, cx);
 5367        }
 5368        if let Some(active_item) = active_item {
 5369            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5370        }
 5371        cx.notify();
 5372    }
 5373
 5374    pub fn join_pane_into_next(
 5375        &mut self,
 5376        pane: Entity<Pane>,
 5377        window: &mut Window,
 5378        cx: &mut Context<Self>,
 5379    ) {
 5380        let next_pane = self
 5381            .find_pane_in_direction(SplitDirection::Right, cx)
 5382            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5383            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5384            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5385        let Some(next_pane) = next_pane else {
 5386            return;
 5387        };
 5388        move_all_items(&pane, &next_pane, window, cx);
 5389        cx.notify();
 5390    }
 5391
 5392    fn remove_pane(
 5393        &mut self,
 5394        pane: Entity<Pane>,
 5395        focus_on: Option<Entity<Pane>>,
 5396        window: &mut Window,
 5397        cx: &mut Context<Self>,
 5398    ) {
 5399        if self.center.remove(&pane, cx).unwrap() {
 5400            self.force_remove_pane(&pane, &focus_on, window, cx);
 5401            self.unfollow_in_pane(&pane, window, cx);
 5402            self.last_leaders_by_pane.remove(&pane.downgrade());
 5403            for removed_item in pane.read(cx).items() {
 5404                self.panes_by_item.remove(&removed_item.item_id());
 5405            }
 5406
 5407            cx.notify();
 5408        } else {
 5409            self.active_item_path_changed(true, window, cx);
 5410        }
 5411        cx.emit(Event::PaneRemoved);
 5412    }
 5413
 5414    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5415        &mut self.panes
 5416    }
 5417
 5418    pub fn panes(&self) -> &[Entity<Pane>] {
 5419        &self.panes
 5420    }
 5421
 5422    pub fn active_pane(&self) -> &Entity<Pane> {
 5423        &self.active_pane
 5424    }
 5425
 5426    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5427        for dock in self.all_docks() {
 5428            if dock.focus_handle(cx).contains_focused(window, cx)
 5429                && let Some(pane) = dock
 5430                    .read(cx)
 5431                    .active_panel()
 5432                    .and_then(|panel| panel.pane(cx))
 5433            {
 5434                return pane;
 5435            }
 5436        }
 5437        self.active_pane().clone()
 5438    }
 5439
 5440    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5441        self.find_pane_in_direction(SplitDirection::Right, cx)
 5442            .unwrap_or_else(|| {
 5443                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5444            })
 5445    }
 5446
 5447    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5448        self.pane_for_item_id(handle.item_id())
 5449    }
 5450
 5451    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5452        let weak_pane = self.panes_by_item.get(&item_id)?;
 5453        weak_pane.upgrade()
 5454    }
 5455
 5456    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5457        self.panes
 5458            .iter()
 5459            .find(|pane| pane.entity_id() == entity_id)
 5460            .cloned()
 5461    }
 5462
 5463    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5464        self.follower_states.retain(|leader_id, state| {
 5465            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5466                for item in state.items_by_leader_view_id.values() {
 5467                    item.view.set_leader_id(None, window, cx);
 5468                }
 5469                false
 5470            } else {
 5471                true
 5472            }
 5473        });
 5474        cx.notify();
 5475    }
 5476
 5477    pub fn start_following(
 5478        &mut self,
 5479        leader_id: impl Into<CollaboratorId>,
 5480        window: &mut Window,
 5481        cx: &mut Context<Self>,
 5482    ) -> Option<Task<Result<()>>> {
 5483        let leader_id = leader_id.into();
 5484        let pane = self.active_pane().clone();
 5485
 5486        self.last_leaders_by_pane
 5487            .insert(pane.downgrade(), leader_id);
 5488        self.unfollow(leader_id, window, cx);
 5489        self.unfollow_in_pane(&pane, window, cx);
 5490        self.follower_states.insert(
 5491            leader_id,
 5492            FollowerState {
 5493                center_pane: pane.clone(),
 5494                dock_pane: None,
 5495                active_view_id: None,
 5496                items_by_leader_view_id: Default::default(),
 5497            },
 5498        );
 5499        cx.notify();
 5500
 5501        match leader_id {
 5502            CollaboratorId::PeerId(leader_peer_id) => {
 5503                let room_id = self.active_call()?.room_id(cx)?;
 5504                let project_id = self.project.read(cx).remote_id();
 5505                let request = self.app_state.client.request(proto::Follow {
 5506                    room_id,
 5507                    project_id,
 5508                    leader_id: Some(leader_peer_id),
 5509                });
 5510
 5511                Some(cx.spawn_in(window, async move |this, cx| {
 5512                    let response = request.await?;
 5513                    this.update(cx, |this, _| {
 5514                        let state = this
 5515                            .follower_states
 5516                            .get_mut(&leader_id)
 5517                            .context("following interrupted")?;
 5518                        state.active_view_id = response
 5519                            .active_view
 5520                            .as_ref()
 5521                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5522                        anyhow::Ok(())
 5523                    })??;
 5524                    if let Some(view) = response.active_view {
 5525                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5526                    }
 5527                    this.update_in(cx, |this, window, cx| {
 5528                        this.leader_updated(leader_id, window, cx)
 5529                    })?;
 5530                    Ok(())
 5531                }))
 5532            }
 5533            CollaboratorId::Agent => {
 5534                self.leader_updated(leader_id, window, cx)?;
 5535                Some(Task::ready(Ok(())))
 5536            }
 5537        }
 5538    }
 5539
 5540    pub fn follow_next_collaborator(
 5541        &mut self,
 5542        _: &FollowNextCollaborator,
 5543        window: &mut Window,
 5544        cx: &mut Context<Self>,
 5545    ) {
 5546        let collaborators = self.project.read(cx).collaborators();
 5547        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5548            let mut collaborators = collaborators.keys().copied();
 5549            for peer_id in collaborators.by_ref() {
 5550                if CollaboratorId::PeerId(peer_id) == leader_id {
 5551                    break;
 5552                }
 5553            }
 5554            collaborators.next().map(CollaboratorId::PeerId)
 5555        } else if let Some(last_leader_id) =
 5556            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5557        {
 5558            match last_leader_id {
 5559                CollaboratorId::PeerId(peer_id) => {
 5560                    if collaborators.contains_key(peer_id) {
 5561                        Some(*last_leader_id)
 5562                    } else {
 5563                        None
 5564                    }
 5565                }
 5566                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5567            }
 5568        } else {
 5569            None
 5570        };
 5571
 5572        let pane = self.active_pane.clone();
 5573        let Some(leader_id) = next_leader_id.or_else(|| {
 5574            Some(CollaboratorId::PeerId(
 5575                collaborators.keys().copied().next()?,
 5576            ))
 5577        }) else {
 5578            return;
 5579        };
 5580        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5581            return;
 5582        }
 5583        if let Some(task) = self.start_following(leader_id, window, cx) {
 5584            task.detach_and_log_err(cx)
 5585        }
 5586    }
 5587
 5588    pub fn follow(
 5589        &mut self,
 5590        leader_id: impl Into<CollaboratorId>,
 5591        window: &mut Window,
 5592        cx: &mut Context<Self>,
 5593    ) {
 5594        let leader_id = leader_id.into();
 5595
 5596        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5597            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5598                return;
 5599            };
 5600            let Some(remote_participant) =
 5601                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5602            else {
 5603                return;
 5604            };
 5605
 5606            let project = self.project.read(cx);
 5607
 5608            let other_project_id = match remote_participant.location {
 5609                ParticipantLocation::External => None,
 5610                ParticipantLocation::UnsharedProject => None,
 5611                ParticipantLocation::SharedProject { project_id } => {
 5612                    if Some(project_id) == project.remote_id() {
 5613                        None
 5614                    } else {
 5615                        Some(project_id)
 5616                    }
 5617                }
 5618            };
 5619
 5620            // if they are active in another project, follow there.
 5621            if let Some(project_id) = other_project_id {
 5622                let app_state = self.app_state.clone();
 5623                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5624                    .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
 5625                        Some(format!("{error:#}"))
 5626                    });
 5627            }
 5628        }
 5629
 5630        // if you're already following, find the right pane and focus it.
 5631        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5632            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5633
 5634            return;
 5635        }
 5636
 5637        // Otherwise, follow.
 5638        if let Some(task) = self.start_following(leader_id, window, cx) {
 5639            task.detach_and_log_err(cx)
 5640        }
 5641    }
 5642
 5643    pub fn unfollow(
 5644        &mut self,
 5645        leader_id: impl Into<CollaboratorId>,
 5646        window: &mut Window,
 5647        cx: &mut Context<Self>,
 5648    ) -> Option<()> {
 5649        cx.notify();
 5650
 5651        let leader_id = leader_id.into();
 5652        let state = self.follower_states.remove(&leader_id)?;
 5653        for (_, item) in state.items_by_leader_view_id {
 5654            item.view.set_leader_id(None, window, cx);
 5655        }
 5656
 5657        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5658            let project_id = self.project.read(cx).remote_id();
 5659            let room_id = self.active_call()?.room_id(cx)?;
 5660            self.app_state
 5661                .client
 5662                .send(proto::Unfollow {
 5663                    room_id,
 5664                    project_id,
 5665                    leader_id: Some(leader_peer_id),
 5666                })
 5667                .log_err();
 5668        }
 5669
 5670        Some(())
 5671    }
 5672
 5673    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5674        self.follower_states.contains_key(&id.into())
 5675    }
 5676
 5677    fn active_item_path_changed(
 5678        &mut self,
 5679        focus_changed: bool,
 5680        window: &mut Window,
 5681        cx: &mut Context<Self>,
 5682    ) {
 5683        cx.emit(Event::ActiveItemChanged);
 5684        let active_entry = self.active_project_path(cx);
 5685        self.project.update(cx, |project, cx| {
 5686            project.set_active_path(active_entry.clone(), cx)
 5687        });
 5688
 5689        if focus_changed && let Some(project_path) = &active_entry {
 5690            let git_store_entity = self.project.read(cx).git_store().clone();
 5691            git_store_entity.update(cx, |git_store, cx| {
 5692                git_store.set_active_repo_for_path(project_path, cx);
 5693            });
 5694        }
 5695
 5696        self.update_window_title(window, cx);
 5697    }
 5698
 5699    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5700        let project = self.project().read(cx);
 5701        let mut title = String::new();
 5702
 5703        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5704            let name = {
 5705                let settings_location = SettingsLocation {
 5706                    worktree_id: worktree.read(cx).id(),
 5707                    path: RelPath::empty(),
 5708                };
 5709
 5710                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5711                match &settings.project_name {
 5712                    Some(name) => name.as_str(),
 5713                    None => worktree.read(cx).root_name_str(),
 5714                }
 5715            };
 5716            if i > 0 {
 5717                title.push_str(", ");
 5718            }
 5719            title.push_str(name);
 5720        }
 5721
 5722        if title.is_empty() {
 5723            title = "empty project".to_string();
 5724        }
 5725
 5726        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5727            let filename = path.path.file_name().or_else(|| {
 5728                Some(
 5729                    project
 5730                        .worktree_for_id(path.worktree_id, cx)?
 5731                        .read(cx)
 5732                        .root_name_str(),
 5733                )
 5734            });
 5735
 5736            if let Some(filename) = filename {
 5737                title.push_str("");
 5738                title.push_str(filename.as_ref());
 5739            }
 5740        }
 5741
 5742        if project.is_via_collab() {
 5743            title.push_str("");
 5744        } else if project.is_shared() {
 5745            title.push_str("");
 5746        }
 5747
 5748        if let Some(last_title) = self.last_window_title.as_ref()
 5749            && &title == last_title
 5750        {
 5751            return;
 5752        }
 5753        window.set_window_title(&title);
 5754        SystemWindowTabController::update_tab_title(
 5755            cx,
 5756            window.window_handle().window_id(),
 5757            SharedString::from(&title),
 5758        );
 5759        self.last_window_title = Some(title);
 5760    }
 5761
 5762    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5763        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5764        if is_edited != self.window_edited {
 5765            self.window_edited = is_edited;
 5766            window.set_window_edited(self.window_edited)
 5767        }
 5768    }
 5769
 5770    fn update_item_dirty_state(
 5771        &mut self,
 5772        item: &dyn ItemHandle,
 5773        window: &mut Window,
 5774        cx: &mut App,
 5775    ) {
 5776        let is_dirty = item.is_dirty(cx);
 5777        let item_id = item.item_id();
 5778        let was_dirty = self.dirty_items.contains_key(&item_id);
 5779        if is_dirty == was_dirty {
 5780            return;
 5781        }
 5782        if was_dirty {
 5783            self.dirty_items.remove(&item_id);
 5784            self.update_window_edited(window, cx);
 5785            return;
 5786        }
 5787
 5788        let workspace = self.weak_handle();
 5789        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5790            return;
 5791        };
 5792        let on_release_callback = Box::new(move |cx: &mut App| {
 5793            window_handle
 5794                .update(cx, |_, window, cx| {
 5795                    workspace
 5796                        .update(cx, |workspace, cx| {
 5797                            workspace.dirty_items.remove(&item_id);
 5798                            workspace.update_window_edited(window, cx)
 5799                        })
 5800                        .ok();
 5801                })
 5802                .ok();
 5803        });
 5804
 5805        let s = item.on_release(cx, on_release_callback);
 5806        self.dirty_items.insert(item_id, s);
 5807        self.update_window_edited(window, cx);
 5808    }
 5809
 5810    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5811        if self.notifications.is_empty() {
 5812            None
 5813        } else {
 5814            Some(
 5815                div()
 5816                    .absolute()
 5817                    .right_3()
 5818                    .bottom_3()
 5819                    .w_112()
 5820                    .h_full()
 5821                    .flex()
 5822                    .flex_col()
 5823                    .justify_end()
 5824                    .gap_2()
 5825                    .children(
 5826                        self.notifications
 5827                            .iter()
 5828                            .map(|(_, notification)| notification.clone().into_any()),
 5829                    ),
 5830            )
 5831        }
 5832    }
 5833
 5834    // RPC handlers
 5835
 5836    fn active_view_for_follower(
 5837        &self,
 5838        follower_project_id: Option<u64>,
 5839        window: &mut Window,
 5840        cx: &mut Context<Self>,
 5841    ) -> Option<proto::View> {
 5842        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5843        let item = item?;
 5844        let leader_id = self
 5845            .pane_for(&*item)
 5846            .and_then(|pane| self.leader_for_pane(&pane));
 5847        let leader_peer_id = match leader_id {
 5848            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5849            Some(CollaboratorId::Agent) | None => None,
 5850        };
 5851
 5852        let item_handle = item.to_followable_item_handle(cx)?;
 5853        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5854        let variant = item_handle.to_state_proto(window, cx)?;
 5855
 5856        if item_handle.is_project_item(window, cx)
 5857            && (follower_project_id.is_none()
 5858                || follower_project_id != self.project.read(cx).remote_id())
 5859        {
 5860            return None;
 5861        }
 5862
 5863        Some(proto::View {
 5864            id: id.to_proto(),
 5865            leader_id: leader_peer_id,
 5866            variant: Some(variant),
 5867            panel_id: panel_id.map(|id| id as i32),
 5868        })
 5869    }
 5870
 5871    fn handle_follow(
 5872        &mut self,
 5873        follower_project_id: Option<u64>,
 5874        window: &mut Window,
 5875        cx: &mut Context<Self>,
 5876    ) -> proto::FollowResponse {
 5877        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5878
 5879        cx.notify();
 5880        proto::FollowResponse {
 5881            views: active_view.iter().cloned().collect(),
 5882            active_view,
 5883        }
 5884    }
 5885
 5886    fn handle_update_followers(
 5887        &mut self,
 5888        leader_id: PeerId,
 5889        message: proto::UpdateFollowers,
 5890        _window: &mut Window,
 5891        _cx: &mut Context<Self>,
 5892    ) {
 5893        self.leader_updates_tx
 5894            .unbounded_send((leader_id, message))
 5895            .ok();
 5896    }
 5897
 5898    async fn process_leader_update(
 5899        this: &WeakEntity<Self>,
 5900        leader_id: PeerId,
 5901        update: proto::UpdateFollowers,
 5902        cx: &mut AsyncWindowContext,
 5903    ) -> Result<()> {
 5904        match update.variant.context("invalid update")? {
 5905            proto::update_followers::Variant::CreateView(view) => {
 5906                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5907                let should_add_view = this.update(cx, |this, _| {
 5908                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5909                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5910                    } else {
 5911                        anyhow::Ok(false)
 5912                    }
 5913                })??;
 5914
 5915                if should_add_view {
 5916                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5917                }
 5918            }
 5919            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5920                let should_add_view = this.update(cx, |this, _| {
 5921                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5922                        state.active_view_id = update_active_view
 5923                            .view
 5924                            .as_ref()
 5925                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5926
 5927                        if state.active_view_id.is_some_and(|view_id| {
 5928                            !state.items_by_leader_view_id.contains_key(&view_id)
 5929                        }) {
 5930                            anyhow::Ok(true)
 5931                        } else {
 5932                            anyhow::Ok(false)
 5933                        }
 5934                    } else {
 5935                        anyhow::Ok(false)
 5936                    }
 5937                })??;
 5938
 5939                if should_add_view && let Some(view) = update_active_view.view {
 5940                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5941                }
 5942            }
 5943            proto::update_followers::Variant::UpdateView(update_view) => {
 5944                let variant = update_view.variant.context("missing update view variant")?;
 5945                let id = update_view.id.context("missing update view id")?;
 5946                let mut tasks = Vec::new();
 5947                this.update_in(cx, |this, window, cx| {
 5948                    let project = this.project.clone();
 5949                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5950                        let view_id = ViewId::from_proto(id.clone())?;
 5951                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5952                            tasks.push(item.view.apply_update_proto(
 5953                                &project,
 5954                                variant.clone(),
 5955                                window,
 5956                                cx,
 5957                            ));
 5958                        }
 5959                    }
 5960                    anyhow::Ok(())
 5961                })??;
 5962                try_join_all(tasks).await.log_err();
 5963            }
 5964        }
 5965        this.update_in(cx, |this, window, cx| {
 5966            this.leader_updated(leader_id, window, cx)
 5967        })?;
 5968        Ok(())
 5969    }
 5970
 5971    async fn add_view_from_leader(
 5972        this: WeakEntity<Self>,
 5973        leader_id: PeerId,
 5974        view: &proto::View,
 5975        cx: &mut AsyncWindowContext,
 5976    ) -> Result<()> {
 5977        let this = this.upgrade().context("workspace dropped")?;
 5978
 5979        let Some(id) = view.id.clone() else {
 5980            anyhow::bail!("no id for view");
 5981        };
 5982        let id = ViewId::from_proto(id)?;
 5983        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5984
 5985        let pane = this.update(cx, |this, _cx| {
 5986            let state = this
 5987                .follower_states
 5988                .get(&leader_id.into())
 5989                .context("stopped following")?;
 5990            anyhow::Ok(state.pane().clone())
 5991        })?;
 5992        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5993            let client = this.read(cx).client().clone();
 5994            pane.items().find_map(|item| {
 5995                let item = item.to_followable_item_handle(cx)?;
 5996                if item.remote_id(&client, window, cx) == Some(id) {
 5997                    Some(item)
 5998                } else {
 5999                    None
 6000                }
 6001            })
 6002        })?;
 6003        let item = if let Some(existing_item) = existing_item {
 6004            existing_item
 6005        } else {
 6006            let variant = view.variant.clone();
 6007            anyhow::ensure!(variant.is_some(), "missing view variant");
 6008
 6009            let task = cx.update(|window, cx| {
 6010                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 6011            })?;
 6012
 6013            let Some(task) = task else {
 6014                anyhow::bail!(
 6015                    "failed to construct view from leader (maybe from a different version of zed?)"
 6016                );
 6017            };
 6018
 6019            let mut new_item = task.await?;
 6020            pane.update_in(cx, |pane, window, cx| {
 6021                let mut item_to_remove = None;
 6022                for (ix, item) in pane.items().enumerate() {
 6023                    if let Some(item) = item.to_followable_item_handle(cx) {
 6024                        match new_item.dedup(item.as_ref(), window, cx) {
 6025                            Some(item::Dedup::KeepExisting) => {
 6026                                new_item =
 6027                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 6028                                break;
 6029                            }
 6030                            Some(item::Dedup::ReplaceExisting) => {
 6031                                item_to_remove = Some((ix, item.item_id()));
 6032                                break;
 6033                            }
 6034                            None => {}
 6035                        }
 6036                    }
 6037                }
 6038
 6039                if let Some((ix, id)) = item_to_remove {
 6040                    pane.remove_item(id, false, false, window, cx);
 6041                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 6042                }
 6043            })?;
 6044
 6045            new_item
 6046        };
 6047
 6048        this.update_in(cx, |this, window, cx| {
 6049            let state = this.follower_states.get_mut(&leader_id.into())?;
 6050            item.set_leader_id(Some(leader_id.into()), window, cx);
 6051            state.items_by_leader_view_id.insert(
 6052                id,
 6053                FollowerView {
 6054                    view: item,
 6055                    location: panel_id,
 6056                },
 6057            );
 6058
 6059            Some(())
 6060        })
 6061        .context("no follower state")?;
 6062
 6063        Ok(())
 6064    }
 6065
 6066    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6067        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 6068            return;
 6069        };
 6070
 6071        if let Some(agent_location) = self.project.read(cx).agent_location() {
 6072            let buffer_entity_id = agent_location.buffer.entity_id();
 6073            let view_id = ViewId {
 6074                creator: CollaboratorId::Agent,
 6075                id: buffer_entity_id.as_u64(),
 6076            };
 6077            follower_state.active_view_id = Some(view_id);
 6078
 6079            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 6080                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 6081                hash_map::Entry::Vacant(entry) => {
 6082                    let existing_view =
 6083                        follower_state
 6084                            .center_pane
 6085                            .read(cx)
 6086                            .items()
 6087                            .find_map(|item| {
 6088                                let item = item.to_followable_item_handle(cx)?;
 6089                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 6090                                    && item.project_item_model_ids(cx).as_slice()
 6091                                        == [buffer_entity_id]
 6092                                {
 6093                                    Some(item)
 6094                                } else {
 6095                                    None
 6096                                }
 6097                            });
 6098                    let view = existing_view.or_else(|| {
 6099                        agent_location.buffer.upgrade().and_then(|buffer| {
 6100                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 6101                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 6102                            })?
 6103                            .to_followable_item_handle(cx)
 6104                        })
 6105                    });
 6106
 6107                    view.map(|view| {
 6108                        entry.insert(FollowerView {
 6109                            view,
 6110                            location: None,
 6111                        })
 6112                    })
 6113                }
 6114            };
 6115
 6116            if let Some(item) = item {
 6117                item.view
 6118                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 6119                item.view
 6120                    .update_agent_location(agent_location.position, window, cx);
 6121            }
 6122        } else {
 6123            follower_state.active_view_id = None;
 6124        }
 6125
 6126        self.leader_updated(CollaboratorId::Agent, window, cx);
 6127    }
 6128
 6129    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 6130        let mut is_project_item = true;
 6131        let mut update = proto::UpdateActiveView::default();
 6132        if window.is_window_active() {
 6133            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 6134
 6135            if let Some(item) = active_item
 6136                && item.item_focus_handle(cx).contains_focused(window, cx)
 6137            {
 6138                let leader_id = self
 6139                    .pane_for(&*item)
 6140                    .and_then(|pane| self.leader_for_pane(&pane));
 6141                let leader_peer_id = match leader_id {
 6142                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 6143                    Some(CollaboratorId::Agent) | None => None,
 6144                };
 6145
 6146                if let Some(item) = item.to_followable_item_handle(cx) {
 6147                    let id = item
 6148                        .remote_id(&self.app_state.client, window, cx)
 6149                        .map(|id| id.to_proto());
 6150
 6151                    if let Some(id) = id
 6152                        && let Some(variant) = item.to_state_proto(window, cx)
 6153                    {
 6154                        let view = Some(proto::View {
 6155                            id,
 6156                            leader_id: leader_peer_id,
 6157                            variant: Some(variant),
 6158                            panel_id: panel_id.map(|id| id as i32),
 6159                        });
 6160
 6161                        is_project_item = item.is_project_item(window, cx);
 6162                        update = proto::UpdateActiveView { view };
 6163                    };
 6164                }
 6165            }
 6166        }
 6167
 6168        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 6169        if active_view_id != self.last_active_view_id.as_ref() {
 6170            self.last_active_view_id = active_view_id.cloned();
 6171            self.update_followers(
 6172                is_project_item,
 6173                proto::update_followers::Variant::UpdateActiveView(update),
 6174                window,
 6175                cx,
 6176            );
 6177        }
 6178    }
 6179
 6180    fn active_item_for_followers(
 6181        &self,
 6182        window: &mut Window,
 6183        cx: &mut App,
 6184    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 6185        let mut active_item = None;
 6186        let mut panel_id = None;
 6187        for dock in self.all_docks() {
 6188            if dock.focus_handle(cx).contains_focused(window, cx)
 6189                && let Some(panel) = dock.read(cx).active_panel()
 6190                && let Some(pane) = panel.pane(cx)
 6191                && let Some(item) = pane.read(cx).active_item()
 6192            {
 6193                active_item = Some(item);
 6194                panel_id = panel.remote_id();
 6195                break;
 6196            }
 6197        }
 6198
 6199        if active_item.is_none() {
 6200            active_item = self.active_pane().read(cx).active_item();
 6201        }
 6202        (active_item, panel_id)
 6203    }
 6204
 6205    fn update_followers(
 6206        &self,
 6207        project_only: bool,
 6208        update: proto::update_followers::Variant,
 6209        _: &mut Window,
 6210        cx: &mut App,
 6211    ) -> Option<()> {
 6212        // If this update only applies to for followers in the current project,
 6213        // then skip it unless this project is shared. If it applies to all
 6214        // followers, regardless of project, then set `project_id` to none,
 6215        // indicating that it goes to all followers.
 6216        let project_id = if project_only {
 6217            Some(self.project.read(cx).remote_id()?)
 6218        } else {
 6219            None
 6220        };
 6221        self.app_state().workspace_store.update(cx, |store, cx| {
 6222            store.update_followers(project_id, update, cx)
 6223        })
 6224    }
 6225
 6226    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 6227        self.follower_states.iter().find_map(|(leader_id, state)| {
 6228            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 6229                Some(*leader_id)
 6230            } else {
 6231                None
 6232            }
 6233        })
 6234    }
 6235
 6236    fn leader_updated(
 6237        &mut self,
 6238        leader_id: impl Into<CollaboratorId>,
 6239        window: &mut Window,
 6240        cx: &mut Context<Self>,
 6241    ) -> Option<Box<dyn ItemHandle>> {
 6242        cx.notify();
 6243
 6244        let leader_id = leader_id.into();
 6245        let (panel_id, item) = match leader_id {
 6246            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 6247            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 6248        };
 6249
 6250        let state = self.follower_states.get(&leader_id)?;
 6251        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 6252        let pane;
 6253        if let Some(panel_id) = panel_id {
 6254            pane = self
 6255                .activate_panel_for_proto_id(panel_id, window, cx)?
 6256                .pane(cx)?;
 6257            let state = self.follower_states.get_mut(&leader_id)?;
 6258            state.dock_pane = Some(pane.clone());
 6259        } else {
 6260            pane = state.center_pane.clone();
 6261            let state = self.follower_states.get_mut(&leader_id)?;
 6262            if let Some(dock_pane) = state.dock_pane.take() {
 6263                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 6264            }
 6265        }
 6266
 6267        pane.update(cx, |pane, cx| {
 6268            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 6269            if let Some(index) = pane.index_for_item(item.as_ref()) {
 6270                pane.activate_item(index, false, false, window, cx);
 6271            } else {
 6272                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 6273            }
 6274
 6275            if focus_active_item {
 6276                pane.focus_active_item(window, cx)
 6277            }
 6278        });
 6279
 6280        Some(item)
 6281    }
 6282
 6283    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 6284        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 6285        let active_view_id = state.active_view_id?;
 6286        Some(
 6287            state
 6288                .items_by_leader_view_id
 6289                .get(&active_view_id)?
 6290                .view
 6291                .boxed_clone(),
 6292        )
 6293    }
 6294
 6295    fn active_item_for_peer(
 6296        &self,
 6297        peer_id: PeerId,
 6298        window: &mut Window,
 6299        cx: &mut Context<Self>,
 6300    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 6301        let call = self.active_call()?;
 6302        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 6303        let leader_in_this_app;
 6304        let leader_in_this_project;
 6305        match participant.location {
 6306            ParticipantLocation::SharedProject { project_id } => {
 6307                leader_in_this_app = true;
 6308                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 6309            }
 6310            ParticipantLocation::UnsharedProject => {
 6311                leader_in_this_app = true;
 6312                leader_in_this_project = false;
 6313            }
 6314            ParticipantLocation::External => {
 6315                leader_in_this_app = false;
 6316                leader_in_this_project = false;
 6317            }
 6318        };
 6319        let state = self.follower_states.get(&peer_id.into())?;
 6320        let mut item_to_activate = None;
 6321        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 6322            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 6323                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 6324            {
 6325                item_to_activate = Some((item.location, item.view.boxed_clone()));
 6326            }
 6327        } else if let Some(shared_screen) =
 6328            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 6329        {
 6330            item_to_activate = Some((None, Box::new(shared_screen)));
 6331        }
 6332        item_to_activate
 6333    }
 6334
 6335    fn shared_screen_for_peer(
 6336        &self,
 6337        peer_id: PeerId,
 6338        pane: &Entity<Pane>,
 6339        window: &mut Window,
 6340        cx: &mut App,
 6341    ) -> Option<Entity<SharedScreen>> {
 6342        self.active_call()?
 6343            .create_shared_screen(peer_id, pane, window, cx)
 6344    }
 6345
 6346    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6347        if window.is_window_active() {
 6348            self.update_active_view_for_followers(window, cx);
 6349
 6350            if let Some(database_id) = self.database_id {
 6351                let db = WorkspaceDb::global(cx);
 6352                cx.background_spawn(async move { db.update_timestamp(database_id).await })
 6353                    .detach();
 6354            }
 6355        } else {
 6356            for pane in &self.panes {
 6357                pane.update(cx, |pane, cx| {
 6358                    if let Some(item) = pane.active_item() {
 6359                        item.workspace_deactivated(window, cx);
 6360                    }
 6361                    for item in pane.items() {
 6362                        if matches!(
 6363                            item.workspace_settings(cx).autosave,
 6364                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6365                        ) {
 6366                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6367                                .detach_and_log_err(cx);
 6368                        }
 6369                    }
 6370                });
 6371            }
 6372        }
 6373    }
 6374
 6375    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6376        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6377    }
 6378
 6379    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6380        self.active_call.as_ref().map(|(call, _)| call.clone())
 6381    }
 6382
 6383    fn on_active_call_event(
 6384        &mut self,
 6385        event: &ActiveCallEvent,
 6386        window: &mut Window,
 6387        cx: &mut Context<Self>,
 6388    ) {
 6389        match event {
 6390            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6391            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6392                self.leader_updated(participant_id, window, cx);
 6393            }
 6394        }
 6395    }
 6396
 6397    pub fn database_id(&self) -> Option<WorkspaceId> {
 6398        self.database_id
 6399    }
 6400
 6401    #[cfg(any(test, feature = "test-support"))]
 6402    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6403        self.database_id = Some(id);
 6404    }
 6405
 6406    pub fn session_id(&self) -> Option<String> {
 6407        self.session_id.clone()
 6408    }
 6409
 6410    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6411        let Some(display) = window.display(cx) else {
 6412            return Task::ready(());
 6413        };
 6414        let Ok(display_uuid) = display.uuid() else {
 6415            return Task::ready(());
 6416        };
 6417
 6418        let window_bounds = window.inner_window_bounds();
 6419        let database_id = self.database_id;
 6420        let has_paths = !self.root_paths(cx).is_empty();
 6421        let db = WorkspaceDb::global(cx);
 6422        let kvp = db::kvp::KeyValueStore::global(cx);
 6423
 6424        cx.background_executor().spawn(async move {
 6425            if !has_paths {
 6426                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6427                    .await
 6428                    .log_err();
 6429            }
 6430            if let Some(database_id) = database_id {
 6431                db.set_window_open_status(
 6432                    database_id,
 6433                    SerializedWindowBounds(window_bounds),
 6434                    display_uuid,
 6435                )
 6436                .await
 6437                .log_err();
 6438            } else {
 6439                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6440                    .await
 6441                    .log_err();
 6442            }
 6443        })
 6444    }
 6445
 6446    /// Bypass the 200ms serialization throttle and write workspace state to
 6447    /// the DB immediately. Returns a task the caller can await to ensure the
 6448    /// write completes. Used by the quit handler so the most recent state
 6449    /// isn't lost to a pending throttle timer when the process exits.
 6450    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6451        self._schedule_serialize_workspace.take();
 6452        self._serialize_workspace_task.take();
 6453        self.bounds_save_task_queued.take();
 6454
 6455        let bounds_task = self.save_window_bounds(window, cx);
 6456        let serialize_task = self.serialize_workspace_internal(window, cx);
 6457        cx.spawn(async move |_| {
 6458            bounds_task.await;
 6459            serialize_task.await;
 6460        })
 6461    }
 6462
 6463    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6464        let project = self.project().read(cx);
 6465        project
 6466            .visible_worktrees(cx)
 6467            .map(|worktree| worktree.read(cx).abs_path())
 6468            .collect::<Vec<_>>()
 6469    }
 6470
 6471    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6472        match member {
 6473            Member::Axis(PaneAxis { members, .. }) => {
 6474                for child in members.iter() {
 6475                    self.remove_panes(child.clone(), window, cx)
 6476                }
 6477            }
 6478            Member::Pane(pane) => {
 6479                self.force_remove_pane(&pane, &None, window, cx);
 6480            }
 6481        }
 6482    }
 6483
 6484    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6485        self.session_id.take();
 6486        self.serialize_workspace_internal(window, cx)
 6487    }
 6488
 6489    fn force_remove_pane(
 6490        &mut self,
 6491        pane: &Entity<Pane>,
 6492        focus_on: &Option<Entity<Pane>>,
 6493        window: &mut Window,
 6494        cx: &mut Context<Workspace>,
 6495    ) {
 6496        self.panes.retain(|p| p != pane);
 6497        if let Some(focus_on) = focus_on {
 6498            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6499        } else if self.active_pane() == pane {
 6500            let fallback_pane = self.panes.last().unwrap().clone();
 6501            if self.has_active_modal(window, cx) {
 6502                self.set_active_pane(&fallback_pane, window, cx);
 6503            } else {
 6504                fallback_pane.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6505            }
 6506        }
 6507        if self.last_active_center_pane == Some(pane.downgrade()) {
 6508            self.last_active_center_pane = None;
 6509        }
 6510        cx.notify();
 6511    }
 6512
 6513    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6514        if self._schedule_serialize_workspace.is_none() {
 6515            self._schedule_serialize_workspace =
 6516                Some(cx.spawn_in(window, async move |this, cx| {
 6517                    cx.background_executor()
 6518                        .timer(SERIALIZATION_THROTTLE_TIME)
 6519                        .await;
 6520                    this.update_in(cx, |this, window, cx| {
 6521                        this._serialize_workspace_task =
 6522                            Some(this.serialize_workspace_internal(window, cx));
 6523                        this._schedule_serialize_workspace.take();
 6524                    })
 6525                    .log_err();
 6526                }));
 6527        }
 6528    }
 6529
 6530    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6531        let Some(database_id) = self.database_id() else {
 6532            return Task::ready(());
 6533        };
 6534
 6535        fn serialize_pane_handle(
 6536            pane_handle: &Entity<Pane>,
 6537            window: &mut Window,
 6538            cx: &mut App,
 6539        ) -> SerializedPane {
 6540            let (items, active, pinned_count) = {
 6541                let pane = pane_handle.read(cx);
 6542                let active_item_id = pane.active_item().map(|item| item.item_id());
 6543                (
 6544                    pane.items()
 6545                        .filter_map(|handle| {
 6546                            let handle = handle.to_serializable_item_handle(cx)?;
 6547
 6548                            Some(SerializedItem {
 6549                                kind: Arc::from(handle.serialized_item_kind()),
 6550                                item_id: handle.item_id().as_u64(),
 6551                                active: Some(handle.item_id()) == active_item_id,
 6552                                preview: pane.is_active_preview_item(handle.item_id()),
 6553                            })
 6554                        })
 6555                        .collect::<Vec<_>>(),
 6556                    pane.has_focus(window, cx),
 6557                    pane.pinned_count(),
 6558                )
 6559            };
 6560
 6561            SerializedPane::new(items, active, pinned_count)
 6562        }
 6563
 6564        fn build_serialized_pane_group(
 6565            pane_group: &Member,
 6566            window: &mut Window,
 6567            cx: &mut App,
 6568        ) -> SerializedPaneGroup {
 6569            match pane_group {
 6570                Member::Axis(PaneAxis {
 6571                    axis,
 6572                    members,
 6573                    flexes,
 6574                    bounding_boxes: _,
 6575                }) => SerializedPaneGroup::Group {
 6576                    axis: SerializedAxis(*axis),
 6577                    children: members
 6578                        .iter()
 6579                        .map(|member| build_serialized_pane_group(member, window, cx))
 6580                        .collect::<Vec<_>>(),
 6581                    flexes: Some(flexes.lock().clone()),
 6582                },
 6583                Member::Pane(pane_handle) => {
 6584                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6585                }
 6586            }
 6587        }
 6588
 6589        fn build_serialized_docks(
 6590            this: &Workspace,
 6591            window: &mut Window,
 6592            cx: &mut App,
 6593        ) -> DockStructure {
 6594            this.capture_dock_state(window, cx)
 6595        }
 6596
 6597        match self.workspace_location(cx) {
 6598            WorkspaceLocation::Location(location, paths) => {
 6599                let breakpoints = self.project.update(cx, |project, cx| {
 6600                    project
 6601                        .breakpoint_store()
 6602                        .read(cx)
 6603                        .all_source_breakpoints(cx)
 6604                });
 6605                let user_toolchains = self
 6606                    .project
 6607                    .read(cx)
 6608                    .user_toolchains(cx)
 6609                    .unwrap_or_default();
 6610
 6611                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6612                let docks = build_serialized_docks(self, window, cx);
 6613                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6614
 6615                let serialized_workspace = SerializedWorkspace {
 6616                    id: database_id,
 6617                    location,
 6618                    paths,
 6619                    center_group,
 6620                    window_bounds,
 6621                    display: Default::default(),
 6622                    docks,
 6623                    centered_layout: self.centered_layout,
 6624                    session_id: self.session_id.clone(),
 6625                    breakpoints,
 6626                    window_id: Some(window.window_handle().window_id().as_u64()),
 6627                    user_toolchains,
 6628                };
 6629
 6630                let db = WorkspaceDb::global(cx);
 6631                window.spawn(cx, async move |_| {
 6632                    db.save_workspace(serialized_workspace).await;
 6633                })
 6634            }
 6635            WorkspaceLocation::DetachFromSession => {
 6636                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6637                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6638                // Save dock state for empty local workspaces
 6639                let docks = build_serialized_docks(self, window, cx);
 6640                let db = WorkspaceDb::global(cx);
 6641                let kvp = db::kvp::KeyValueStore::global(cx);
 6642                window.spawn(cx, async move |_| {
 6643                    db.set_window_open_status(
 6644                        database_id,
 6645                        window_bounds,
 6646                        display.unwrap_or_default(),
 6647                    )
 6648                    .await
 6649                    .log_err();
 6650                    db.set_session_id(database_id, None).await.log_err();
 6651                    persistence::write_default_dock_state(&kvp, docks)
 6652                        .await
 6653                        .log_err();
 6654                })
 6655            }
 6656            WorkspaceLocation::None => {
 6657                // Save dock state for empty non-local workspaces
 6658                let docks = build_serialized_docks(self, window, cx);
 6659                let kvp = db::kvp::KeyValueStore::global(cx);
 6660                window.spawn(cx, async move |_| {
 6661                    persistence::write_default_dock_state(&kvp, docks)
 6662                        .await
 6663                        .log_err();
 6664                })
 6665            }
 6666        }
 6667    }
 6668
 6669    fn has_any_items_open(&self, cx: &App) -> bool {
 6670        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6671    }
 6672
 6673    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6674        let paths = PathList::new(&self.root_paths(cx));
 6675        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6676            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6677        } else if self.project.read(cx).is_local() {
 6678            if !paths.is_empty() || self.has_any_items_open(cx) {
 6679                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6680            } else {
 6681                WorkspaceLocation::DetachFromSession
 6682            }
 6683        } else {
 6684            WorkspaceLocation::None
 6685        }
 6686    }
 6687
 6688    fn update_history(&self, cx: &mut App) {
 6689        let Some(id) = self.database_id() else {
 6690            return;
 6691        };
 6692        if !self.project.read(cx).is_local() {
 6693            return;
 6694        }
 6695        if let Some(manager) = HistoryManager::global(cx) {
 6696            let paths = PathList::new(&self.root_paths(cx));
 6697            manager.update(cx, |this, cx| {
 6698                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6699            });
 6700        }
 6701    }
 6702
 6703    async fn serialize_items(
 6704        this: &WeakEntity<Self>,
 6705        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6706        cx: &mut AsyncWindowContext,
 6707    ) -> Result<()> {
 6708        const CHUNK_SIZE: usize = 200;
 6709
 6710        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6711
 6712        while let Some(items_received) = serializable_items.next().await {
 6713            let unique_items =
 6714                items_received
 6715                    .into_iter()
 6716                    .fold(HashMap::default(), |mut acc, item| {
 6717                        acc.entry(item.item_id()).or_insert(item);
 6718                        acc
 6719                    });
 6720
 6721            // We use into_iter() here so that the references to the items are moved into
 6722            // the tasks and not kept alive while we're sleeping.
 6723            for (_, item) in unique_items.into_iter() {
 6724                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6725                    item.serialize(workspace, false, window, cx)
 6726                }) {
 6727                    cx.background_spawn(async move { task.await.log_err() })
 6728                        .detach();
 6729                }
 6730            }
 6731
 6732            cx.background_executor()
 6733                .timer(SERIALIZATION_THROTTLE_TIME)
 6734                .await;
 6735        }
 6736
 6737        Ok(())
 6738    }
 6739
 6740    pub(crate) fn enqueue_item_serialization(
 6741        &mut self,
 6742        item: Box<dyn SerializableItemHandle>,
 6743    ) -> Result<()> {
 6744        self.serializable_items_tx
 6745            .unbounded_send(item)
 6746            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6747    }
 6748
 6749    pub(crate) fn load_workspace(
 6750        serialized_workspace: SerializedWorkspace,
 6751        paths_to_open: Vec<Option<ProjectPath>>,
 6752        window: &mut Window,
 6753        cx: &mut Context<Workspace>,
 6754    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6755        cx.spawn_in(window, async move |workspace, cx| {
 6756            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6757
 6758            let mut center_group = None;
 6759            let mut center_items = None;
 6760
 6761            // Traverse the splits tree and add to things
 6762            if let Some((group, active_pane, items)) = serialized_workspace
 6763                .center_group
 6764                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6765                .await
 6766            {
 6767                center_items = Some(items);
 6768                center_group = Some((group, active_pane))
 6769            }
 6770
 6771            let mut items_by_project_path = HashMap::default();
 6772            let mut item_ids_by_kind = HashMap::default();
 6773            let mut all_deserialized_items = Vec::default();
 6774            cx.update(|_, cx| {
 6775                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6776                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6777                        item_ids_by_kind
 6778                            .entry(serializable_item_handle.serialized_item_kind())
 6779                            .or_insert(Vec::new())
 6780                            .push(item.item_id().as_u64() as ItemId);
 6781                    }
 6782
 6783                    if let Some(project_path) = item.project_path(cx) {
 6784                        items_by_project_path.insert(project_path, item.clone());
 6785                    }
 6786                    all_deserialized_items.push(item);
 6787                }
 6788            })?;
 6789
 6790            let opened_items = paths_to_open
 6791                .into_iter()
 6792                .map(|path_to_open| {
 6793                    path_to_open
 6794                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6795                })
 6796                .collect::<Vec<_>>();
 6797
 6798            // Remove old panes from workspace panes list
 6799            workspace.update_in(cx, |workspace, window, cx| {
 6800                if let Some((center_group, active_pane)) = center_group {
 6801                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6802
 6803                    // Swap workspace center group
 6804                    workspace.center = PaneGroup::with_root(center_group);
 6805                    workspace.center.set_is_center(true);
 6806                    workspace.center.mark_positions(cx);
 6807
 6808                    if let Some(active_pane) = active_pane {
 6809                        workspace.set_active_pane(&active_pane, window, cx);
 6810                        cx.focus_self(window);
 6811                    } else {
 6812                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6813                    }
 6814                }
 6815
 6816                let docks = serialized_workspace.docks;
 6817
 6818                for (dock, serialized_dock) in [
 6819                    (&mut workspace.right_dock, docks.right),
 6820                    (&mut workspace.left_dock, docks.left),
 6821                    (&mut workspace.bottom_dock, docks.bottom),
 6822                ]
 6823                .iter_mut()
 6824                {
 6825                    dock.update(cx, |dock, cx| {
 6826                        dock.serialized_dock = Some(serialized_dock.clone());
 6827                        dock.restore_state(window, cx);
 6828                    });
 6829                }
 6830
 6831                cx.notify();
 6832            })?;
 6833
 6834            let _ = project
 6835                .update(cx, |project, cx| {
 6836                    project
 6837                        .breakpoint_store()
 6838                        .update(cx, |breakpoint_store, cx| {
 6839                            breakpoint_store
 6840                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6841                        })
 6842                })
 6843                .await;
 6844
 6845            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6846            // after loading the items, we might have different items and in order to avoid
 6847            // the database filling up, we delete items that haven't been loaded now.
 6848            //
 6849            // The items that have been loaded, have been saved after they've been added to the workspace.
 6850            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6851                item_ids_by_kind
 6852                    .into_iter()
 6853                    .map(|(item_kind, loaded_items)| {
 6854                        SerializableItemRegistry::cleanup(
 6855                            item_kind,
 6856                            serialized_workspace.id,
 6857                            loaded_items,
 6858                            window,
 6859                            cx,
 6860                        )
 6861                        .log_err()
 6862                    })
 6863                    .collect::<Vec<_>>()
 6864            })?;
 6865
 6866            futures::future::join_all(clean_up_tasks).await;
 6867
 6868            workspace
 6869                .update_in(cx, |workspace, window, cx| {
 6870                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6871                    workspace.serialize_workspace_internal(window, cx).detach();
 6872
 6873                    // Ensure that we mark the window as edited if we did load dirty items
 6874                    workspace.update_window_edited(window, cx);
 6875                })
 6876                .ok();
 6877
 6878            Ok(opened_items)
 6879        })
 6880    }
 6881
 6882    pub fn key_context(&self, cx: &App) -> KeyContext {
 6883        let mut context = KeyContext::new_with_defaults();
 6884        context.add("Workspace");
 6885        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6886        if let Some(status) = self
 6887            .debugger_provider
 6888            .as_ref()
 6889            .and_then(|provider| provider.active_thread_state(cx))
 6890        {
 6891            match status {
 6892                ThreadStatus::Running | ThreadStatus::Stepping => {
 6893                    context.add("debugger_running");
 6894                }
 6895                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6896                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6897            }
 6898        }
 6899
 6900        if self.left_dock.read(cx).is_open() {
 6901            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6902                context.set("left_dock", active_panel.panel_key());
 6903            }
 6904        }
 6905
 6906        if self.right_dock.read(cx).is_open() {
 6907            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6908                context.set("right_dock", active_panel.panel_key());
 6909            }
 6910        }
 6911
 6912        if self.bottom_dock.read(cx).is_open() {
 6913            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6914                context.set("bottom_dock", active_panel.panel_key());
 6915            }
 6916        }
 6917
 6918        context
 6919    }
 6920
 6921    /// Multiworkspace uses this to add workspace action handling to itself
 6922    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6923        self.add_workspace_actions_listeners(div, window, cx)
 6924            .on_action(cx.listener(
 6925                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6926                    for action in &action_sequence.0 {
 6927                        window.dispatch_action(action.boxed_clone(), cx);
 6928                    }
 6929                },
 6930            ))
 6931            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6932            .on_action(cx.listener(Self::close_all_items_and_panes))
 6933            .on_action(cx.listener(Self::close_item_in_all_panes))
 6934            .on_action(cx.listener(Self::save_all))
 6935            .on_action(cx.listener(Self::send_keystrokes))
 6936            .on_action(cx.listener(Self::add_folder_to_project))
 6937            .on_action(cx.listener(Self::follow_next_collaborator))
 6938            .on_action(cx.listener(Self::activate_pane_at_index))
 6939            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6940            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6941            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6942            .on_action(cx.listener(Self::toggle_theme_mode))
 6943            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6944                let pane = workspace.active_pane().clone();
 6945                workspace.unfollow_in_pane(&pane, window, cx);
 6946            }))
 6947            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6948                workspace
 6949                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6950                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6951            }))
 6952            .on_action(cx.listener(|workspace, _: &FormatAndSave, window, cx| {
 6953                workspace
 6954                    .save_active_item(SaveIntent::FormatAndSave, window, cx)
 6955                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6956            }))
 6957            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6958                workspace
 6959                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6960                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6961            }))
 6962            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6963                workspace
 6964                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6965                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6966            }))
 6967            .on_action(
 6968                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6969                    workspace.activate_previous_pane(window, cx)
 6970                }),
 6971            )
 6972            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6973                workspace.activate_next_pane(window, cx)
 6974            }))
 6975            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6976                workspace.activate_last_pane(window, cx)
 6977            }))
 6978            .on_action(
 6979                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6980                    workspace.activate_next_window(cx)
 6981                }),
 6982            )
 6983            .on_action(
 6984                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6985                    workspace.activate_previous_window(cx)
 6986                }),
 6987            )
 6988            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6989                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6990            }))
 6991            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6992                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6993            }))
 6994            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6995                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6996            }))
 6997            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6998                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6999            }))
 7000            .on_action(cx.listener(
 7001                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 7002                    workspace.move_item_to_pane_in_direction(action, window, cx)
 7003                },
 7004            ))
 7005            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 7006                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 7007            }))
 7008            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 7009                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 7010            }))
 7011            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 7012                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 7013            }))
 7014            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 7015                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 7016            }))
 7017            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 7018                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 7019                    SplitDirection::Down,
 7020                    SplitDirection::Up,
 7021                    SplitDirection::Right,
 7022                    SplitDirection::Left,
 7023                ];
 7024                for dir in DIRECTION_PRIORITY {
 7025                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 7026                        workspace.swap_pane_in_direction(dir, cx);
 7027                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 7028                        break;
 7029                    }
 7030                }
 7031            }))
 7032            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 7033                workspace.move_pane_to_border(SplitDirection::Left, cx)
 7034            }))
 7035            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 7036                workspace.move_pane_to_border(SplitDirection::Right, cx)
 7037            }))
 7038            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 7039                workspace.move_pane_to_border(SplitDirection::Up, cx)
 7040            }))
 7041            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 7042                workspace.move_pane_to_border(SplitDirection::Down, cx)
 7043            }))
 7044            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 7045                this.toggle_dock(DockPosition::Left, window, cx);
 7046            }))
 7047            .on_action(cx.listener(
 7048                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 7049                    workspace.toggle_dock(DockPosition::Right, window, cx);
 7050                },
 7051            ))
 7052            .on_action(cx.listener(
 7053                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 7054                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 7055                },
 7056            ))
 7057            .on_action(cx.listener(
 7058                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 7059                    if !workspace.close_active_dock(window, cx) {
 7060                        cx.propagate();
 7061                    }
 7062                },
 7063            ))
 7064            .on_action(
 7065                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 7066                    workspace.close_all_docks(window, cx);
 7067                }),
 7068            )
 7069            .on_action(cx.listener(Self::toggle_all_docks))
 7070            .on_action(cx.listener(
 7071                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 7072                    workspace.clear_all_notifications(cx);
 7073                },
 7074            ))
 7075            .on_action(cx.listener(
 7076                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 7077                    workspace.clear_navigation_history(window, cx);
 7078                },
 7079            ))
 7080            .on_action(cx.listener(
 7081                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 7082                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 7083                        workspace.suppress_notification(&notification_id, cx);
 7084                    }
 7085                },
 7086            ))
 7087            .on_action(cx.listener(
 7088                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 7089                    workspace.show_worktree_trust_security_modal(true, window, cx);
 7090                },
 7091            ))
 7092            .on_action(
 7093                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 7094                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 7095                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 7096                            trusted_worktrees.clear_trusted_paths()
 7097                        });
 7098                        let db = WorkspaceDb::global(cx);
 7099                        cx.spawn(async move |_, cx| {
 7100                            if db.clear_trusted_worktrees().await.log_err().is_some() {
 7101                                cx.update(|cx| reload(cx));
 7102                            }
 7103                        })
 7104                        .detach();
 7105                    }
 7106                }),
 7107            )
 7108            .on_action(cx.listener(
 7109                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 7110                    workspace.reopen_closed_item(window, cx).detach();
 7111                },
 7112            ))
 7113            .on_action(cx.listener(
 7114                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 7115                    for dock in workspace.all_docks() {
 7116                        if dock.focus_handle(cx).contains_focused(window, cx) {
 7117                            let panel = dock.read(cx).active_panel().cloned();
 7118                            if let Some(panel) = panel {
 7119                                dock.update(cx, |dock, cx| {
 7120                                    dock.set_panel_size_state(
 7121                                        panel.as_ref(),
 7122                                        dock::PanelSizeState::default(),
 7123                                        cx,
 7124                                    );
 7125                                });
 7126                            }
 7127                            return;
 7128                        }
 7129                    }
 7130                },
 7131            ))
 7132            .on_action(cx.listener(
 7133                |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
 7134                    for dock in workspace.all_docks() {
 7135                        let panel = dock.read(cx).visible_panel().cloned();
 7136                        if let Some(panel) = panel {
 7137                            dock.update(cx, |dock, cx| {
 7138                                dock.set_panel_size_state(
 7139                                    panel.as_ref(),
 7140                                    dock::PanelSizeState::default(),
 7141                                    cx,
 7142                                );
 7143                            });
 7144                        }
 7145                    }
 7146                },
 7147            ))
 7148            .on_action(cx.listener(
 7149                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 7150                    adjust_active_dock_size_by_px(
 7151                        px_with_ui_font_fallback(act.px, cx),
 7152                        workspace,
 7153                        window,
 7154                        cx,
 7155                    );
 7156                },
 7157            ))
 7158            .on_action(cx.listener(
 7159                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 7160                    adjust_active_dock_size_by_px(
 7161                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7162                        workspace,
 7163                        window,
 7164                        cx,
 7165                    );
 7166                },
 7167            ))
 7168            .on_action(cx.listener(
 7169                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 7170                    adjust_open_docks_size_by_px(
 7171                        px_with_ui_font_fallback(act.px, cx),
 7172                        workspace,
 7173                        window,
 7174                        cx,
 7175                    );
 7176                },
 7177            ))
 7178            .on_action(cx.listener(
 7179                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 7180                    adjust_open_docks_size_by_px(
 7181                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7182                        workspace,
 7183                        window,
 7184                        cx,
 7185                    );
 7186                },
 7187            ))
 7188            .on_action(cx.listener(Workspace::toggle_centered_layout))
 7189            .on_action(cx.listener(
 7190                |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
 7191                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7192                        let dock = active_dock.read(cx);
 7193                        if let Some(active_panel) = dock.active_panel() {
 7194                            if active_panel.pane(cx).is_none() {
 7195                                let mut recent_pane: Option<Entity<Pane>> = None;
 7196                                let mut recent_timestamp = 0;
 7197                                for pane_handle in workspace.panes() {
 7198                                    let pane = pane_handle.read(cx);
 7199                                    for entry in pane.activation_history() {
 7200                                        if entry.timestamp > recent_timestamp {
 7201                                            recent_timestamp = entry.timestamp;
 7202                                            recent_pane = Some(pane_handle.clone());
 7203                                        }
 7204                                    }
 7205                                }
 7206
 7207                                if let Some(pane) = recent_pane {
 7208                                    let wrap_around = action.wrap_around;
 7209                                    pane.update(cx, |pane, cx| {
 7210                                        let current_index = pane.active_item_index();
 7211                                        let items_len = pane.items_len();
 7212                                        if items_len > 0 {
 7213                                            let next_index = if current_index + 1 < items_len {
 7214                                                current_index + 1
 7215                                            } else if wrap_around {
 7216                                                0
 7217                                            } else {
 7218                                                return;
 7219                                            };
 7220                                            pane.activate_item(
 7221                                                next_index, false, false, window, cx,
 7222                                            );
 7223                                        }
 7224                                    });
 7225                                    return;
 7226                                }
 7227                            }
 7228                        }
 7229                    }
 7230                    cx.propagate();
 7231                },
 7232            ))
 7233            .on_action(cx.listener(
 7234                |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
 7235                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7236                        let dock = active_dock.read(cx);
 7237                        if let Some(active_panel) = dock.active_panel() {
 7238                            if active_panel.pane(cx).is_none() {
 7239                                let mut recent_pane: Option<Entity<Pane>> = None;
 7240                                let mut recent_timestamp = 0;
 7241                                for pane_handle in workspace.panes() {
 7242                                    let pane = pane_handle.read(cx);
 7243                                    for entry in pane.activation_history() {
 7244                                        if entry.timestamp > recent_timestamp {
 7245                                            recent_timestamp = entry.timestamp;
 7246                                            recent_pane = Some(pane_handle.clone());
 7247                                        }
 7248                                    }
 7249                                }
 7250
 7251                                if let Some(pane) = recent_pane {
 7252                                    let wrap_around = action.wrap_around;
 7253                                    pane.update(cx, |pane, cx| {
 7254                                        let current_index = pane.active_item_index();
 7255                                        let items_len = pane.items_len();
 7256                                        if items_len > 0 {
 7257                                            let prev_index = if current_index > 0 {
 7258                                                current_index - 1
 7259                                            } else if wrap_around {
 7260                                                items_len.saturating_sub(1)
 7261                                            } else {
 7262                                                return;
 7263                                            };
 7264                                            pane.activate_item(
 7265                                                prev_index, false, false, window, cx,
 7266                                            );
 7267                                        }
 7268                                    });
 7269                                    return;
 7270                                }
 7271                            }
 7272                        }
 7273                    }
 7274                    cx.propagate();
 7275                },
 7276            ))
 7277            .on_action(cx.listener(
 7278                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 7279                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7280                        let dock = active_dock.read(cx);
 7281                        if let Some(active_panel) = dock.active_panel() {
 7282                            if active_panel.pane(cx).is_none() {
 7283                                let active_pane = workspace.active_pane().clone();
 7284                                active_pane.update(cx, |pane, cx| {
 7285                                    pane.close_active_item(action, window, cx)
 7286                                        .detach_and_log_err(cx);
 7287                                });
 7288                                return;
 7289                            }
 7290                        }
 7291                    }
 7292                    cx.propagate();
 7293                },
 7294            ))
 7295            .on_action(
 7296                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 7297                    let pane = workspace.active_pane().clone();
 7298                    if let Some(item) = pane.read(cx).active_item() {
 7299                        item.toggle_read_only(window, cx);
 7300                    }
 7301                }),
 7302            )
 7303            .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
 7304                workspace.focus_center_pane(window, cx);
 7305            }))
 7306            .on_action(cx.listener(Workspace::cancel))
 7307    }
 7308
 7309    #[cfg(any(test, feature = "test-support"))]
 7310    pub fn set_random_database_id(&mut self) {
 7311        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 7312    }
 7313
 7314    #[cfg(any(test, feature = "test-support"))]
 7315    pub(crate) fn test_new(
 7316        project: Entity<Project>,
 7317        window: &mut Window,
 7318        cx: &mut Context<Self>,
 7319    ) -> Self {
 7320        use node_runtime::NodeRuntime;
 7321        use session::Session;
 7322
 7323        let client = project.read(cx).client();
 7324        let user_store = project.read(cx).user_store();
 7325        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 7326        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 7327        window.activate_window();
 7328        let app_state = Arc::new(AppState {
 7329            languages: project.read(cx).languages().clone(),
 7330            workspace_store,
 7331            client,
 7332            user_store,
 7333            fs: project.read(cx).fs().clone(),
 7334            build_window_options: |_, _| Default::default(),
 7335            node_runtime: NodeRuntime::unavailable(),
 7336            session,
 7337        });
 7338        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 7339        workspace
 7340            .active_pane
 7341            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 7342        workspace
 7343    }
 7344
 7345    pub fn register_action<A: Action>(
 7346        &mut self,
 7347        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 7348    ) -> &mut Self {
 7349        let callback = Arc::new(callback);
 7350
 7351        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 7352            let callback = callback.clone();
 7353            div.on_action(cx.listener(move |workspace, event, window, cx| {
 7354                (callback)(workspace, event, window, cx)
 7355            }))
 7356        }));
 7357        self
 7358    }
 7359    pub fn register_action_renderer(
 7360        &mut self,
 7361        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 7362    ) -> &mut Self {
 7363        self.workspace_actions.push(Box::new(callback));
 7364        self
 7365    }
 7366
 7367    fn add_workspace_actions_listeners(
 7368        &self,
 7369        mut div: Div,
 7370        window: &mut Window,
 7371        cx: &mut Context<Self>,
 7372    ) -> Div {
 7373        for action in self.workspace_actions.iter() {
 7374            div = (action)(div, self, window, cx)
 7375        }
 7376        div
 7377    }
 7378
 7379    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 7380        self.modal_layer.read(cx).has_active_modal()
 7381    }
 7382
 7383    pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
 7384        self.modal_layer
 7385            .read(cx)
 7386            .is_active_modal_command_palette(cx)
 7387    }
 7388
 7389    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7390        self.modal_layer.read(cx).active_modal()
 7391    }
 7392
 7393    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7394    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7395    /// If no modal is active, the new modal will be shown.
 7396    ///
 7397    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7398    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7399    /// will not be shown.
 7400    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7401    where
 7402        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7403    {
 7404        self.modal_layer.update(cx, |modal_layer, cx| {
 7405            modal_layer.toggle_modal(window, cx, build)
 7406        })
 7407    }
 7408
 7409    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7410        self.modal_layer
 7411            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7412    }
 7413
 7414    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7415        self.toast_layer
 7416            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7417    }
 7418
 7419    pub fn toggle_centered_layout(
 7420        &mut self,
 7421        _: &ToggleCenteredLayout,
 7422        _: &mut Window,
 7423        cx: &mut Context<Self>,
 7424    ) {
 7425        self.centered_layout = !self.centered_layout;
 7426        if let Some(database_id) = self.database_id() {
 7427            let db = WorkspaceDb::global(cx);
 7428            let centered_layout = self.centered_layout;
 7429            cx.background_spawn(async move {
 7430                db.set_centered_layout(database_id, centered_layout).await
 7431            })
 7432            .detach_and_log_err(cx);
 7433        }
 7434        cx.notify();
 7435    }
 7436
 7437    fn adjust_padding(padding: Option<f32>) -> f32 {
 7438        padding
 7439            .unwrap_or(CenteredPaddingSettings::default().0)
 7440            .clamp(
 7441                CenteredPaddingSettings::MIN_PADDING,
 7442                CenteredPaddingSettings::MAX_PADDING,
 7443            )
 7444    }
 7445
 7446    fn render_dock(
 7447        &self,
 7448        position: DockPosition,
 7449        dock: &Entity<Dock>,
 7450        window: &mut Window,
 7451        cx: &mut App,
 7452    ) -> Option<Div> {
 7453        if self.zoomed_position == Some(position) {
 7454            return None;
 7455        }
 7456
 7457        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7458            let pane = panel.pane(cx)?;
 7459            let follower_states = &self.follower_states;
 7460            leader_border_for_pane(follower_states, &pane, window, cx)
 7461        });
 7462
 7463        let mut container = div()
 7464            .flex()
 7465            .overflow_hidden()
 7466            .flex_none()
 7467            .child(dock.clone())
 7468            .children(leader_border);
 7469
 7470        // Apply sizing only when the dock is open. When closed the dock is still
 7471        // included in the element tree so its focus handle remains mounted — without
 7472        // this, toggle_panel_focus cannot focus the panel when the dock is closed.
 7473        let dock = dock.read(cx);
 7474        if let Some(panel) = dock.visible_panel() {
 7475            let size_state = dock.stored_panel_size_state(panel.as_ref());
 7476            let min_size = panel.min_size(window, cx);
 7477            if position.axis() == Axis::Horizontal {
 7478                let use_flexible = panel.has_flexible_size(window, cx);
 7479                let flex_grow = if use_flexible {
 7480                    size_state
 7481                        .and_then(|state| state.flex)
 7482                        .or_else(|| self.default_dock_flex(position))
 7483                } else {
 7484                    None
 7485                };
 7486                if let Some(grow) = flex_grow {
 7487                    let grow = grow.max(0.001);
 7488                    let style = container.style();
 7489                    style.flex_grow = Some(grow);
 7490                    style.flex_shrink = Some(1.0);
 7491                    style.flex_basis = Some(relative(0.).into());
 7492                } else {
 7493                    let size = size_state
 7494                        .and_then(|state| state.size)
 7495                        .unwrap_or_else(|| panel.default_size(window, cx));
 7496                    container = container.w(size);
 7497                }
 7498                if let Some(min) = min_size {
 7499                    container = container.min_w(min);
 7500                }
 7501            } else {
 7502                let size = size_state
 7503                    .and_then(|state| state.size)
 7504                    .unwrap_or_else(|| panel.default_size(window, cx));
 7505                container = container.h(size);
 7506            }
 7507        }
 7508
 7509        Some(container)
 7510    }
 7511
 7512    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7513        window
 7514            .root::<MultiWorkspace>()
 7515            .flatten()
 7516            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7517    }
 7518
 7519    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7520        self.zoomed.as_ref()
 7521    }
 7522
 7523    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7524        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7525            return;
 7526        };
 7527        let windows = cx.windows();
 7528        let next_window =
 7529            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7530                || {
 7531                    windows
 7532                        .iter()
 7533                        .cycle()
 7534                        .skip_while(|window| window.window_id() != current_window_id)
 7535                        .nth(1)
 7536                },
 7537            );
 7538
 7539        if let Some(window) = next_window {
 7540            window
 7541                .update(cx, |_, window, _| window.activate_window())
 7542                .ok();
 7543        }
 7544    }
 7545
 7546    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7547        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7548            return;
 7549        };
 7550        let windows = cx.windows();
 7551        let prev_window =
 7552            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7553                || {
 7554                    windows
 7555                        .iter()
 7556                        .rev()
 7557                        .cycle()
 7558                        .skip_while(|window| window.window_id() != current_window_id)
 7559                        .nth(1)
 7560                },
 7561            );
 7562
 7563        if let Some(window) = prev_window {
 7564            window
 7565                .update(cx, |_, window, _| window.activate_window())
 7566                .ok();
 7567        }
 7568    }
 7569
 7570    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7571        if cx.stop_active_drag(window) {
 7572        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7573            dismiss_app_notification(&notification_id, cx);
 7574        } else {
 7575            cx.propagate();
 7576        }
 7577    }
 7578
 7579    fn resize_dock(
 7580        &mut self,
 7581        dock_pos: DockPosition,
 7582        new_size: Pixels,
 7583        window: &mut Window,
 7584        cx: &mut Context<Self>,
 7585    ) {
 7586        match dock_pos {
 7587            DockPosition::Left => self.resize_left_dock(new_size, window, cx),
 7588            DockPosition::Right => self.resize_right_dock(new_size, window, cx),
 7589            DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
 7590        }
 7591    }
 7592
 7593    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7594        let workspace_width = self.bounds.size.width;
 7595        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7596
 7597        self.right_dock.read_with(cx, |right_dock, cx| {
 7598            let right_dock_size = right_dock
 7599                .stored_active_panel_size(window, cx)
 7600                .unwrap_or(Pixels::ZERO);
 7601            if right_dock_size + size > workspace_width {
 7602                size = workspace_width - right_dock_size
 7603            }
 7604        });
 7605
 7606        let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
 7607        self.left_dock.update(cx, |left_dock, cx| {
 7608            if WorkspaceSettings::get_global(cx)
 7609                .resize_all_panels_in_dock
 7610                .contains(&DockPosition::Left)
 7611            {
 7612                left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7613            } else {
 7614                left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7615            }
 7616        });
 7617    }
 7618
 7619    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7620        let workspace_width = self.bounds.size.width;
 7621        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7622        self.left_dock.read_with(cx, |left_dock, cx| {
 7623            let left_dock_size = left_dock
 7624                .stored_active_panel_size(window, cx)
 7625                .unwrap_or(Pixels::ZERO);
 7626            if left_dock_size + size > workspace_width {
 7627                size = workspace_width - left_dock_size
 7628            }
 7629        });
 7630        let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
 7631        self.right_dock.update(cx, |right_dock, cx| {
 7632            if WorkspaceSettings::get_global(cx)
 7633                .resize_all_panels_in_dock
 7634                .contains(&DockPosition::Right)
 7635            {
 7636                right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7637            } else {
 7638                right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7639            }
 7640        });
 7641    }
 7642
 7643    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7644        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7645        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7646            if WorkspaceSettings::get_global(cx)
 7647                .resize_all_panels_in_dock
 7648                .contains(&DockPosition::Bottom)
 7649            {
 7650                bottom_dock.resize_all_panels(Some(size), None, window, cx);
 7651            } else {
 7652                bottom_dock.resize_active_panel(Some(size), None, window, cx);
 7653            }
 7654        });
 7655    }
 7656
 7657    fn toggle_edit_predictions_all_files(
 7658        &mut self,
 7659        _: &ToggleEditPrediction,
 7660        _window: &mut Window,
 7661        cx: &mut Context<Self>,
 7662    ) {
 7663        let fs = self.project().read(cx).fs().clone();
 7664        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7665        update_settings_file(fs, cx, move |file, _| {
 7666            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7667        });
 7668    }
 7669
 7670    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7671        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7672        let next_mode = match current_mode {
 7673            Some(theme_settings::ThemeAppearanceMode::Light) => {
 7674                theme_settings::ThemeAppearanceMode::Dark
 7675            }
 7676            Some(theme_settings::ThemeAppearanceMode::Dark) => {
 7677                theme_settings::ThemeAppearanceMode::Light
 7678            }
 7679            Some(theme_settings::ThemeAppearanceMode::System) | None => {
 7680                match cx.theme().appearance() {
 7681                    theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
 7682                    theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
 7683                }
 7684            }
 7685        };
 7686
 7687        let fs = self.project().read(cx).fs().clone();
 7688        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7689            theme_settings::set_mode(settings, next_mode);
 7690        });
 7691    }
 7692
 7693    pub fn show_worktree_trust_security_modal(
 7694        &mut self,
 7695        toggle: bool,
 7696        window: &mut Window,
 7697        cx: &mut Context<Self>,
 7698    ) {
 7699        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7700            if toggle {
 7701                security_modal.update(cx, |security_modal, cx| {
 7702                    security_modal.dismiss(cx);
 7703                })
 7704            } else {
 7705                security_modal.update(cx, |security_modal, cx| {
 7706                    security_modal.refresh_restricted_paths(cx);
 7707                });
 7708            }
 7709        } else {
 7710            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7711                .map(|trusted_worktrees| {
 7712                    trusted_worktrees
 7713                        .read(cx)
 7714                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7715                })
 7716                .unwrap_or(false);
 7717            if has_restricted_worktrees {
 7718                let project = self.project().read(cx);
 7719                let remote_host = project
 7720                    .remote_connection_options(cx)
 7721                    .map(RemoteHostLocation::from);
 7722                let worktree_store = project.worktree_store().downgrade();
 7723                self.toggle_modal(window, cx, |_, cx| {
 7724                    SecurityModal::new(worktree_store, remote_host, cx)
 7725                });
 7726            }
 7727        }
 7728    }
 7729}
 7730
 7731pub trait AnyActiveCall {
 7732    fn entity(&self) -> AnyEntity;
 7733    fn is_in_room(&self, _: &App) -> bool;
 7734    fn room_id(&self, _: &App) -> Option<u64>;
 7735    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7736    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7737    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7738    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7739    fn is_sharing_project(&self, _: &App) -> bool;
 7740    fn has_remote_participants(&self, _: &App) -> bool;
 7741    fn local_participant_is_guest(&self, _: &App) -> bool;
 7742    fn client(&self, _: &App) -> Arc<Client>;
 7743    fn share_on_join(&self, _: &App) -> bool;
 7744    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7745    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7746    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7747    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7748    fn join_project(
 7749        &self,
 7750        _: u64,
 7751        _: Arc<LanguageRegistry>,
 7752        _: Arc<dyn Fs>,
 7753        _: &mut App,
 7754    ) -> Task<Result<Entity<Project>>>;
 7755    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7756    fn subscribe(
 7757        &self,
 7758        _: &mut Window,
 7759        _: &mut Context<Workspace>,
 7760        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7761    ) -> Subscription;
 7762    fn create_shared_screen(
 7763        &self,
 7764        _: PeerId,
 7765        _: &Entity<Pane>,
 7766        _: &mut Window,
 7767        _: &mut App,
 7768    ) -> Option<Entity<SharedScreen>>;
 7769}
 7770
 7771#[derive(Clone)]
 7772pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7773impl Global for GlobalAnyActiveCall {}
 7774
 7775impl GlobalAnyActiveCall {
 7776    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7777        cx.try_global()
 7778    }
 7779
 7780    pub(crate) fn global(cx: &App) -> &Self {
 7781        cx.global()
 7782    }
 7783}
 7784
 7785/// Workspace-local view of a remote participant's location.
 7786#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7787pub enum ParticipantLocation {
 7788    SharedProject { project_id: u64 },
 7789    UnsharedProject,
 7790    External,
 7791}
 7792
 7793impl ParticipantLocation {
 7794    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7795        match location
 7796            .and_then(|l| l.variant)
 7797            .context("participant location was not provided")?
 7798        {
 7799            proto::participant_location::Variant::SharedProject(project) => {
 7800                Ok(Self::SharedProject {
 7801                    project_id: project.id,
 7802                })
 7803            }
 7804            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7805            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7806        }
 7807    }
 7808}
 7809/// Workspace-local view of a remote collaborator's state.
 7810/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7811#[derive(Clone)]
 7812pub struct RemoteCollaborator {
 7813    pub user: Arc<User>,
 7814    pub peer_id: PeerId,
 7815    pub location: ParticipantLocation,
 7816    pub participant_index: ParticipantIndex,
 7817}
 7818
 7819pub enum ActiveCallEvent {
 7820    ParticipantLocationChanged { participant_id: PeerId },
 7821    RemoteVideoTracksChanged { participant_id: PeerId },
 7822}
 7823
 7824fn leader_border_for_pane(
 7825    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7826    pane: &Entity<Pane>,
 7827    _: &Window,
 7828    cx: &App,
 7829) -> Option<Div> {
 7830    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7831        if state.pane() == pane {
 7832            Some((*leader_id, state))
 7833        } else {
 7834            None
 7835        }
 7836    })?;
 7837
 7838    let mut leader_color = match leader_id {
 7839        CollaboratorId::PeerId(leader_peer_id) => {
 7840            let leader = GlobalAnyActiveCall::try_global(cx)?
 7841                .0
 7842                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7843
 7844            cx.theme()
 7845                .players()
 7846                .color_for_participant(leader.participant_index.0)
 7847                .cursor
 7848        }
 7849        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7850    };
 7851    leader_color.fade_out(0.3);
 7852    Some(
 7853        div()
 7854            .absolute()
 7855            .size_full()
 7856            .left_0()
 7857            .top_0()
 7858            .border_2()
 7859            .border_color(leader_color),
 7860    )
 7861}
 7862
 7863fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7864    ZED_WINDOW_POSITION
 7865        .zip(*ZED_WINDOW_SIZE)
 7866        .map(|(position, size)| Bounds {
 7867            origin: position,
 7868            size,
 7869        })
 7870}
 7871
 7872fn open_items(
 7873    serialized_workspace: Option<SerializedWorkspace>,
 7874    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7875    window: &mut Window,
 7876    cx: &mut Context<Workspace>,
 7877) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7878    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7879        Workspace::load_workspace(
 7880            serialized_workspace,
 7881            project_paths_to_open
 7882                .iter()
 7883                .map(|(_, project_path)| project_path)
 7884                .cloned()
 7885                .collect(),
 7886            window,
 7887            cx,
 7888        )
 7889    });
 7890
 7891    cx.spawn_in(window, async move |workspace, cx| {
 7892        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7893
 7894        if let Some(restored_items) = restored_items {
 7895            let restored_items = restored_items.await?;
 7896
 7897            let restored_project_paths = restored_items
 7898                .iter()
 7899                .filter_map(|item| {
 7900                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7901                        .ok()
 7902                        .flatten()
 7903                })
 7904                .collect::<HashSet<_>>();
 7905
 7906            for restored_item in restored_items {
 7907                opened_items.push(restored_item.map(Ok));
 7908            }
 7909
 7910            project_paths_to_open
 7911                .iter_mut()
 7912                .for_each(|(_, project_path)| {
 7913                    if let Some(project_path_to_open) = project_path
 7914                        && restored_project_paths.contains(project_path_to_open)
 7915                    {
 7916                        *project_path = None;
 7917                    }
 7918                });
 7919        } else {
 7920            for _ in 0..project_paths_to_open.len() {
 7921                opened_items.push(None);
 7922            }
 7923        }
 7924        assert!(opened_items.len() == project_paths_to_open.len());
 7925
 7926        let tasks =
 7927            project_paths_to_open
 7928                .into_iter()
 7929                .enumerate()
 7930                .map(|(ix, (abs_path, project_path))| {
 7931                    let workspace = workspace.clone();
 7932                    cx.spawn(async move |cx| {
 7933                        let file_project_path = project_path?;
 7934                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7935                            workspace.project().update(cx, |project, cx| {
 7936                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7937                            })
 7938                        });
 7939
 7940                        // We only want to open file paths here. If one of the items
 7941                        // here is a directory, it was already opened further above
 7942                        // with a `find_or_create_worktree`.
 7943                        if let Ok(task) = abs_path_task
 7944                            && task.await.is_none_or(|p| p.is_file())
 7945                        {
 7946                            return Some((
 7947                                ix,
 7948                                workspace
 7949                                    .update_in(cx, |workspace, window, cx| {
 7950                                        workspace.open_path(
 7951                                            file_project_path,
 7952                                            None,
 7953                                            true,
 7954                                            window,
 7955                                            cx,
 7956                                        )
 7957                                    })
 7958                                    .log_err()?
 7959                                    .await,
 7960                            ));
 7961                        }
 7962                        None
 7963                    })
 7964                });
 7965
 7966        let tasks = tasks.collect::<Vec<_>>();
 7967
 7968        let tasks = futures::future::join_all(tasks);
 7969        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7970            opened_items[ix] = Some(path_open_result);
 7971        }
 7972
 7973        Ok(opened_items)
 7974    })
 7975}
 7976
 7977#[derive(Clone)]
 7978enum ActivateInDirectionTarget {
 7979    Pane(Entity<Pane>),
 7980    Dock(Entity<Dock>),
 7981    Sidebar(FocusHandle),
 7982}
 7983
 7984fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7985    window
 7986        .update(cx, |multi_workspace, _, cx| {
 7987            let workspace = multi_workspace.workspace().clone();
 7988            workspace.update(cx, |workspace, cx| {
 7989                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7990                    struct DatabaseFailedNotification;
 7991
 7992                    workspace.show_notification(
 7993                        NotificationId::unique::<DatabaseFailedNotification>(),
 7994                        cx,
 7995                        |cx| {
 7996                            cx.new(|cx| {
 7997                                MessageNotification::new("Failed to load the database file.", cx)
 7998                                    .primary_message("File an Issue")
 7999                                    .primary_icon(IconName::Plus)
 8000                                    .primary_on_click(|window, cx| {
 8001                                        window.dispatch_action(Box::new(FileBugReport), cx)
 8002                                    })
 8003                            })
 8004                        },
 8005                    );
 8006                }
 8007            });
 8008        })
 8009        .log_err();
 8010}
 8011
 8012fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 8013    if val == 0 {
 8014        ThemeSettings::get_global(cx).ui_font_size(cx)
 8015    } else {
 8016        px(val as f32)
 8017    }
 8018}
 8019
 8020fn adjust_active_dock_size_by_px(
 8021    px: Pixels,
 8022    workspace: &mut Workspace,
 8023    window: &mut Window,
 8024    cx: &mut Context<Workspace>,
 8025) {
 8026    let Some(active_dock) = workspace
 8027        .all_docks()
 8028        .into_iter()
 8029        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 8030    else {
 8031        return;
 8032    };
 8033    let dock = active_dock.read(cx);
 8034    let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
 8035        return;
 8036    };
 8037    workspace.resize_dock(dock.position(), panel_size + px, window, cx);
 8038}
 8039
 8040fn adjust_open_docks_size_by_px(
 8041    px: Pixels,
 8042    workspace: &mut Workspace,
 8043    window: &mut Window,
 8044    cx: &mut Context<Workspace>,
 8045) {
 8046    let docks = workspace
 8047        .all_docks()
 8048        .into_iter()
 8049        .filter_map(|dock_entity| {
 8050            let dock = dock_entity.read(cx);
 8051            if dock.is_open() {
 8052                let dock_pos = dock.position();
 8053                let panel_size = workspace.dock_size(&dock, window, cx)?;
 8054                Some((dock_pos, panel_size + px))
 8055            } else {
 8056                None
 8057            }
 8058        })
 8059        .collect::<Vec<_>>();
 8060
 8061    for (position, new_size) in docks {
 8062        workspace.resize_dock(position, new_size, window, cx);
 8063    }
 8064}
 8065
 8066impl Focusable for Workspace {
 8067    fn focus_handle(&self, cx: &App) -> FocusHandle {
 8068        self.active_pane.focus_handle(cx)
 8069    }
 8070}
 8071
 8072#[derive(Clone)]
 8073struct DraggedDock(DockPosition);
 8074
 8075impl Render for DraggedDock {
 8076    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 8077        gpui::Empty
 8078    }
 8079}
 8080
 8081impl Render for Workspace {
 8082    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 8083        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 8084        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 8085            log::info!("Rendered first frame");
 8086        }
 8087
 8088        let centered_layout = self.centered_layout
 8089            && self.center.panes().len() == 1
 8090            && self.active_item(cx).is_some();
 8091        let render_padding = |size| {
 8092            (size > 0.0).then(|| {
 8093                div()
 8094                    .h_full()
 8095                    .w(relative(size))
 8096                    .bg(cx.theme().colors().editor_background)
 8097                    .border_color(cx.theme().colors().pane_group_border)
 8098            })
 8099        };
 8100        let paddings = if centered_layout {
 8101            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 8102            (
 8103                render_padding(Self::adjust_padding(
 8104                    settings.left_padding.map(|padding| padding.0),
 8105                )),
 8106                render_padding(Self::adjust_padding(
 8107                    settings.right_padding.map(|padding| padding.0),
 8108                )),
 8109            )
 8110        } else {
 8111            (None, None)
 8112        };
 8113        let ui_font = theme_settings::setup_ui_font(window, cx);
 8114
 8115        let theme = cx.theme().clone();
 8116        let colors = theme.colors();
 8117        let notification_entities = self
 8118            .notifications
 8119            .iter()
 8120            .map(|(_, notification)| notification.entity_id())
 8121            .collect::<Vec<_>>();
 8122        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 8123
 8124        div()
 8125            .relative()
 8126            .size_full()
 8127            .flex()
 8128            .flex_col()
 8129            .font(ui_font)
 8130            .gap_0()
 8131                .justify_start()
 8132                .items_start()
 8133                .text_color(colors.text)
 8134                .overflow_hidden()
 8135                .children(self.titlebar_item.clone())
 8136                .on_modifiers_changed(move |_, _, cx| {
 8137                    for &id in &notification_entities {
 8138                        cx.notify(id);
 8139                    }
 8140                })
 8141                .child(
 8142                    div()
 8143                        .size_full()
 8144                        .relative()
 8145                        .flex_1()
 8146                        .flex()
 8147                        .flex_col()
 8148                        .child(
 8149                            div()
 8150                                .id("workspace")
 8151                                .bg(colors.background)
 8152                                .relative()
 8153                                .flex_1()
 8154                                .w_full()
 8155                                .flex()
 8156                                .flex_col()
 8157                                .overflow_hidden()
 8158                                .border_t_1()
 8159                                .border_b_1()
 8160                                .border_color(colors.border)
 8161                                .child({
 8162                                    let this = cx.entity();
 8163                                    canvas(
 8164                                        move |bounds, window, cx| {
 8165                                            this.update(cx, |this, cx| {
 8166                                                let bounds_changed = this.bounds != bounds;
 8167                                                this.bounds = bounds;
 8168
 8169                                                if bounds_changed {
 8170                                                    this.left_dock.update(cx, |dock, cx| {
 8171                                                        dock.clamp_panel_size(
 8172                                                            bounds.size.width,
 8173                                                            window,
 8174                                                            cx,
 8175                                                        )
 8176                                                    });
 8177
 8178                                                    this.right_dock.update(cx, |dock, cx| {
 8179                                                        dock.clamp_panel_size(
 8180                                                            bounds.size.width,
 8181                                                            window,
 8182                                                            cx,
 8183                                                        )
 8184                                                    });
 8185
 8186                                                    this.bottom_dock.update(cx, |dock, cx| {
 8187                                                        dock.clamp_panel_size(
 8188                                                            bounds.size.height,
 8189                                                            window,
 8190                                                            cx,
 8191                                                        )
 8192                                                    });
 8193                                                }
 8194                                            })
 8195                                        },
 8196                                        |_, _, _, _| {},
 8197                                    )
 8198                                    .absolute()
 8199                                    .size_full()
 8200                                })
 8201                                .when(self.zoomed.is_none(), |this| {
 8202                                    this.on_drag_move(cx.listener(
 8203                                        move |workspace,
 8204                                              e: &DragMoveEvent<DraggedDock>,
 8205                                              window,
 8206                                              cx| {
 8207                                            if workspace.previous_dock_drag_coordinates
 8208                                                != Some(e.event.position)
 8209                                            {
 8210                                                workspace.previous_dock_drag_coordinates =
 8211                                                    Some(e.event.position);
 8212
 8213                                                match e.drag(cx).0 {
 8214                                                    DockPosition::Left => {
 8215                                                        workspace.resize_left_dock(
 8216                                                            e.event.position.x
 8217                                                                - workspace.bounds.left(),
 8218                                                            window,
 8219                                                            cx,
 8220                                                        );
 8221                                                    }
 8222                                                    DockPosition::Right => {
 8223                                                        workspace.resize_right_dock(
 8224                                                            workspace.bounds.right()
 8225                                                                - e.event.position.x,
 8226                                                            window,
 8227                                                            cx,
 8228                                                        );
 8229                                                    }
 8230                                                    DockPosition::Bottom => {
 8231                                                        workspace.resize_bottom_dock(
 8232                                                            workspace.bounds.bottom()
 8233                                                                - e.event.position.y,
 8234                                                            window,
 8235                                                            cx,
 8236                                                        );
 8237                                                    }
 8238                                                };
 8239                                                workspace.serialize_workspace(window, cx);
 8240                                            }
 8241                                        },
 8242                                    ))
 8243
 8244                                })
 8245                                .child({
 8246                                    match bottom_dock_layout {
 8247                                        BottomDockLayout::Full => div()
 8248                                            .flex()
 8249                                            .flex_col()
 8250                                            .h_full()
 8251                                            .child(
 8252                                                div()
 8253                                                    .flex()
 8254                                                    .flex_row()
 8255                                                    .flex_1()
 8256                                                    .overflow_hidden()
 8257                                                    .children(self.render_dock(
 8258                                                        DockPosition::Left,
 8259                                                        &self.left_dock,
 8260                                                        window,
 8261                                                        cx,
 8262                                                    ))
 8263
 8264                                                    .child(
 8265                                                        div()
 8266                                                            .flex()
 8267                                                            .flex_col()
 8268                                                            .flex_1()
 8269                                                            .overflow_hidden()
 8270                                                            .child(
 8271                                                                h_flex()
 8272                                                                    .flex_1()
 8273                                                                    .when_some(
 8274                                                                        paddings.0,
 8275                                                                        |this, p| {
 8276                                                                            this.child(
 8277                                                                                p.border_r_1(),
 8278                                                                            )
 8279                                                                        },
 8280                                                                    )
 8281                                                                    .child(self.center.render(
 8282                                                                        self.zoomed.as_ref(),
 8283                                                                        &PaneRenderContext {
 8284                                                                            follower_states:
 8285                                                                                &self.follower_states,
 8286                                                                            active_call: self.active_call(),
 8287                                                                            active_pane: &self.active_pane,
 8288                                                                            app_state: &self.app_state,
 8289                                                                            project: &self.project,
 8290                                                                            workspace: &self.weak_self,
 8291                                                                        },
 8292                                                                        window,
 8293                                                                        cx,
 8294                                                                    ))
 8295                                                                    .when_some(
 8296                                                                        paddings.1,
 8297                                                                        |this, p| {
 8298                                                                            this.child(
 8299                                                                                p.border_l_1(),
 8300                                                                            )
 8301                                                                        },
 8302                                                                    ),
 8303                                                            ),
 8304                                                    )
 8305
 8306                                                    .children(self.render_dock(
 8307                                                        DockPosition::Right,
 8308                                                        &self.right_dock,
 8309                                                        window,
 8310                                                        cx,
 8311                                                    )),
 8312                                            )
 8313                                            .child(div().w_full().children(self.render_dock(
 8314                                                DockPosition::Bottom,
 8315                                                &self.bottom_dock,
 8316                                                window,
 8317                                                cx
 8318                                            ))),
 8319
 8320                                        BottomDockLayout::LeftAligned => div()
 8321                                            .flex()
 8322                                            .flex_row()
 8323                                            .h_full()
 8324                                            .child(
 8325                                                div()
 8326                                                    .flex()
 8327                                                    .flex_col()
 8328                                                    .flex_1()
 8329                                                    .h_full()
 8330                                                    .child(
 8331                                                        div()
 8332                                                            .flex()
 8333                                                            .flex_row()
 8334                                                            .flex_1()
 8335                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 8336
 8337                                                            .child(
 8338                                                                div()
 8339                                                                    .flex()
 8340                                                                    .flex_col()
 8341                                                                    .flex_1()
 8342                                                                    .overflow_hidden()
 8343                                                                    .child(
 8344                                                                        h_flex()
 8345                                                                            .flex_1()
 8346                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8347                                                                            .child(self.center.render(
 8348                                                                                self.zoomed.as_ref(),
 8349                                                                                &PaneRenderContext {
 8350                                                                                    follower_states:
 8351                                                                                        &self.follower_states,
 8352                                                                                    active_call: self.active_call(),
 8353                                                                                    active_pane: &self.active_pane,
 8354                                                                                    app_state: &self.app_state,
 8355                                                                                    project: &self.project,
 8356                                                                                    workspace: &self.weak_self,
 8357                                                                                },
 8358                                                                                window,
 8359                                                                                cx,
 8360                                                                            ))
 8361                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8362                                                                    )
 8363                                                            )
 8364
 8365                                                    )
 8366                                                    .child(
 8367                                                        div()
 8368                                                            .w_full()
 8369                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8370                                                    ),
 8371                                            )
 8372                                            .children(self.render_dock(
 8373                                                DockPosition::Right,
 8374                                                &self.right_dock,
 8375                                                window,
 8376                                                cx,
 8377                                            )),
 8378                                        BottomDockLayout::RightAligned => div()
 8379                                            .flex()
 8380                                            .flex_row()
 8381                                            .h_full()
 8382                                            .children(self.render_dock(
 8383                                                DockPosition::Left,
 8384                                                &self.left_dock,
 8385                                                window,
 8386                                                cx,
 8387                                            ))
 8388
 8389                                            .child(
 8390                                                div()
 8391                                                    .flex()
 8392                                                    .flex_col()
 8393                                                    .flex_1()
 8394                                                    .h_full()
 8395                                                    .child(
 8396                                                        div()
 8397                                                            .flex()
 8398                                                            .flex_row()
 8399                                                            .flex_1()
 8400                                                            .child(
 8401                                                                div()
 8402                                                                    .flex()
 8403                                                                    .flex_col()
 8404                                                                    .flex_1()
 8405                                                                    .overflow_hidden()
 8406                                                                    .child(
 8407                                                                        h_flex()
 8408                                                                            .flex_1()
 8409                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8410                                                                            .child(self.center.render(
 8411                                                                                self.zoomed.as_ref(),
 8412                                                                                &PaneRenderContext {
 8413                                                                                    follower_states:
 8414                                                                                        &self.follower_states,
 8415                                                                                    active_call: self.active_call(),
 8416                                                                                    active_pane: &self.active_pane,
 8417                                                                                    app_state: &self.app_state,
 8418                                                                                    project: &self.project,
 8419                                                                                    workspace: &self.weak_self,
 8420                                                                                },
 8421                                                                                window,
 8422                                                                                cx,
 8423                                                                            ))
 8424                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8425                                                                    )
 8426                                                            )
 8427
 8428                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 8429                                                    )
 8430                                                    .child(
 8431                                                        div()
 8432                                                            .w_full()
 8433                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8434                                                    ),
 8435                                            ),
 8436                                        BottomDockLayout::Contained => div()
 8437                                            .flex()
 8438                                            .flex_row()
 8439                                            .h_full()
 8440                                            .children(self.render_dock(
 8441                                                DockPosition::Left,
 8442                                                &self.left_dock,
 8443                                                window,
 8444                                                cx,
 8445                                            ))
 8446
 8447                                            .child(
 8448                                                div()
 8449                                                    .flex()
 8450                                                    .flex_col()
 8451                                                    .flex_1()
 8452                                                    .overflow_hidden()
 8453                                                    .child(
 8454                                                        h_flex()
 8455                                                            .flex_1()
 8456                                                            .when_some(paddings.0, |this, p| {
 8457                                                                this.child(p.border_r_1())
 8458                                                            })
 8459                                                            .child(self.center.render(
 8460                                                                self.zoomed.as_ref(),
 8461                                                                &PaneRenderContext {
 8462                                                                    follower_states:
 8463                                                                        &self.follower_states,
 8464                                                                    active_call: self.active_call(),
 8465                                                                    active_pane: &self.active_pane,
 8466                                                                    app_state: &self.app_state,
 8467                                                                    project: &self.project,
 8468                                                                    workspace: &self.weak_self,
 8469                                                                },
 8470                                                                window,
 8471                                                                cx,
 8472                                                            ))
 8473                                                            .when_some(paddings.1, |this, p| {
 8474                                                                this.child(p.border_l_1())
 8475                                                            }),
 8476                                                    )
 8477                                                    .children(self.render_dock(
 8478                                                        DockPosition::Bottom,
 8479                                                        &self.bottom_dock,
 8480                                                        window,
 8481                                                        cx,
 8482                                                    )),
 8483                                            )
 8484
 8485                                            .children(self.render_dock(
 8486                                                DockPosition::Right,
 8487                                                &self.right_dock,
 8488                                                window,
 8489                                                cx,
 8490                                            )),
 8491                                    }
 8492                                })
 8493                                .children(self.zoomed.as_ref().and_then(|view| {
 8494                                    let zoomed_view = view.upgrade()?;
 8495                                    let div = div()
 8496                                        .occlude()
 8497                                        .absolute()
 8498                                        .overflow_hidden()
 8499                                        .border_color(colors.border)
 8500                                        .bg(colors.background)
 8501                                        .child(zoomed_view)
 8502                                        .inset_0()
 8503                                        .shadow_lg();
 8504
 8505                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8506                                       return Some(div);
 8507                                    }
 8508
 8509                                    Some(match self.zoomed_position {
 8510                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8511                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8512                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8513                                        None => {
 8514                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8515                                        }
 8516                                    })
 8517                                }))
 8518                                .children(self.render_notifications(window, cx)),
 8519                        )
 8520                        .when(self.status_bar_visible(cx), |parent| {
 8521                            parent.child(self.status_bar.clone())
 8522                        })
 8523                        .child(self.toast_layer.clone()),
 8524                )
 8525    }
 8526}
 8527
 8528impl WorkspaceStore {
 8529    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8530        Self {
 8531            workspaces: Default::default(),
 8532            _subscriptions: vec![
 8533                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8534                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8535            ],
 8536            client,
 8537        }
 8538    }
 8539
 8540    pub fn update_followers(
 8541        &self,
 8542        project_id: Option<u64>,
 8543        update: proto::update_followers::Variant,
 8544        cx: &App,
 8545    ) -> Option<()> {
 8546        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8547        let room_id = active_call.0.room_id(cx)?;
 8548        self.client
 8549            .send(proto::UpdateFollowers {
 8550                room_id,
 8551                project_id,
 8552                variant: Some(update),
 8553            })
 8554            .log_err()
 8555    }
 8556
 8557    pub async fn handle_follow(
 8558        this: Entity<Self>,
 8559        envelope: TypedEnvelope<proto::Follow>,
 8560        mut cx: AsyncApp,
 8561    ) -> Result<proto::FollowResponse> {
 8562        this.update(&mut cx, |this, cx| {
 8563            let follower = Follower {
 8564                project_id: envelope.payload.project_id,
 8565                peer_id: envelope.original_sender_id()?,
 8566            };
 8567
 8568            let mut response = proto::FollowResponse::default();
 8569
 8570            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8571                let Some(workspace) = weak_workspace.upgrade() else {
 8572                    return false;
 8573                };
 8574                window_handle
 8575                    .update(cx, |_, window, cx| {
 8576                        workspace.update(cx, |workspace, cx| {
 8577                            let handler_response =
 8578                                workspace.handle_follow(follower.project_id, window, cx);
 8579                            if let Some(active_view) = handler_response.active_view
 8580                                && workspace.project.read(cx).remote_id() == follower.project_id
 8581                            {
 8582                                response.active_view = Some(active_view)
 8583                            }
 8584                        });
 8585                    })
 8586                    .is_ok()
 8587            });
 8588
 8589            Ok(response)
 8590        })
 8591    }
 8592
 8593    async fn handle_update_followers(
 8594        this: Entity<Self>,
 8595        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8596        mut cx: AsyncApp,
 8597    ) -> Result<()> {
 8598        let leader_id = envelope.original_sender_id()?;
 8599        let update = envelope.payload;
 8600
 8601        this.update(&mut cx, |this, cx| {
 8602            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8603                let Some(workspace) = weak_workspace.upgrade() else {
 8604                    return false;
 8605                };
 8606                window_handle
 8607                    .update(cx, |_, window, cx| {
 8608                        workspace.update(cx, |workspace, cx| {
 8609                            let project_id = workspace.project.read(cx).remote_id();
 8610                            if update.project_id != project_id && update.project_id.is_some() {
 8611                                return;
 8612                            }
 8613                            workspace.handle_update_followers(
 8614                                leader_id,
 8615                                update.clone(),
 8616                                window,
 8617                                cx,
 8618                            );
 8619                        });
 8620                    })
 8621                    .is_ok()
 8622            });
 8623            Ok(())
 8624        })
 8625    }
 8626
 8627    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8628        self.workspaces.iter().map(|(_, weak)| weak)
 8629    }
 8630
 8631    pub fn workspaces_with_windows(
 8632        &self,
 8633    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8634        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8635    }
 8636}
 8637
 8638impl ViewId {
 8639    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8640        Ok(Self {
 8641            creator: message
 8642                .creator
 8643                .map(CollaboratorId::PeerId)
 8644                .context("creator is missing")?,
 8645            id: message.id,
 8646        })
 8647    }
 8648
 8649    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8650        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8651            Some(proto::ViewId {
 8652                creator: Some(peer_id),
 8653                id: self.id,
 8654            })
 8655        } else {
 8656            None
 8657        }
 8658    }
 8659}
 8660
 8661impl FollowerState {
 8662    fn pane(&self) -> &Entity<Pane> {
 8663        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8664    }
 8665}
 8666
 8667pub trait WorkspaceHandle {
 8668    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8669}
 8670
 8671impl WorkspaceHandle for Entity<Workspace> {
 8672    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8673        self.read(cx)
 8674            .worktrees(cx)
 8675            .flat_map(|worktree| {
 8676                let worktree_id = worktree.read(cx).id();
 8677                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8678                    worktree_id,
 8679                    path: f.path.clone(),
 8680                })
 8681            })
 8682            .collect::<Vec<_>>()
 8683    }
 8684}
 8685
 8686pub async fn last_opened_workspace_location(
 8687    db: &WorkspaceDb,
 8688    fs: &dyn fs::Fs,
 8689) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8690    db.last_workspace(fs)
 8691        .await
 8692        .log_err()
 8693        .flatten()
 8694        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8695}
 8696
 8697pub async fn last_session_workspace_locations(
 8698    db: &WorkspaceDb,
 8699    last_session_id: &str,
 8700    last_session_window_stack: Option<Vec<WindowId>>,
 8701    fs: &dyn fs::Fs,
 8702) -> Option<Vec<SessionWorkspace>> {
 8703    db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8704        .await
 8705        .log_err()
 8706}
 8707
 8708pub async fn restore_multiworkspace(
 8709    multi_workspace: SerializedMultiWorkspace,
 8710    app_state: Arc<AppState>,
 8711    cx: &mut AsyncApp,
 8712) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8713    let SerializedMultiWorkspace {
 8714        active_workspace,
 8715        state,
 8716    } = multi_workspace;
 8717
 8718    let workspace_result = if active_workspace.paths.is_empty() {
 8719        cx.update(|cx| {
 8720            open_workspace_by_id(active_workspace.workspace_id, app_state.clone(), None, cx)
 8721        })
 8722        .await
 8723    } else {
 8724        cx.update(|cx| {
 8725            Workspace::new_local(
 8726                active_workspace.paths.paths().to_vec(),
 8727                app_state.clone(),
 8728                None,
 8729                None,
 8730                None,
 8731                OpenMode::Activate,
 8732                cx,
 8733            )
 8734        })
 8735        .await
 8736        .map(|result| result.window)
 8737    };
 8738
 8739    let window_handle = match workspace_result {
 8740        Ok(handle) => handle,
 8741        Err(err) => {
 8742            log::error!("Failed to restore active workspace: {err:#}");
 8743
 8744            let mut fallback_handle = None;
 8745            for key in &state.project_groups {
 8746                let key: ProjectGroupKey = key.clone().into();
 8747                let paths = key.path_list().paths().to_vec();
 8748                match cx
 8749                    .update(|cx| {
 8750                        Workspace::new_local(
 8751                            paths,
 8752                            app_state.clone(),
 8753                            None,
 8754                            None,
 8755                            None,
 8756                            OpenMode::Activate,
 8757                            cx,
 8758                        )
 8759                    })
 8760                    .await
 8761                {
 8762                    Ok(OpenResult { window, .. }) => {
 8763                        fallback_handle = Some(window);
 8764                        break;
 8765                    }
 8766                    Err(fallback_err) => {
 8767                        log::error!("Fallback project group also failed: {fallback_err:#}");
 8768                    }
 8769                }
 8770            }
 8771
 8772            fallback_handle.ok_or(err)?
 8773        }
 8774    };
 8775
 8776    apply_restored_multiworkspace_state(window_handle, &state, app_state.fs.clone(), cx).await;
 8777
 8778    window_handle
 8779        .update(cx, |_, window, _cx| {
 8780            window.activate_window();
 8781        })
 8782        .ok();
 8783
 8784    Ok(window_handle)
 8785}
 8786
 8787pub async fn apply_restored_multiworkspace_state(
 8788    window_handle: WindowHandle<MultiWorkspace>,
 8789    state: &MultiWorkspaceState,
 8790    fs: Arc<dyn fs::Fs>,
 8791    cx: &mut AsyncApp,
 8792) {
 8793    let MultiWorkspaceState {
 8794        sidebar_open,
 8795        project_groups,
 8796        sidebar_state,
 8797        ..
 8798    } = state;
 8799
 8800    if !project_groups.is_empty() {
 8801        // Resolve linked worktree paths to their main repo paths so
 8802        // stale keys from previous sessions get normalized and deduped.
 8803        let mut resolved_groups: Vec<SerializedProjectGroupState> = Vec::new();
 8804        for serialized in project_groups.iter().cloned() {
 8805            let SerializedProjectGroupState {
 8806                key,
 8807                expanded,
 8808                visible_thread_count,
 8809            } = serialized.into_restored_state();
 8810            if key.path_list().paths().is_empty() {
 8811                continue;
 8812            }
 8813            let mut resolved_paths = Vec::new();
 8814            for path in key.path_list().paths() {
 8815                if key.host().is_none()
 8816                    && let Some(common_dir) =
 8817                        project::discover_root_repo_common_dir(path, fs.as_ref()).await
 8818                {
 8819                    let main_path = common_dir.parent().unwrap_or(&common_dir);
 8820                    resolved_paths.push(main_path.to_path_buf());
 8821                } else {
 8822                    resolved_paths.push(path.to_path_buf());
 8823                }
 8824            }
 8825            let resolved = ProjectGroupKey::new(key.host(), PathList::new(&resolved_paths));
 8826            if !resolved_groups.iter().any(|g| g.key == resolved) {
 8827                resolved_groups.push(SerializedProjectGroupState {
 8828                    key: resolved,
 8829                    expanded,
 8830                    visible_thread_count,
 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.bounds.size.width = px(800.);
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, window, cx);
12758            workspace.toggle_dock(DockPosition::Right, window, cx);
12759        });
12760
12761        let (panel, resized_width, ratio_basis_width) =
12762            workspace.update_in(cx, |workspace, window, cx| {
12763                let item = cx.new(|cx| {
12764                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12765                });
12766                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12767
12768                let dock = workspace.right_dock().read(cx);
12769                let workspace_width = workspace.bounds.size.width;
12770                let initial_width = workspace
12771                    .dock_size(&dock, window, cx)
12772                    .expect("flexible dock should have an initial width");
12773
12774                assert_eq!(initial_width, workspace_width / 2.);
12775
12776                workspace.resize_right_dock(px(300.), window, cx);
12777
12778                let dock = workspace.right_dock().read(cx);
12779                let resized_width = workspace
12780                    .dock_size(&dock, window, cx)
12781                    .expect("flexible dock should keep its resized width");
12782
12783                assert_eq!(resized_width, px(300.));
12784
12785                let panel = workspace
12786                    .right_dock()
12787                    .read(cx)
12788                    .visible_panel()
12789                    .expect("flexible dock should have a visible panel")
12790                    .panel_id();
12791
12792                (panel, resized_width, workspace_width)
12793            });
12794
12795        workspace.update_in(cx, |workspace, window, cx| {
12796            workspace.toggle_dock(DockPosition::Right, window, cx);
12797            workspace.toggle_dock(DockPosition::Right, window, cx);
12798
12799            let dock = workspace.right_dock().read(cx);
12800            let reopened_width = workspace
12801                .dock_size(&dock, window, cx)
12802                .expect("flexible dock should restore when reopened");
12803
12804            assert_eq!(reopened_width, resized_width);
12805
12806            let right_dock = workspace.right_dock().read(cx);
12807            let flexible_panel = right_dock
12808                .visible_panel()
12809                .expect("flexible dock should still have a visible panel");
12810            assert_eq!(flexible_panel.panel_id(), panel);
12811            assert_eq!(
12812                right_dock
12813                    .stored_panel_size_state(flexible_panel.as_ref())
12814                    .and_then(|size_state| size_state.flex),
12815                Some(
12816                    resized_width.to_f64() as f32
12817                        / (workspace.bounds.size.width - resized_width).to_f64() as f32
12818                )
12819            );
12820        });
12821
12822        workspace.update_in(cx, |workspace, window, cx| {
12823            workspace.split_pane(
12824                workspace.active_pane().clone(),
12825                SplitDirection::Right,
12826                window,
12827                cx,
12828            );
12829
12830            let dock = workspace.right_dock().read(cx);
12831            let split_width = workspace
12832                .dock_size(&dock, window, cx)
12833                .expect("flexible dock should keep its user-resized proportion");
12834
12835            assert_eq!(split_width, px(300.));
12836
12837            workspace.bounds.size.width = px(1600.);
12838
12839            let dock = workspace.right_dock().read(cx);
12840            let resized_window_width = workspace
12841                .dock_size(&dock, window, cx)
12842                .expect("flexible dock should preserve proportional size on window resize");
12843
12844            assert_eq!(
12845                resized_window_width,
12846                workspace.bounds.size.width
12847                    * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12848            );
12849        });
12850    }
12851
12852    #[gpui::test]
12853    async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12854        init_test(cx);
12855        let fs = FakeFs::new(cx.executor());
12856
12857        // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12858        {
12859            let project = Project::test(fs.clone(), [], cx).await;
12860            let (multi_workspace, cx) =
12861                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12862            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12863
12864            workspace.update(cx, |workspace, _cx| {
12865                workspace.set_random_database_id();
12866                workspace.bounds.size.width = px(800.);
12867            });
12868
12869            let panel = workspace.update_in(cx, |workspace, window, cx| {
12870                let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12871                workspace.add_panel(panel.clone(), window, cx);
12872                workspace.toggle_dock(DockPosition::Left, window, cx);
12873                panel
12874            });
12875
12876            workspace.update_in(cx, |workspace, window, cx| {
12877                workspace.resize_left_dock(px(350.), window, cx);
12878            });
12879
12880            cx.run_until_parked();
12881
12882            let persisted = workspace.read_with(cx, |workspace, cx| {
12883                workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12884            });
12885            assert_eq!(
12886                persisted.and_then(|s| s.size),
12887                Some(px(350.)),
12888                "fixed-width panel size should be persisted to KVP"
12889            );
12890
12891            // Remove the panel and re-add a fresh instance with the same key.
12892            // The new instance should have its size state restored from KVP.
12893            workspace.update_in(cx, |workspace, window, cx| {
12894                workspace.remove_panel(&panel, window, cx);
12895            });
12896
12897            workspace.update_in(cx, |workspace, window, cx| {
12898                let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12899                workspace.add_panel(new_panel, window, cx);
12900
12901                let left_dock = workspace.left_dock().read(cx);
12902                let size_state = left_dock
12903                    .panel::<TestPanel>()
12904                    .and_then(|p| left_dock.stored_panel_size_state(&p));
12905                assert_eq!(
12906                    size_state.and_then(|s| s.size),
12907                    Some(px(350.)),
12908                    "re-added fixed-width panel should restore persisted size from KVP"
12909                );
12910            });
12911        }
12912
12913        // Flexible panel: both pixel size and ratio are persisted and restored.
12914        {
12915            let project = Project::test(fs.clone(), [], cx).await;
12916            let (multi_workspace, cx) =
12917                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12918            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12919
12920            workspace.update(cx, |workspace, _cx| {
12921                workspace.set_random_database_id();
12922                workspace.bounds.size.width = px(800.);
12923            });
12924
12925            let panel = workspace.update_in(cx, |workspace, window, cx| {
12926                let item = cx.new(|cx| {
12927                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12928                });
12929                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12930
12931                let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12932                workspace.add_panel(panel.clone(), window, cx);
12933                workspace.toggle_dock(DockPosition::Right, window, cx);
12934                panel
12935            });
12936
12937            workspace.update_in(cx, |workspace, window, cx| {
12938                workspace.resize_right_dock(px(300.), window, cx);
12939            });
12940
12941            cx.run_until_parked();
12942
12943            let persisted = workspace
12944                .read_with(cx, |workspace, cx| {
12945                    workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12946                })
12947                .expect("flexible panel state should be persisted to KVP");
12948            assert_eq!(
12949                persisted.size, None,
12950                "flexible panel should not persist a redundant pixel size"
12951            );
12952            let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12953
12954            // Remove the panel and re-add: both size and ratio should be restored.
12955            workspace.update_in(cx, |workspace, window, cx| {
12956                workspace.remove_panel(&panel, window, cx);
12957            });
12958
12959            workspace.update_in(cx, |workspace, window, cx| {
12960                let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12961                workspace.add_panel(new_panel, window, cx);
12962
12963                let right_dock = workspace.right_dock().read(cx);
12964                let size_state = right_dock
12965                    .panel::<TestPanel>()
12966                    .and_then(|p| right_dock.stored_panel_size_state(&p))
12967                    .expect("re-added flexible panel should have restored size state from KVP");
12968                assert_eq!(
12969                    size_state.size, None,
12970                    "re-added flexible panel should not have a persisted pixel size"
12971                );
12972                assert_eq!(
12973                    size_state.flex,
12974                    Some(original_ratio),
12975                    "re-added flexible panel should restore persisted flex"
12976                );
12977            });
12978        }
12979    }
12980
12981    #[gpui::test]
12982    async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12983        init_test(cx);
12984        let fs = FakeFs::new(cx.executor());
12985
12986        let project = Project::test(fs, [], cx).await;
12987        let (multi_workspace, cx) =
12988            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12989        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12990
12991        workspace.update(cx, |workspace, _cx| {
12992            workspace.bounds.size.width = px(900.);
12993        });
12994
12995        // Step 1: Add a tab to the center pane then open a flexible panel in the left
12996        // dock. With one full-width center pane the default ratio is 0.5, so the panel
12997        // and the center pane each take half the workspace width.
12998        workspace.update_in(cx, |workspace, window, cx| {
12999            let item = cx.new(|cx| {
13000                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
13001            });
13002            workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
13003
13004            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
13005            workspace.add_panel(panel, window, cx);
13006            workspace.toggle_dock(DockPosition::Left, window, cx);
13007
13008            let left_dock = workspace.left_dock().read(cx);
13009            let left_width = workspace
13010                .dock_size(&left_dock, window, cx)
13011                .expect("left dock should have an active panel");
13012
13013            assert_eq!(
13014                left_width,
13015                workspace.bounds.size.width / 2.,
13016                "flexible left panel should split evenly with the center pane"
13017            );
13018        });
13019
13020        // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
13021        // change horizontal width fractions, so the flexible panel stays at the same
13022        // width as each half of the split.
13023        workspace.update_in(cx, |workspace, window, cx| {
13024            workspace.split_pane(
13025                workspace.active_pane().clone(),
13026                SplitDirection::Down,
13027                window,
13028                cx,
13029            );
13030
13031            let left_dock = workspace.left_dock().read(cx);
13032            let left_width = workspace
13033                .dock_size(&left_dock, window, cx)
13034                .expect("left dock should still have an active panel after vertical split");
13035
13036            assert_eq!(
13037                left_width,
13038                workspace.bounds.size.width / 2.,
13039                "flexible left panel width should match each vertically-split pane"
13040            );
13041        });
13042
13043        // Step 3: Open a fixed-width panel in the right dock. The right dock's default
13044        // size reduces the available width, so the flexible left panel and the center
13045        // panes all shrink proportionally to accommodate it.
13046        workspace.update_in(cx, |workspace, window, cx| {
13047            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
13048            workspace.add_panel(panel, window, cx);
13049            workspace.toggle_dock(DockPosition::Right, window, cx);
13050
13051            let right_dock = workspace.right_dock().read(cx);
13052            let right_width = workspace
13053                .dock_size(&right_dock, window, cx)
13054                .expect("right dock should have an active panel");
13055
13056            let left_dock = workspace.left_dock().read(cx);
13057            let left_width = workspace
13058                .dock_size(&left_dock, window, cx)
13059                .expect("left dock should still have an active panel");
13060
13061            let available_width = workspace.bounds.size.width - right_width;
13062            assert_eq!(
13063                left_width,
13064                available_width / 2.,
13065                "flexible left panel should shrink proportionally as the right dock takes space"
13066            );
13067        });
13068
13069        // Step 4: Toggle the right dock's panel to flexible. Now both docks use
13070        // flex sizing and the workspace width is divided among left-flex, center
13071        // (implicit flex 1.0), and right-flex.
13072        workspace.update_in(cx, |workspace, window, cx| {
13073            let right_dock = workspace.right_dock().clone();
13074            let right_panel = right_dock
13075                .read(cx)
13076                .visible_panel()
13077                .expect("right dock should have a visible panel")
13078                .clone();
13079            workspace.toggle_dock_panel_flexible_size(
13080                &right_dock,
13081                right_panel.as_ref(),
13082                window,
13083                cx,
13084            );
13085
13086            let right_dock = right_dock.read(cx);
13087            let right_panel = right_dock
13088                .visible_panel()
13089                .expect("right dock should still have a visible panel");
13090            assert!(
13091                right_panel.has_flexible_size(window, cx),
13092                "right panel should now be flexible"
13093            );
13094
13095            let right_size_state = right_dock
13096                .stored_panel_size_state(right_panel.as_ref())
13097                .expect("right panel should have a stored size state after toggling");
13098            let right_flex = right_size_state
13099                .flex
13100                .expect("right panel should have a flex value after toggling");
13101
13102            let left_dock = workspace.left_dock().read(cx);
13103            let left_width = workspace
13104                .dock_size(&left_dock, window, cx)
13105                .expect("left dock should still have an active panel");
13106            let right_width = workspace
13107                .dock_size(&right_dock, window, cx)
13108                .expect("right dock should still have an active panel");
13109
13110            let left_flex = workspace
13111                .default_dock_flex(DockPosition::Left)
13112                .expect("left dock should have a default flex");
13113
13114            let total_flex = left_flex + 1.0 + right_flex;
13115            let expected_left = left_flex / total_flex * workspace.bounds.size.width;
13116            let expected_right = right_flex / total_flex * workspace.bounds.size.width;
13117            assert_eq!(
13118                left_width, expected_left,
13119                "flexible left panel should share workspace width via flex ratios"
13120            );
13121            assert_eq!(
13122                right_width, expected_right,
13123                "flexible right panel should share workspace width via flex ratios"
13124            );
13125        });
13126    }
13127
13128    struct TestModal(FocusHandle);
13129
13130    impl TestModal {
13131        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
13132            Self(cx.focus_handle())
13133        }
13134    }
13135
13136    impl EventEmitter<DismissEvent> for TestModal {}
13137
13138    impl Focusable for TestModal {
13139        fn focus_handle(&self, _cx: &App) -> FocusHandle {
13140            self.0.clone()
13141        }
13142    }
13143
13144    impl ModalView for TestModal {}
13145
13146    impl Render for TestModal {
13147        fn render(
13148            &mut self,
13149            _window: &mut Window,
13150            _cx: &mut Context<TestModal>,
13151        ) -> impl IntoElement {
13152            div().track_focus(&self.0)
13153        }
13154    }
13155
13156    #[gpui::test]
13157    async fn test_panels(cx: &mut gpui::TestAppContext) {
13158        init_test(cx);
13159        let fs = FakeFs::new(cx.executor());
13160
13161        let project = Project::test(fs, [], cx).await;
13162        let (multi_workspace, cx) =
13163            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13164        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13165
13166        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
13167            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
13168            workspace.add_panel(panel_1.clone(), window, cx);
13169            workspace.toggle_dock(DockPosition::Left, window, cx);
13170            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
13171            workspace.add_panel(panel_2.clone(), window, cx);
13172            workspace.toggle_dock(DockPosition::Right, window, cx);
13173
13174            let left_dock = workspace.left_dock();
13175            assert_eq!(
13176                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13177                panel_1.panel_id()
13178            );
13179            assert_eq!(
13180                workspace.dock_size(&left_dock.read(cx), window, cx),
13181                Some(px(300.))
13182            );
13183
13184            workspace.resize_left_dock(px(1337.), window, cx);
13185            assert_eq!(
13186                workspace
13187                    .right_dock()
13188                    .read(cx)
13189                    .visible_panel()
13190                    .unwrap()
13191                    .panel_id(),
13192                panel_2.panel_id(),
13193            );
13194
13195            (panel_1, panel_2)
13196        });
13197
13198        // Move panel_1 to the right
13199        panel_1.update_in(cx, |panel_1, window, cx| {
13200            panel_1.set_position(DockPosition::Right, window, cx)
13201        });
13202
13203        workspace.update_in(cx, |workspace, window, cx| {
13204            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
13205            // Since it was the only panel on the left, the left dock should now be closed.
13206            assert!(!workspace.left_dock().read(cx).is_open());
13207            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
13208            let right_dock = workspace.right_dock();
13209            assert_eq!(
13210                right_dock.read(cx).visible_panel().unwrap().panel_id(),
13211                panel_1.panel_id()
13212            );
13213            assert_eq!(
13214                right_dock
13215                    .read(cx)
13216                    .active_panel_size()
13217                    .unwrap()
13218                    .size
13219                    .unwrap(),
13220                px(1337.)
13221            );
13222
13223            // Now we move panel_2 to the left
13224            panel_2.set_position(DockPosition::Left, window, cx);
13225        });
13226
13227        workspace.update(cx, |workspace, cx| {
13228            // Since panel_2 was not visible on the right, we don't open the left dock.
13229            assert!(!workspace.left_dock().read(cx).is_open());
13230            // And the right dock is unaffected in its displaying of panel_1
13231            assert!(workspace.right_dock().read(cx).is_open());
13232            assert_eq!(
13233                workspace
13234                    .right_dock()
13235                    .read(cx)
13236                    .visible_panel()
13237                    .unwrap()
13238                    .panel_id(),
13239                panel_1.panel_id(),
13240            );
13241        });
13242
13243        // Move panel_1 back to the left
13244        panel_1.update_in(cx, |panel_1, window, cx| {
13245            panel_1.set_position(DockPosition::Left, window, cx)
13246        });
13247
13248        workspace.update_in(cx, |workspace, window, cx| {
13249            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
13250            let left_dock = workspace.left_dock();
13251            assert!(left_dock.read(cx).is_open());
13252            assert_eq!(
13253                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13254                panel_1.panel_id()
13255            );
13256            assert_eq!(
13257                workspace.dock_size(&left_dock.read(cx), window, cx),
13258                Some(px(1337.))
13259            );
13260            // And the right dock should be closed as it no longer has any panels.
13261            assert!(!workspace.right_dock().read(cx).is_open());
13262
13263            // Now we move panel_1 to the bottom
13264            panel_1.set_position(DockPosition::Bottom, window, cx);
13265        });
13266
13267        workspace.update_in(cx, |workspace, window, cx| {
13268            // Since panel_1 was visible on the left, we close the left dock.
13269            assert!(!workspace.left_dock().read(cx).is_open());
13270            // The bottom dock is sized based on the panel's default size,
13271            // since the panel orientation changed from vertical to horizontal.
13272            let bottom_dock = workspace.bottom_dock();
13273            assert_eq!(
13274                workspace.dock_size(&bottom_dock.read(cx), window, cx),
13275                Some(px(300.))
13276            );
13277            // Close bottom dock and move panel_1 back to the left.
13278            bottom_dock.update(cx, |bottom_dock, cx| {
13279                bottom_dock.set_open(false, window, cx)
13280            });
13281            panel_1.set_position(DockPosition::Left, window, cx);
13282        });
13283
13284        // Emit activated event on panel 1
13285        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
13286
13287        // Now the left dock is open and panel_1 is active and focused.
13288        workspace.update_in(cx, |workspace, window, cx| {
13289            let left_dock = workspace.left_dock();
13290            assert!(left_dock.read(cx).is_open());
13291            assert_eq!(
13292                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13293                panel_1.panel_id(),
13294            );
13295            assert!(panel_1.focus_handle(cx).is_focused(window));
13296        });
13297
13298        // Emit closed event on panel 2, which is not active
13299        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13300
13301        // Wo don't close the left dock, because panel_2 wasn't the active panel
13302        workspace.update(cx, |workspace, cx| {
13303            let left_dock = workspace.left_dock();
13304            assert!(left_dock.read(cx).is_open());
13305            assert_eq!(
13306                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13307                panel_1.panel_id(),
13308            );
13309        });
13310
13311        // Emitting a ZoomIn event shows the panel as zoomed.
13312        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
13313        workspace.read_with(cx, |workspace, _| {
13314            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13315            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
13316        });
13317
13318        // Move panel to another dock while it is zoomed
13319        panel_1.update_in(cx, |panel, window, cx| {
13320            panel.set_position(DockPosition::Right, window, cx)
13321        });
13322        workspace.read_with(cx, |workspace, _| {
13323            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13324
13325            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13326        });
13327
13328        // This is a helper for getting a:
13329        // - valid focus on an element,
13330        // - that isn't a part of the panes and panels system of the Workspace,
13331        // - and doesn't trigger the 'on_focus_lost' API.
13332        let focus_other_view = {
13333            let workspace = workspace.clone();
13334            move |cx: &mut VisualTestContext| {
13335                workspace.update_in(cx, |workspace, window, cx| {
13336                    if workspace.active_modal::<TestModal>(cx).is_some() {
13337                        workspace.toggle_modal(window, cx, TestModal::new);
13338                        workspace.toggle_modal(window, cx, TestModal::new);
13339                    } else {
13340                        workspace.toggle_modal(window, cx, TestModal::new);
13341                    }
13342                })
13343            }
13344        };
13345
13346        // If focus is transferred to another view that's not a panel or another pane, we still show
13347        // the panel as zoomed.
13348        focus_other_view(cx);
13349        workspace.read_with(cx, |workspace, _| {
13350            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13351            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13352        });
13353
13354        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13355        workspace.update_in(cx, |_workspace, window, cx| {
13356            cx.focus_self(window);
13357        });
13358        workspace.read_with(cx, |workspace, _| {
13359            assert_eq!(workspace.zoomed, None);
13360            assert_eq!(workspace.zoomed_position, None);
13361        });
13362
13363        // If focus is transferred again to another view that's not a panel or a pane, we won't
13364        // show the panel as zoomed because it wasn't zoomed before.
13365        focus_other_view(cx);
13366        workspace.read_with(cx, |workspace, _| {
13367            assert_eq!(workspace.zoomed, None);
13368            assert_eq!(workspace.zoomed_position, None);
13369        });
13370
13371        // When the panel is activated, it is zoomed again.
13372        cx.dispatch_action(ToggleRightDock);
13373        workspace.read_with(cx, |workspace, _| {
13374            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13375            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13376        });
13377
13378        // Emitting a ZoomOut event unzooms the panel.
13379        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13380        workspace.read_with(cx, |workspace, _| {
13381            assert_eq!(workspace.zoomed, None);
13382            assert_eq!(workspace.zoomed_position, None);
13383        });
13384
13385        // Emit closed event on panel 1, which is active
13386        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13387
13388        // Now the left dock is closed, because panel_1 was the active panel
13389        workspace.update(cx, |workspace, cx| {
13390            let right_dock = workspace.right_dock();
13391            assert!(!right_dock.read(cx).is_open());
13392        });
13393    }
13394
13395    #[gpui::test]
13396    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13397        init_test(cx);
13398
13399        let fs = FakeFs::new(cx.background_executor.clone());
13400        let project = Project::test(fs, [], cx).await;
13401        let (workspace, cx) =
13402            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13403        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13404
13405        let dirty_regular_buffer = cx.new(|cx| {
13406            TestItem::new(cx)
13407                .with_dirty(true)
13408                .with_label("1.txt")
13409                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13410        });
13411        let dirty_regular_buffer_2 = cx.new(|cx| {
13412            TestItem::new(cx)
13413                .with_dirty(true)
13414                .with_label("2.txt")
13415                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13416        });
13417        let dirty_multi_buffer_with_both = cx.new(|cx| {
13418            TestItem::new(cx)
13419                .with_dirty(true)
13420                .with_buffer_kind(ItemBufferKind::Multibuffer)
13421                .with_label("Fake Project Search")
13422                .with_project_items(&[
13423                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13424                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13425                ])
13426        });
13427        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13428        workspace.update_in(cx, |workspace, window, cx| {
13429            workspace.add_item(
13430                pane.clone(),
13431                Box::new(dirty_regular_buffer.clone()),
13432                None,
13433                false,
13434                false,
13435                window,
13436                cx,
13437            );
13438            workspace.add_item(
13439                pane.clone(),
13440                Box::new(dirty_regular_buffer_2.clone()),
13441                None,
13442                false,
13443                false,
13444                window,
13445                cx,
13446            );
13447            workspace.add_item(
13448                pane.clone(),
13449                Box::new(dirty_multi_buffer_with_both.clone()),
13450                None,
13451                false,
13452                false,
13453                window,
13454                cx,
13455            );
13456        });
13457
13458        pane.update_in(cx, |pane, window, cx| {
13459            pane.activate_item(2, true, true, window, cx);
13460            assert_eq!(
13461                pane.active_item().unwrap().item_id(),
13462                multi_buffer_with_both_files_id,
13463                "Should select the multi buffer in the pane"
13464            );
13465        });
13466        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13467            pane.close_other_items(
13468                &CloseOtherItems {
13469                    save_intent: Some(SaveIntent::Save),
13470                    close_pinned: true,
13471                },
13472                None,
13473                window,
13474                cx,
13475            )
13476        });
13477        cx.background_executor.run_until_parked();
13478        assert!(!cx.has_pending_prompt());
13479        close_all_but_multi_buffer_task
13480            .await
13481            .expect("Closing all buffers but the multi buffer failed");
13482        pane.update(cx, |pane, cx| {
13483            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13484            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13485            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13486            assert_eq!(pane.items_len(), 1);
13487            assert_eq!(
13488                pane.active_item().unwrap().item_id(),
13489                multi_buffer_with_both_files_id,
13490                "Should have only the multi buffer left in the pane"
13491            );
13492            assert!(
13493                dirty_multi_buffer_with_both.read(cx).is_dirty,
13494                "The multi buffer containing the unsaved buffer should still be dirty"
13495            );
13496        });
13497
13498        dirty_regular_buffer.update(cx, |buffer, cx| {
13499            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13500        });
13501
13502        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13503            pane.close_active_item(
13504                &CloseActiveItem {
13505                    save_intent: Some(SaveIntent::Close),
13506                    close_pinned: false,
13507                },
13508                window,
13509                cx,
13510            )
13511        });
13512        cx.background_executor.run_until_parked();
13513        assert!(
13514            cx.has_pending_prompt(),
13515            "Dirty multi buffer should prompt a save dialog"
13516        );
13517        cx.simulate_prompt_answer("Save");
13518        cx.background_executor.run_until_parked();
13519        close_multi_buffer_task
13520            .await
13521            .expect("Closing the multi buffer failed");
13522        pane.update(cx, |pane, cx| {
13523            assert_eq!(
13524                dirty_multi_buffer_with_both.read(cx).save_count,
13525                1,
13526                "Multi buffer item should get be saved"
13527            );
13528            // Test impl does not save inner items, so we do not assert them
13529            assert_eq!(
13530                pane.items_len(),
13531                0,
13532                "No more items should be left in the pane"
13533            );
13534            assert!(pane.active_item().is_none());
13535        });
13536    }
13537
13538    #[gpui::test]
13539    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13540        cx: &mut TestAppContext,
13541    ) {
13542        init_test(cx);
13543
13544        let fs = FakeFs::new(cx.background_executor.clone());
13545        let project = Project::test(fs, [], cx).await;
13546        let (workspace, cx) =
13547            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13548        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13549
13550        let dirty_regular_buffer = cx.new(|cx| {
13551            TestItem::new(cx)
13552                .with_dirty(true)
13553                .with_label("1.txt")
13554                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13555        });
13556        let dirty_regular_buffer_2 = cx.new(|cx| {
13557            TestItem::new(cx)
13558                .with_dirty(true)
13559                .with_label("2.txt")
13560                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13561        });
13562        let clear_regular_buffer = cx.new(|cx| {
13563            TestItem::new(cx)
13564                .with_label("3.txt")
13565                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13566        });
13567
13568        let dirty_multi_buffer_with_both = cx.new(|cx| {
13569            TestItem::new(cx)
13570                .with_dirty(true)
13571                .with_buffer_kind(ItemBufferKind::Multibuffer)
13572                .with_label("Fake Project Search")
13573                .with_project_items(&[
13574                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13575                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13576                    clear_regular_buffer.read(cx).project_items[0].clone(),
13577                ])
13578        });
13579        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13580        workspace.update_in(cx, |workspace, window, cx| {
13581            workspace.add_item(
13582                pane.clone(),
13583                Box::new(dirty_regular_buffer.clone()),
13584                None,
13585                false,
13586                false,
13587                window,
13588                cx,
13589            );
13590            workspace.add_item(
13591                pane.clone(),
13592                Box::new(dirty_multi_buffer_with_both.clone()),
13593                None,
13594                false,
13595                false,
13596                window,
13597                cx,
13598            );
13599        });
13600
13601        pane.update_in(cx, |pane, window, cx| {
13602            pane.activate_item(1, true, true, window, cx);
13603            assert_eq!(
13604                pane.active_item().unwrap().item_id(),
13605                multi_buffer_with_both_files_id,
13606                "Should select the multi buffer in the pane"
13607            );
13608        });
13609        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13610            pane.close_active_item(
13611                &CloseActiveItem {
13612                    save_intent: None,
13613                    close_pinned: false,
13614                },
13615                window,
13616                cx,
13617            )
13618        });
13619        cx.background_executor.run_until_parked();
13620        assert!(
13621            cx.has_pending_prompt(),
13622            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13623        );
13624    }
13625
13626    /// Tests that when `close_on_file_delete` is enabled, files are automatically
13627    /// closed when they are deleted from disk.
13628    #[gpui::test]
13629    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13630        init_test(cx);
13631
13632        // Enable the close_on_disk_deletion setting
13633        cx.update_global(|store: &mut SettingsStore, cx| {
13634            store.update_user_settings(cx, |settings| {
13635                settings.workspace.close_on_file_delete = Some(true);
13636            });
13637        });
13638
13639        let fs = FakeFs::new(cx.background_executor.clone());
13640        let project = Project::test(fs, [], cx).await;
13641        let (workspace, cx) =
13642            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13643        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13644
13645        // Create a test item that simulates a file
13646        let item = cx.new(|cx| {
13647            TestItem::new(cx)
13648                .with_label("test.txt")
13649                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13650        });
13651
13652        // Add item to workspace
13653        workspace.update_in(cx, |workspace, window, cx| {
13654            workspace.add_item(
13655                pane.clone(),
13656                Box::new(item.clone()),
13657                None,
13658                false,
13659                false,
13660                window,
13661                cx,
13662            );
13663        });
13664
13665        // Verify the item is in the pane
13666        pane.read_with(cx, |pane, _| {
13667            assert_eq!(pane.items().count(), 1);
13668        });
13669
13670        // Simulate file deletion by setting the item's deleted state
13671        item.update(cx, |item, _| {
13672            item.set_has_deleted_file(true);
13673        });
13674
13675        // Emit UpdateTab event to trigger the close behavior
13676        cx.run_until_parked();
13677        item.update(cx, |_, cx| {
13678            cx.emit(ItemEvent::UpdateTab);
13679        });
13680
13681        // Allow the close operation to complete
13682        cx.run_until_parked();
13683
13684        // Verify the item was automatically closed
13685        pane.read_with(cx, |pane, _| {
13686            assert_eq!(
13687                pane.items().count(),
13688                0,
13689                "Item should be automatically closed when file is deleted"
13690            );
13691        });
13692    }
13693
13694    /// Tests that when `close_on_file_delete` is disabled (default), files remain
13695    /// open with a strikethrough when they are deleted from disk.
13696    #[gpui::test]
13697    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13698        init_test(cx);
13699
13700        // Ensure close_on_disk_deletion is disabled (default)
13701        cx.update_global(|store: &mut SettingsStore, cx| {
13702            store.update_user_settings(cx, |settings| {
13703                settings.workspace.close_on_file_delete = Some(false);
13704            });
13705        });
13706
13707        let fs = FakeFs::new(cx.background_executor.clone());
13708        let project = Project::test(fs, [], cx).await;
13709        let (workspace, cx) =
13710            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13711        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13712
13713        // Create a test item that simulates a file
13714        let item = cx.new(|cx| {
13715            TestItem::new(cx)
13716                .with_label("test.txt")
13717                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13718        });
13719
13720        // Add item to workspace
13721        workspace.update_in(cx, |workspace, window, cx| {
13722            workspace.add_item(
13723                pane.clone(),
13724                Box::new(item.clone()),
13725                None,
13726                false,
13727                false,
13728                window,
13729                cx,
13730            );
13731        });
13732
13733        // Verify the item is in the pane
13734        pane.read_with(cx, |pane, _| {
13735            assert_eq!(pane.items().count(), 1);
13736        });
13737
13738        // Simulate file deletion
13739        item.update(cx, |item, _| {
13740            item.set_has_deleted_file(true);
13741        });
13742
13743        // Emit UpdateTab event
13744        cx.run_until_parked();
13745        item.update(cx, |_, cx| {
13746            cx.emit(ItemEvent::UpdateTab);
13747        });
13748
13749        // Allow any potential close operation to complete
13750        cx.run_until_parked();
13751
13752        // Verify the item remains open (with strikethrough)
13753        pane.read_with(cx, |pane, _| {
13754            assert_eq!(
13755                pane.items().count(),
13756                1,
13757                "Item should remain open when close_on_disk_deletion is disabled"
13758            );
13759        });
13760
13761        // Verify the item shows as deleted
13762        item.read_with(cx, |item, _| {
13763            assert!(
13764                item.has_deleted_file,
13765                "Item should be marked as having deleted file"
13766            );
13767        });
13768    }
13769
13770    /// Tests that dirty files are not automatically closed when deleted from disk,
13771    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13772    /// unsaved changes without being prompted.
13773    #[gpui::test]
13774    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13775        init_test(cx);
13776
13777        // Enable the close_on_file_delete setting
13778        cx.update_global(|store: &mut SettingsStore, cx| {
13779            store.update_user_settings(cx, |settings| {
13780                settings.workspace.close_on_file_delete = Some(true);
13781            });
13782        });
13783
13784        let fs = FakeFs::new(cx.background_executor.clone());
13785        let project = Project::test(fs, [], cx).await;
13786        let (workspace, cx) =
13787            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13788        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13789
13790        // Create a dirty test item
13791        let item = cx.new(|cx| {
13792            TestItem::new(cx)
13793                .with_dirty(true)
13794                .with_label("test.txt")
13795                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13796        });
13797
13798        // Add item to workspace
13799        workspace.update_in(cx, |workspace, window, cx| {
13800            workspace.add_item(
13801                pane.clone(),
13802                Box::new(item.clone()),
13803                None,
13804                false,
13805                false,
13806                window,
13807                cx,
13808            );
13809        });
13810
13811        // Simulate file deletion
13812        item.update(cx, |item, _| {
13813            item.set_has_deleted_file(true);
13814        });
13815
13816        // Emit UpdateTab event to trigger the close behavior
13817        cx.run_until_parked();
13818        item.update(cx, |_, cx| {
13819            cx.emit(ItemEvent::UpdateTab);
13820        });
13821
13822        // Allow any potential close operation to complete
13823        cx.run_until_parked();
13824
13825        // Verify the item remains open (dirty files are not auto-closed)
13826        pane.read_with(cx, |pane, _| {
13827            assert_eq!(
13828                pane.items().count(),
13829                1,
13830                "Dirty items should not be automatically closed even when file is deleted"
13831            );
13832        });
13833
13834        // Verify the item is marked as deleted and still dirty
13835        item.read_with(cx, |item, _| {
13836            assert!(
13837                item.has_deleted_file,
13838                "Item should be marked as having deleted file"
13839            );
13840            assert!(item.is_dirty, "Item should still be dirty");
13841        });
13842    }
13843
13844    /// Tests that navigation history is cleaned up when files are auto-closed
13845    /// due to deletion from disk.
13846    #[gpui::test]
13847    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13848        init_test(cx);
13849
13850        // Enable the close_on_file_delete setting
13851        cx.update_global(|store: &mut SettingsStore, cx| {
13852            store.update_user_settings(cx, |settings| {
13853                settings.workspace.close_on_file_delete = Some(true);
13854            });
13855        });
13856
13857        let fs = FakeFs::new(cx.background_executor.clone());
13858        let project = Project::test(fs, [], cx).await;
13859        let (workspace, cx) =
13860            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13861        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13862
13863        // Create test items
13864        let item1 = cx.new(|cx| {
13865            TestItem::new(cx)
13866                .with_label("test1.txt")
13867                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13868        });
13869        let item1_id = item1.item_id();
13870
13871        let item2 = cx.new(|cx| {
13872            TestItem::new(cx)
13873                .with_label("test2.txt")
13874                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13875        });
13876
13877        // Add items to workspace
13878        workspace.update_in(cx, |workspace, window, cx| {
13879            workspace.add_item(
13880                pane.clone(),
13881                Box::new(item1.clone()),
13882                None,
13883                false,
13884                false,
13885                window,
13886                cx,
13887            );
13888            workspace.add_item(
13889                pane.clone(),
13890                Box::new(item2.clone()),
13891                None,
13892                false,
13893                false,
13894                window,
13895                cx,
13896            );
13897        });
13898
13899        // Activate item1 to ensure it gets navigation entries
13900        pane.update_in(cx, |pane, window, cx| {
13901            pane.activate_item(0, true, true, window, cx);
13902        });
13903
13904        // Switch to item2 and back to create navigation history
13905        pane.update_in(cx, |pane, window, cx| {
13906            pane.activate_item(1, true, true, window, cx);
13907        });
13908        cx.run_until_parked();
13909
13910        pane.update_in(cx, |pane, window, cx| {
13911            pane.activate_item(0, true, true, window, cx);
13912        });
13913        cx.run_until_parked();
13914
13915        // Simulate file deletion for item1
13916        item1.update(cx, |item, _| {
13917            item.set_has_deleted_file(true);
13918        });
13919
13920        // Emit UpdateTab event to trigger the close behavior
13921        item1.update(cx, |_, cx| {
13922            cx.emit(ItemEvent::UpdateTab);
13923        });
13924        cx.run_until_parked();
13925
13926        // Verify item1 was closed
13927        pane.read_with(cx, |pane, _| {
13928            assert_eq!(
13929                pane.items().count(),
13930                1,
13931                "Should have 1 item remaining after auto-close"
13932            );
13933        });
13934
13935        // Check navigation history after close
13936        let has_item = pane.read_with(cx, |pane, cx| {
13937            let mut has_item = false;
13938            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13939                if entry.item.id() == item1_id {
13940                    has_item = true;
13941                }
13942            });
13943            has_item
13944        });
13945
13946        assert!(
13947            !has_item,
13948            "Navigation history should not contain closed item entries"
13949        );
13950    }
13951
13952    #[gpui::test]
13953    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13954        cx: &mut TestAppContext,
13955    ) {
13956        init_test(cx);
13957
13958        let fs = FakeFs::new(cx.background_executor.clone());
13959        let project = Project::test(fs, [], cx).await;
13960        let (workspace, cx) =
13961            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13962        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13963
13964        let dirty_regular_buffer = cx.new(|cx| {
13965            TestItem::new(cx)
13966                .with_dirty(true)
13967                .with_label("1.txt")
13968                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13969        });
13970        let dirty_regular_buffer_2 = cx.new(|cx| {
13971            TestItem::new(cx)
13972                .with_dirty(true)
13973                .with_label("2.txt")
13974                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13975        });
13976        let clear_regular_buffer = cx.new(|cx| {
13977            TestItem::new(cx)
13978                .with_label("3.txt")
13979                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13980        });
13981
13982        let dirty_multi_buffer = cx.new(|cx| {
13983            TestItem::new(cx)
13984                .with_dirty(true)
13985                .with_buffer_kind(ItemBufferKind::Multibuffer)
13986                .with_label("Fake Project Search")
13987                .with_project_items(&[
13988                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13989                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13990                    clear_regular_buffer.read(cx).project_items[0].clone(),
13991                ])
13992        });
13993        workspace.update_in(cx, |workspace, window, cx| {
13994            workspace.add_item(
13995                pane.clone(),
13996                Box::new(dirty_regular_buffer.clone()),
13997                None,
13998                false,
13999                false,
14000                window,
14001                cx,
14002            );
14003            workspace.add_item(
14004                pane.clone(),
14005                Box::new(dirty_regular_buffer_2.clone()),
14006                None,
14007                false,
14008                false,
14009                window,
14010                cx,
14011            );
14012            workspace.add_item(
14013                pane.clone(),
14014                Box::new(dirty_multi_buffer.clone()),
14015                None,
14016                false,
14017                false,
14018                window,
14019                cx,
14020            );
14021        });
14022
14023        pane.update_in(cx, |pane, window, cx| {
14024            pane.activate_item(2, true, true, window, cx);
14025            assert_eq!(
14026                pane.active_item().unwrap().item_id(),
14027                dirty_multi_buffer.item_id(),
14028                "Should select the multi buffer in the pane"
14029            );
14030        });
14031        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
14032            pane.close_active_item(
14033                &CloseActiveItem {
14034                    save_intent: None,
14035                    close_pinned: false,
14036                },
14037                window,
14038                cx,
14039            )
14040        });
14041        cx.background_executor.run_until_parked();
14042        assert!(
14043            !cx.has_pending_prompt(),
14044            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
14045        );
14046        close_multi_buffer_task
14047            .await
14048            .expect("Closing multi buffer failed");
14049        pane.update(cx, |pane, cx| {
14050            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
14051            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
14052            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
14053            assert_eq!(
14054                pane.items()
14055                    .map(|item| item.item_id())
14056                    .sorted()
14057                    .collect::<Vec<_>>(),
14058                vec![
14059                    dirty_regular_buffer.item_id(),
14060                    dirty_regular_buffer_2.item_id(),
14061                ],
14062                "Should have no multi buffer left in the pane"
14063            );
14064            assert!(dirty_regular_buffer.read(cx).is_dirty);
14065            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
14066        });
14067    }
14068
14069    #[gpui::test]
14070    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
14071        init_test(cx);
14072        let fs = FakeFs::new(cx.executor());
14073        let project = Project::test(fs, [], cx).await;
14074        let (multi_workspace, cx) =
14075            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14076        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14077
14078        // Add a new panel to the right dock, opening the dock and setting the
14079        // focus to the new panel.
14080        let panel = workspace.update_in(cx, |workspace, window, cx| {
14081            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14082            workspace.add_panel(panel.clone(), window, cx);
14083
14084            workspace
14085                .right_dock()
14086                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14087
14088            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14089
14090            panel
14091        });
14092
14093        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
14094        // panel to the next valid position which, in this case, is the left
14095        // dock.
14096        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14097        workspace.update(cx, |workspace, cx| {
14098            assert!(workspace.left_dock().read(cx).is_open());
14099            assert_eq!(panel.read(cx).position, DockPosition::Left);
14100        });
14101
14102        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
14103        // panel to the next valid position which, in this case, is the bottom
14104        // dock.
14105        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14106        workspace.update(cx, |workspace, cx| {
14107            assert!(workspace.bottom_dock().read(cx).is_open());
14108            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
14109        });
14110
14111        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
14112        // around moving the panel to its initial position, the right dock.
14113        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14114        workspace.update(cx, |workspace, cx| {
14115            assert!(workspace.right_dock().read(cx).is_open());
14116            assert_eq!(panel.read(cx).position, DockPosition::Right);
14117        });
14118
14119        // Remove focus from the panel, ensuring that, if the panel is not
14120        // focused, the `MoveFocusedPanelToNextPosition` action does not update
14121        // the panel's position, so the panel is still in the right dock.
14122        workspace.update_in(cx, |workspace, window, cx| {
14123            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14124        });
14125
14126        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14127        workspace.update(cx, |workspace, cx| {
14128            assert!(workspace.right_dock().read(cx).is_open());
14129            assert_eq!(panel.read(cx).position, DockPosition::Right);
14130        });
14131    }
14132
14133    #[gpui::test]
14134    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
14135        init_test(cx);
14136
14137        let fs = FakeFs::new(cx.executor());
14138        let project = Project::test(fs, [], cx).await;
14139        let (workspace, cx) =
14140            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14141
14142        let item_1 = cx.new(|cx| {
14143            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14144        });
14145        workspace.update_in(cx, |workspace, window, cx| {
14146            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14147            workspace.move_item_to_pane_in_direction(
14148                &MoveItemToPaneInDirection {
14149                    direction: SplitDirection::Right,
14150                    focus: true,
14151                    clone: false,
14152                },
14153                window,
14154                cx,
14155            );
14156            workspace.move_item_to_pane_at_index(
14157                &MoveItemToPane {
14158                    destination: 3,
14159                    focus: true,
14160                    clone: false,
14161                },
14162                window,
14163                cx,
14164            );
14165
14166            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
14167            assert_eq!(
14168                pane_items_paths(&workspace.active_pane, cx),
14169                vec!["first.txt".to_string()],
14170                "Single item was not moved anywhere"
14171            );
14172        });
14173
14174        let item_2 = cx.new(|cx| {
14175            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
14176        });
14177        workspace.update_in(cx, |workspace, window, cx| {
14178            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
14179            assert_eq!(
14180                pane_items_paths(&workspace.panes[0], cx),
14181                vec!["first.txt".to_string(), "second.txt".to_string()],
14182            );
14183            workspace.move_item_to_pane_in_direction(
14184                &MoveItemToPaneInDirection {
14185                    direction: SplitDirection::Right,
14186                    focus: true,
14187                    clone: false,
14188                },
14189                window,
14190                cx,
14191            );
14192
14193            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
14194            assert_eq!(
14195                pane_items_paths(&workspace.panes[0], cx),
14196                vec!["first.txt".to_string()],
14197                "After moving, one item should be left in the original pane"
14198            );
14199            assert_eq!(
14200                pane_items_paths(&workspace.panes[1], cx),
14201                vec!["second.txt".to_string()],
14202                "New item should have been moved to the new pane"
14203            );
14204        });
14205
14206        let item_3 = cx.new(|cx| {
14207            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
14208        });
14209        workspace.update_in(cx, |workspace, window, cx| {
14210            let original_pane = workspace.panes[0].clone();
14211            workspace.set_active_pane(&original_pane, window, cx);
14212            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
14213            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
14214            assert_eq!(
14215                pane_items_paths(&workspace.active_pane, cx),
14216                vec!["first.txt".to_string(), "third.txt".to_string()],
14217                "New pane should be ready to move one item out"
14218            );
14219
14220            workspace.move_item_to_pane_at_index(
14221                &MoveItemToPane {
14222                    destination: 3,
14223                    focus: true,
14224                    clone: false,
14225                },
14226                window,
14227                cx,
14228            );
14229            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
14230            assert_eq!(
14231                pane_items_paths(&workspace.active_pane, cx),
14232                vec!["first.txt".to_string()],
14233                "After moving, one item should be left in the original pane"
14234            );
14235            assert_eq!(
14236                pane_items_paths(&workspace.panes[1], cx),
14237                vec!["second.txt".to_string()],
14238                "Previously created pane should be unchanged"
14239            );
14240            assert_eq!(
14241                pane_items_paths(&workspace.panes[2], cx),
14242                vec!["third.txt".to_string()],
14243                "New item should have been moved to the new pane"
14244            );
14245        });
14246    }
14247
14248    #[gpui::test]
14249    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
14250        init_test(cx);
14251
14252        let fs = FakeFs::new(cx.executor());
14253        let project = Project::test(fs, [], cx).await;
14254        let (workspace, cx) =
14255            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14256
14257        let item_1 = cx.new(|cx| {
14258            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14259        });
14260        workspace.update_in(cx, |workspace, window, cx| {
14261            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14262            workspace.move_item_to_pane_in_direction(
14263                &MoveItemToPaneInDirection {
14264                    direction: SplitDirection::Right,
14265                    focus: true,
14266                    clone: true,
14267                },
14268                window,
14269                cx,
14270            );
14271        });
14272        cx.run_until_parked();
14273        workspace.update_in(cx, |workspace, window, cx| {
14274            workspace.move_item_to_pane_at_index(
14275                &MoveItemToPane {
14276                    destination: 3,
14277                    focus: true,
14278                    clone: true,
14279                },
14280                window,
14281                cx,
14282            );
14283        });
14284        cx.run_until_parked();
14285
14286        workspace.update(cx, |workspace, cx| {
14287            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
14288            for pane in workspace.panes() {
14289                assert_eq!(
14290                    pane_items_paths(pane, cx),
14291                    vec!["first.txt".to_string()],
14292                    "Single item exists in all panes"
14293                );
14294            }
14295        });
14296
14297        // verify that the active pane has been updated after waiting for the
14298        // pane focus event to fire and resolve
14299        workspace.read_with(cx, |workspace, _app| {
14300            assert_eq!(
14301                workspace.active_pane(),
14302                &workspace.panes[2],
14303                "The third pane should be the active one: {:?}",
14304                workspace.panes
14305            );
14306        })
14307    }
14308
14309    #[gpui::test]
14310    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
14311        init_test(cx);
14312
14313        let fs = FakeFs::new(cx.executor());
14314        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
14315
14316        let project = Project::test(fs, ["root".as_ref()], cx).await;
14317        let (workspace, cx) =
14318            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14319
14320        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14321        // Add item to pane A with project path
14322        let item_a = cx.new(|cx| {
14323            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14324        });
14325        workspace.update_in(cx, |workspace, window, cx| {
14326            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14327        });
14328
14329        // Split to create pane B
14330        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14331            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14332        });
14333
14334        // Add item with SAME project path to pane B, and pin it
14335        let item_b = cx.new(|cx| {
14336            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14337        });
14338        pane_b.update_in(cx, |pane, window, cx| {
14339            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14340            pane.set_pinned_count(1);
14341        });
14342
14343        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14344        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14345
14346        // close_pinned: false should only close the unpinned copy
14347        workspace.update_in(cx, |workspace, window, cx| {
14348            workspace.close_item_in_all_panes(
14349                &CloseItemInAllPanes {
14350                    save_intent: Some(SaveIntent::Close),
14351                    close_pinned: false,
14352                },
14353                window,
14354                cx,
14355            )
14356        });
14357        cx.executor().run_until_parked();
14358
14359        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14360        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14361        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14362        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14363
14364        // Split again, seeing as closing the previous item also closed its
14365        // pane, so only pane remains, which does not allow us to properly test
14366        // that both items close when `close_pinned: true`.
14367        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14368            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14369        });
14370
14371        // Add an item with the same project path to pane C so that
14372        // close_item_in_all_panes can determine what to close across all panes
14373        // (it reads the active item from the active pane, and split_pane
14374        // creates an empty pane).
14375        let item_c = cx.new(|cx| {
14376            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14377        });
14378        pane_c.update_in(cx, |pane, window, cx| {
14379            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14380        });
14381
14382        // close_pinned: true should close the pinned copy too
14383        workspace.update_in(cx, |workspace, window, cx| {
14384            let panes_count = workspace.panes().len();
14385            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14386
14387            workspace.close_item_in_all_panes(
14388                &CloseItemInAllPanes {
14389                    save_intent: Some(SaveIntent::Close),
14390                    close_pinned: true,
14391                },
14392                window,
14393                cx,
14394            )
14395        });
14396        cx.executor().run_until_parked();
14397
14398        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14399        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14400        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14401        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14402    }
14403
14404    mod register_project_item_tests {
14405
14406        use super::*;
14407
14408        // View
14409        struct TestPngItemView {
14410            focus_handle: FocusHandle,
14411        }
14412        // Model
14413        struct TestPngItem {}
14414
14415        impl project::ProjectItem for TestPngItem {
14416            fn try_open(
14417                _project: &Entity<Project>,
14418                path: &ProjectPath,
14419                cx: &mut App,
14420            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14421                if path.path.extension().unwrap() == "png" {
14422                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14423                } else {
14424                    None
14425                }
14426            }
14427
14428            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14429                None
14430            }
14431
14432            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14433                None
14434            }
14435
14436            fn is_dirty(&self) -> bool {
14437                false
14438            }
14439        }
14440
14441        impl Item for TestPngItemView {
14442            type Event = ();
14443            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14444                "".into()
14445            }
14446        }
14447        impl EventEmitter<()> for TestPngItemView {}
14448        impl Focusable for TestPngItemView {
14449            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14450                self.focus_handle.clone()
14451            }
14452        }
14453
14454        impl Render for TestPngItemView {
14455            fn render(
14456                &mut self,
14457                _window: &mut Window,
14458                _cx: &mut Context<Self>,
14459            ) -> impl IntoElement {
14460                Empty
14461            }
14462        }
14463
14464        impl ProjectItem for TestPngItemView {
14465            type Item = TestPngItem;
14466
14467            fn for_project_item(
14468                _project: Entity<Project>,
14469                _pane: Option<&Pane>,
14470                _item: Entity<Self::Item>,
14471                _: &mut Window,
14472                cx: &mut Context<Self>,
14473            ) -> Self
14474            where
14475                Self: Sized,
14476            {
14477                Self {
14478                    focus_handle: cx.focus_handle(),
14479                }
14480            }
14481        }
14482
14483        // View
14484        struct TestIpynbItemView {
14485            focus_handle: FocusHandle,
14486        }
14487        // Model
14488        struct TestIpynbItem {}
14489
14490        impl project::ProjectItem for TestIpynbItem {
14491            fn try_open(
14492                _project: &Entity<Project>,
14493                path: &ProjectPath,
14494                cx: &mut App,
14495            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14496                if path.path.extension().unwrap() == "ipynb" {
14497                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14498                } else {
14499                    None
14500                }
14501            }
14502
14503            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14504                None
14505            }
14506
14507            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14508                None
14509            }
14510
14511            fn is_dirty(&self) -> bool {
14512                false
14513            }
14514        }
14515
14516        impl Item for TestIpynbItemView {
14517            type Event = ();
14518            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14519                "".into()
14520            }
14521        }
14522        impl EventEmitter<()> for TestIpynbItemView {}
14523        impl Focusable for TestIpynbItemView {
14524            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14525                self.focus_handle.clone()
14526            }
14527        }
14528
14529        impl Render for TestIpynbItemView {
14530            fn render(
14531                &mut self,
14532                _window: &mut Window,
14533                _cx: &mut Context<Self>,
14534            ) -> impl IntoElement {
14535                Empty
14536            }
14537        }
14538
14539        impl ProjectItem for TestIpynbItemView {
14540            type Item = TestIpynbItem;
14541
14542            fn for_project_item(
14543                _project: Entity<Project>,
14544                _pane: Option<&Pane>,
14545                _item: Entity<Self::Item>,
14546                _: &mut Window,
14547                cx: &mut Context<Self>,
14548            ) -> Self
14549            where
14550                Self: Sized,
14551            {
14552                Self {
14553                    focus_handle: cx.focus_handle(),
14554                }
14555            }
14556        }
14557
14558        struct TestAlternatePngItemView {
14559            focus_handle: FocusHandle,
14560        }
14561
14562        impl Item for TestAlternatePngItemView {
14563            type Event = ();
14564            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14565                "".into()
14566            }
14567        }
14568
14569        impl EventEmitter<()> for TestAlternatePngItemView {}
14570        impl Focusable for TestAlternatePngItemView {
14571            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14572                self.focus_handle.clone()
14573            }
14574        }
14575
14576        impl Render for TestAlternatePngItemView {
14577            fn render(
14578                &mut self,
14579                _window: &mut Window,
14580                _cx: &mut Context<Self>,
14581            ) -> impl IntoElement {
14582                Empty
14583            }
14584        }
14585
14586        impl ProjectItem for TestAlternatePngItemView {
14587            type Item = TestPngItem;
14588
14589            fn for_project_item(
14590                _project: Entity<Project>,
14591                _pane: Option<&Pane>,
14592                _item: Entity<Self::Item>,
14593                _: &mut Window,
14594                cx: &mut Context<Self>,
14595            ) -> Self
14596            where
14597                Self: Sized,
14598            {
14599                Self {
14600                    focus_handle: cx.focus_handle(),
14601                }
14602            }
14603        }
14604
14605        #[gpui::test]
14606        async fn test_register_project_item(cx: &mut TestAppContext) {
14607            init_test(cx);
14608
14609            cx.update(|cx| {
14610                register_project_item::<TestPngItemView>(cx);
14611                register_project_item::<TestIpynbItemView>(cx);
14612            });
14613
14614            let fs = FakeFs::new(cx.executor());
14615            fs.insert_tree(
14616                "/root1",
14617                json!({
14618                    "one.png": "BINARYDATAHERE",
14619                    "two.ipynb": "{ totally a notebook }",
14620                    "three.txt": "editing text, sure why not?"
14621                }),
14622            )
14623            .await;
14624
14625            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14626            let (workspace, cx) =
14627                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14628
14629            let worktree_id = project.update(cx, |project, cx| {
14630                project.worktrees(cx).next().unwrap().read(cx).id()
14631            });
14632
14633            let handle = workspace
14634                .update_in(cx, |workspace, window, cx| {
14635                    let project_path = (worktree_id, rel_path("one.png"));
14636                    workspace.open_path(project_path, None, true, window, cx)
14637                })
14638                .await
14639                .unwrap();
14640
14641            // Now we can check if the handle we got back errored or not
14642            assert_eq!(
14643                handle.to_any_view().entity_type(),
14644                TypeId::of::<TestPngItemView>()
14645            );
14646
14647            let handle = workspace
14648                .update_in(cx, |workspace, window, cx| {
14649                    let project_path = (worktree_id, rel_path("two.ipynb"));
14650                    workspace.open_path(project_path, None, true, window, cx)
14651                })
14652                .await
14653                .unwrap();
14654
14655            assert_eq!(
14656                handle.to_any_view().entity_type(),
14657                TypeId::of::<TestIpynbItemView>()
14658            );
14659
14660            let handle = workspace
14661                .update_in(cx, |workspace, window, cx| {
14662                    let project_path = (worktree_id, rel_path("three.txt"));
14663                    workspace.open_path(project_path, None, true, window, cx)
14664                })
14665                .await;
14666            assert!(handle.is_err());
14667        }
14668
14669        #[gpui::test]
14670        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14671            init_test(cx);
14672
14673            cx.update(|cx| {
14674                register_project_item::<TestPngItemView>(cx);
14675                register_project_item::<TestAlternatePngItemView>(cx);
14676            });
14677
14678            let fs = FakeFs::new(cx.executor());
14679            fs.insert_tree(
14680                "/root1",
14681                json!({
14682                    "one.png": "BINARYDATAHERE",
14683                    "two.ipynb": "{ totally a notebook }",
14684                    "three.txt": "editing text, sure why not?"
14685                }),
14686            )
14687            .await;
14688            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14689            let (workspace, cx) =
14690                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14691            let worktree_id = project.update(cx, |project, cx| {
14692                project.worktrees(cx).next().unwrap().read(cx).id()
14693            });
14694
14695            let handle = workspace
14696                .update_in(cx, |workspace, window, cx| {
14697                    let project_path = (worktree_id, rel_path("one.png"));
14698                    workspace.open_path(project_path, None, true, window, cx)
14699                })
14700                .await
14701                .unwrap();
14702
14703            // This _must_ be the second item registered
14704            assert_eq!(
14705                handle.to_any_view().entity_type(),
14706                TypeId::of::<TestAlternatePngItemView>()
14707            );
14708
14709            let handle = workspace
14710                .update_in(cx, |workspace, window, cx| {
14711                    let project_path = (worktree_id, rel_path("three.txt"));
14712                    workspace.open_path(project_path, None, true, window, cx)
14713                })
14714                .await;
14715            assert!(handle.is_err());
14716        }
14717    }
14718
14719    #[gpui::test]
14720    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14721        init_test(cx);
14722
14723        let fs = FakeFs::new(cx.executor());
14724        let project = Project::test(fs, [], cx).await;
14725        let (workspace, _cx) =
14726            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14727
14728        // Test with status bar shown (default)
14729        workspace.read_with(cx, |workspace, cx| {
14730            let visible = workspace.status_bar_visible(cx);
14731            assert!(visible, "Status bar should be visible by default");
14732        });
14733
14734        // Test with status bar hidden
14735        cx.update_global(|store: &mut SettingsStore, cx| {
14736            store.update_user_settings(cx, |settings| {
14737                settings.status_bar.get_or_insert_default().show = Some(false);
14738            });
14739        });
14740
14741        workspace.read_with(cx, |workspace, cx| {
14742            let visible = workspace.status_bar_visible(cx);
14743            assert!(!visible, "Status bar should be hidden when show is false");
14744        });
14745
14746        // Test with status bar shown explicitly
14747        cx.update_global(|store: &mut SettingsStore, cx| {
14748            store.update_user_settings(cx, |settings| {
14749                settings.status_bar.get_or_insert_default().show = Some(true);
14750            });
14751        });
14752
14753        workspace.read_with(cx, |workspace, cx| {
14754            let visible = workspace.status_bar_visible(cx);
14755            assert!(visible, "Status bar should be visible when show is true");
14756        });
14757    }
14758
14759    #[gpui::test]
14760    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14761        init_test(cx);
14762
14763        let fs = FakeFs::new(cx.executor());
14764        let project = Project::test(fs, [], cx).await;
14765        let (multi_workspace, cx) =
14766            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14767        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14768        let panel = workspace.update_in(cx, |workspace, window, cx| {
14769            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14770            workspace.add_panel(panel.clone(), window, cx);
14771
14772            workspace
14773                .right_dock()
14774                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14775
14776            panel
14777        });
14778
14779        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14780        let item_a = cx.new(TestItem::new);
14781        let item_b = cx.new(TestItem::new);
14782        let item_a_id = item_a.entity_id();
14783        let item_b_id = item_b.entity_id();
14784
14785        pane.update_in(cx, |pane, window, cx| {
14786            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14787            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14788        });
14789
14790        pane.read_with(cx, |pane, _| {
14791            assert_eq!(pane.items_len(), 2);
14792            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14793        });
14794
14795        workspace.update_in(cx, |workspace, window, cx| {
14796            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14797        });
14798
14799        workspace.update_in(cx, |_, window, cx| {
14800            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14801        });
14802
14803        // Assert that the `pane::CloseActiveItem` action is handled at the
14804        // workspace level when one of the dock panels is focused and, in that
14805        // case, the center pane's active item is closed but the focus is not
14806        // moved.
14807        cx.dispatch_action(pane::CloseActiveItem::default());
14808        cx.run_until_parked();
14809
14810        pane.read_with(cx, |pane, _| {
14811            assert_eq!(pane.items_len(), 1);
14812            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14813        });
14814
14815        workspace.update_in(cx, |workspace, window, cx| {
14816            assert!(workspace.right_dock().read(cx).is_open());
14817            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14818        });
14819    }
14820
14821    #[gpui::test]
14822    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14823        init_test(cx);
14824        let fs = FakeFs::new(cx.executor());
14825
14826        let project_a = Project::test(fs.clone(), [], cx).await;
14827        let project_b = Project::test(fs, [], cx).await;
14828
14829        let multi_workspace_handle =
14830            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14831        cx.run_until_parked();
14832
14833        multi_workspace_handle
14834            .update(cx, |mw, _window, cx| {
14835                mw.open_sidebar(cx);
14836            })
14837            .unwrap();
14838
14839        let workspace_a = multi_workspace_handle
14840            .read_with(cx, |mw, _| mw.workspace().clone())
14841            .unwrap();
14842
14843        let _workspace_b = multi_workspace_handle
14844            .update(cx, |mw, window, cx| {
14845                mw.test_add_workspace(project_b, window, cx)
14846            })
14847            .unwrap();
14848
14849        // Switch to workspace A
14850        multi_workspace_handle
14851            .update(cx, |mw, window, cx| {
14852                let workspace = mw.workspaces().next().unwrap().clone();
14853                mw.activate(workspace, window, cx);
14854            })
14855            .unwrap();
14856
14857        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14858
14859        // Add a panel to workspace A's right dock and open the dock
14860        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14861            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14862            workspace.add_panel(panel.clone(), window, cx);
14863            workspace
14864                .right_dock()
14865                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14866            panel
14867        });
14868
14869        // Focus the panel through the workspace (matching existing test pattern)
14870        workspace_a.update_in(cx, |workspace, window, cx| {
14871            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14872        });
14873
14874        // Zoom the panel
14875        panel.update_in(cx, |panel, window, cx| {
14876            panel.set_zoomed(true, window, cx);
14877        });
14878
14879        // Verify the panel is zoomed and the dock is open
14880        workspace_a.update_in(cx, |workspace, window, cx| {
14881            assert!(
14882                workspace.right_dock().read(cx).is_open(),
14883                "dock should be open before switch"
14884            );
14885            assert!(
14886                panel.is_zoomed(window, cx),
14887                "panel should be zoomed before switch"
14888            );
14889            assert!(
14890                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14891                "panel should be focused before switch"
14892            );
14893        });
14894
14895        // Switch to workspace B
14896        multi_workspace_handle
14897            .update(cx, |mw, window, cx| {
14898                let workspace = mw.workspaces().nth(1).unwrap().clone();
14899                mw.activate(workspace, window, cx);
14900            })
14901            .unwrap();
14902        cx.run_until_parked();
14903
14904        // Switch back to workspace A
14905        multi_workspace_handle
14906            .update(cx, |mw, window, cx| {
14907                let workspace = mw.workspaces().next().unwrap().clone();
14908                mw.activate(workspace, window, cx);
14909            })
14910            .unwrap();
14911        cx.run_until_parked();
14912
14913        // Verify the panel is still zoomed and the dock is still open
14914        workspace_a.update_in(cx, |workspace, window, cx| {
14915            assert!(
14916                workspace.right_dock().read(cx).is_open(),
14917                "dock should still be open after switching back"
14918            );
14919            assert!(
14920                panel.is_zoomed(window, cx),
14921                "panel should still be zoomed after switching back"
14922            );
14923        });
14924    }
14925
14926    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14927        pane.read(cx)
14928            .items()
14929            .flat_map(|item| {
14930                item.project_paths(cx)
14931                    .into_iter()
14932                    .map(|path| path.path.display(PathStyle::local()).into_owned())
14933            })
14934            .collect()
14935    }
14936
14937    pub fn init_test(cx: &mut TestAppContext) {
14938        cx.update(|cx| {
14939            let settings_store = SettingsStore::test(cx);
14940            cx.set_global(settings_store);
14941            cx.set_global(db::AppDatabase::test_new());
14942            theme_settings::init(theme::LoadThemes::JustBase, cx);
14943        });
14944    }
14945
14946    #[gpui::test]
14947    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14948        use settings::{ThemeName, ThemeSelection};
14949        use theme::SystemAppearance;
14950        use zed_actions::theme::ToggleMode;
14951
14952        init_test(cx);
14953
14954        let fs = FakeFs::new(cx.executor());
14955        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14956
14957        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14958            .await;
14959
14960        // Build a test project and workspace view so the test can invoke
14961        // the workspace action handler the same way the UI would.
14962        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14963        let (workspace, cx) =
14964            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14965
14966        // Seed the settings file with a plain static light theme so the
14967        // first toggle always starts from a known persisted state.
14968        workspace.update_in(cx, |_workspace, _window, cx| {
14969            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14970            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14971                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14972            });
14973        });
14974        cx.executor().advance_clock(Duration::from_millis(200));
14975        cx.run_until_parked();
14976
14977        // Confirm the initial persisted settings contain the static theme
14978        // we just wrote before any toggling happens.
14979        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14980        assert!(settings_text.contains(r#""theme": "One Light""#));
14981
14982        // Toggle once. This should migrate the persisted theme settings
14983        // into light/dark slots and enable system mode.
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        // 1. Static -> Dynamic
14991        // this assertion checks theme changed from static to dynamic.
14992        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14993        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14994        assert_eq!(
14995            parsed["theme"],
14996            serde_json::json!({
14997                "mode": "system",
14998                "light": "One Light",
14999                "dark": "One Dark"
15000            })
15001        );
15002
15003        // 2. Toggle again, suppose it will change the mode to light
15004        workspace.update_in(cx, |workspace, window, cx| {
15005            workspace.toggle_theme_mode(&ToggleMode, window, cx);
15006        });
15007        cx.executor().advance_clock(Duration::from_millis(200));
15008        cx.run_until_parked();
15009
15010        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
15011        assert!(settings_text.contains(r#""mode": "light""#));
15012    }
15013
15014    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
15015        let item = TestProjectItem::new(id, path, cx);
15016        item.update(cx, |item, _| {
15017            item.is_dirty = true;
15018        });
15019        item
15020    }
15021
15022    #[gpui::test]
15023    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
15024        cx: &mut gpui::TestAppContext,
15025    ) {
15026        init_test(cx);
15027        let fs = FakeFs::new(cx.executor());
15028
15029        let project = Project::test(fs, [], cx).await;
15030        let (workspace, cx) =
15031            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
15032
15033        let panel = workspace.update_in(cx, |workspace, window, cx| {
15034            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
15035            workspace.add_panel(panel.clone(), window, cx);
15036            workspace
15037                .right_dock()
15038                .update(cx, |dock, cx| dock.set_open(true, window, cx));
15039            panel
15040        });
15041
15042        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
15043        pane.update_in(cx, |pane, window, cx| {
15044            let item = cx.new(TestItem::new);
15045            pane.add_item(Box::new(item), true, true, None, window, cx);
15046        });
15047
15048        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
15049        // mirrors the real-world flow and avoids side effects from directly
15050        // focusing the panel while the center pane is active.
15051        workspace.update_in(cx, |workspace, window, cx| {
15052            workspace.toggle_panel_focus::<TestPanel>(window, cx);
15053        });
15054
15055        panel.update_in(cx, |panel, window, cx| {
15056            panel.set_zoomed(true, window, cx);
15057        });
15058
15059        workspace.update_in(cx, |workspace, window, cx| {
15060            assert!(workspace.right_dock().read(cx).is_open());
15061            assert!(panel.is_zoomed(window, cx));
15062            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
15063        });
15064
15065        // Simulate a spurious pane::Event::Focus on the center pane while the
15066        // panel still has focus. This mirrors what happens during macOS window
15067        // activation: the center pane fires a focus event even though actual
15068        // focus remains on the dock panel.
15069        pane.update_in(cx, |_, _, cx| {
15070            cx.emit(pane::Event::Focus);
15071        });
15072
15073        // The dock must remain open because the panel had focus at the time the
15074        // event was processed. Before the fix, dock_to_preserve was None for
15075        // panels that don't implement pane(), causing the dock to close.
15076        workspace.update_in(cx, |workspace, window, cx| {
15077            assert!(
15078                workspace.right_dock().read(cx).is_open(),
15079                "Dock should stay open when its zoomed panel (without pane()) still has focus"
15080            );
15081            assert!(panel.is_zoomed(window, cx));
15082        });
15083    }
15084
15085    #[gpui::test]
15086    async fn test_panels_stay_open_after_position_change_and_settings_update(
15087        cx: &mut gpui::TestAppContext,
15088    ) {
15089        init_test(cx);
15090        let fs = FakeFs::new(cx.executor());
15091        let project = Project::test(fs, [], cx).await;
15092        let (workspace, cx) =
15093            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
15094
15095        // Add two panels to the left dock and open it.
15096        let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
15097            let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
15098            let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
15099            workspace.add_panel(panel_a.clone(), window, cx);
15100            workspace.add_panel(panel_b.clone(), window, cx);
15101            workspace.left_dock().update(cx, |dock, cx| {
15102                dock.set_open(true, window, cx);
15103                dock.activate_panel(0, window, cx);
15104            });
15105            (panel_a, panel_b)
15106        });
15107
15108        workspace.update_in(cx, |workspace, _, cx| {
15109            assert!(workspace.left_dock().read(cx).is_open());
15110        });
15111
15112        // Simulate a feature flag changing default dock positions: both panels
15113        // move from Left to Right.
15114        workspace.update_in(cx, |_workspace, _window, cx| {
15115            panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
15116            panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
15117            cx.update_global::<SettingsStore, _>(|_, _| {});
15118        });
15119
15120        // Both panels should now be in the right dock.
15121        workspace.update_in(cx, |workspace, _, cx| {
15122            let right_dock = workspace.right_dock().read(cx);
15123            assert_eq!(right_dock.panels_len(), 2);
15124        });
15125
15126        // Open the right dock and activate panel_b (simulating the user
15127        // opening the panel after it moved).
15128        workspace.update_in(cx, |workspace, window, cx| {
15129            workspace.right_dock().update(cx, |dock, cx| {
15130                dock.set_open(true, window, cx);
15131                dock.activate_panel(1, window, cx);
15132            });
15133        });
15134
15135        // Now trigger another SettingsStore change
15136        workspace.update_in(cx, |_workspace, _window, cx| {
15137            cx.update_global::<SettingsStore, _>(|_, _| {});
15138        });
15139
15140        workspace.update_in(cx, |workspace, _, cx| {
15141            assert!(
15142                workspace.right_dock().read(cx).is_open(),
15143                "Right dock should still be open after a settings change"
15144            );
15145            assert_eq!(
15146                workspace.right_dock().read(cx).panels_len(),
15147                2,
15148                "Both panels should still be in the right dock"
15149            );
15150        });
15151    }
15152}