workspace.rs

    1pub mod active_file_name;
    2pub mod dock;
    3pub mod history_manager;
    4pub mod invalid_item_view;
    5pub mod item;
    6mod modal_layer;
    7mod multi_workspace;
    8#[cfg(test)]
    9mod multi_workspace_tests;
   10pub mod notifications;
   11pub mod pane;
   12pub mod pane_group;
   13pub mod path_list {
   14    pub use util::path_list::{PathList, SerializedPathList};
   15}
   16mod persistence;
   17pub mod searchable;
   18mod security_modal;
   19pub mod shared_screen;
   20use db::smol::future::yield_now;
   21pub use shared_screen::SharedScreen;
   22pub mod focus_follows_mouse;
   23mod status_bar;
   24pub mod tasks;
   25mod theme_preview;
   26mod toast_layer;
   27mod toolbar;
   28pub mod welcome;
   29mod workspace_settings;
   30
   31pub use crate::notifications::NotificationFrame;
   32pub use dock::Panel;
   33pub use multi_workspace::{
   34    CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MoveProjectToNewWindow,
   35    MultiWorkspace, MultiWorkspaceEvent, NewThread, NextProject, NextThread, PreviousProject,
   36    PreviousThread, ProjectGroup, ProjectGroupKey, SerializedProjectGroupState, Sidebar,
   37    SidebarEvent, SidebarHandle, SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar,
   38    sidebar_side_context_menu,
   39};
   40pub use path_list::{PathList, SerializedPathList};
   41pub use remote::{
   42    RemoteConnectionIdentity, remote_connection_identity, same_remote_connection_identity,
   43};
   44pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   45
   46use anyhow::{Context as _, Result, anyhow};
   47use client::{
   48    ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
   49    proto::{self, ErrorCode, PanelId, PeerId},
   50};
   51use collections::{HashMap, HashSet, hash_map};
   52use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   53use fs::Fs;
   54use futures::{
   55    Future, FutureExt, StreamExt,
   56    channel::{
   57        mpsc::{self, UnboundedReceiver, UnboundedSender},
   58        oneshot,
   59    },
   60    future::{Shared, try_join_all},
   61};
   62use gpui::{
   63    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
   64    Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   65    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   66    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   67    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   68    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   69};
   70pub use history_manager::*;
   71pub use item::{
   72    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   73    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   74};
   75use itertools::Itertools;
   76use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   77pub use modal_layer::*;
   78use node_runtime::NodeRuntime;
   79use notifications::{
   80    DetachAndPromptErr, Notifications, dismiss_app_notification,
   81    simple_message_notification::MessageNotification,
   82};
   83pub use pane::*;
   84pub use pane_group::{
   85    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   86    SplitDirection,
   87};
   88use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
   89pub use persistence::{
   90    WorkspaceDb, delete_unloaded_items,
   91    model::{
   92        DockData, DockStructure, ItemId, MultiWorkspaceState, SerializedMultiWorkspace,
   93        SerializedProjectGroup, SerializedWorkspaceLocation, SessionWorkspace,
   94    },
   95    read_serialized_multi_workspaces, resolve_worktree_workspaces,
   96};
   97use postage::stream::Stream;
   98use project::{
   99    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
  100    WorktreeSettings,
  101    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
  102    project_settings::ProjectSettings,
  103    toolchain_store::ToolchainStoreEvent,
  104    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
  105};
  106use remote::{
  107    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
  108    remote_client::ConnectionIdentifier,
  109};
  110use schemars::JsonSchema;
  111use serde::Deserialize;
  112use session::AppSession;
  113use settings::{
  114    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  115};
  116
  117use sqlez::{
  118    bindable::{Bind, Column, StaticColumnCount},
  119    statement::Statement,
  120};
  121use status_bar::StatusBar;
  122pub use status_bar::StatusItemView;
  123use std::{
  124    any::TypeId,
  125    borrow::Cow,
  126    cell::RefCell,
  127    cmp,
  128    collections::VecDeque,
  129    env,
  130    hash::Hash,
  131    path::{Path, PathBuf},
  132    process::ExitStatus,
  133    rc::Rc,
  134    sync::{
  135        Arc, LazyLock,
  136        atomic::{AtomicBool, AtomicUsize},
  137    },
  138    time::Duration,
  139};
  140use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  141use theme::{ActiveTheme, SystemAppearance};
  142use theme_settings::ThemeSettings;
  143pub use toolbar::{
  144    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  145};
  146pub use ui;
  147use ui::{Window, prelude::*};
  148use util::{
  149    ResultExt, TryFutureExt,
  150    paths::{PathStyle, SanitizedPath},
  151    rel_path::RelPath,
  152    serde::default_true,
  153};
  154use uuid::Uuid;
  155pub use workspace_settings::{
  156    AutosaveSetting, BottomDockLayout, FocusFollowsMouse, RestoreOnStartupBehavior,
  157    StatusBarSettings, TabBarSettings, WorkspaceSettings,
  158};
  159use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
  160
  161use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::NotificationId};
  162use crate::{
  163    persistence::{
  164        SerializedAxis,
  165        model::{SerializedItem, SerializedPane, SerializedPaneGroup},
  166    },
  167    security_modal::SecurityModal,
  168};
  169
  170pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  171
  172static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  173    env::var("ZED_WINDOW_SIZE")
  174        .ok()
  175        .as_deref()
  176        .and_then(parse_pixel_size_env_var)
  177});
  178
  179static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  180    env::var("ZED_WINDOW_POSITION")
  181        .ok()
  182        .as_deref()
  183        .and_then(parse_pixel_position_env_var)
  184});
  185
  186pub trait TerminalProvider {
  187    fn spawn(
  188        &self,
  189        task: SpawnInTerminal,
  190        window: &mut Window,
  191        cx: &mut App,
  192    ) -> Task<Option<Result<ExitStatus>>>;
  193}
  194
  195pub trait DebuggerProvider {
  196    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  197    fn start_session(
  198        &self,
  199        definition: DebugScenario,
  200        task_context: SharedTaskContext,
  201        active_buffer: Option<Entity<Buffer>>,
  202        worktree_id: Option<WorktreeId>,
  203        window: &mut Window,
  204        cx: &mut App,
  205    );
  206
  207    fn spawn_task_or_modal(
  208        &self,
  209        workspace: &mut Workspace,
  210        action: &Spawn,
  211        window: &mut Window,
  212        cx: &mut Context<Workspace>,
  213    );
  214
  215    fn task_scheduled(&self, cx: &mut App);
  216    fn debug_scenario_scheduled(&self, cx: &mut App);
  217    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  218
  219    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  220}
  221
  222/// Opens a file or directory.
  223#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  224#[action(namespace = workspace)]
  225pub struct Open {
  226    /// When true, opens in a new window. When false, adds to the current
  227    /// window as a new workspace (multi-workspace).
  228    #[serde(default = "Open::default_create_new_window")]
  229    pub create_new_window: bool,
  230}
  231
  232impl Open {
  233    pub const DEFAULT: Self = Self {
  234        create_new_window: false,
  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 bookmarks in the project.
  266        ClearBookmarks,
  267        /// Clears all notifications.
  268        ClearAllNotifications,
  269        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  270        ClearNavigationHistory,
  271        /// Closes the active dock.
  272        CloseActiveDock,
  273        /// Closes all docks.
  274        CloseAllDocks,
  275        /// Toggles all docks.
  276        ToggleAllDocks,
  277        /// Closes the current window.
  278        CloseWindow,
  279        /// Closes the current project.
  280        CloseProject,
  281        /// Opens the feedback dialog.
  282        Feedback,
  283        /// Follows the next collaborator in the session.
  284        FollowNextCollaborator,
  285        /// Moves the focused panel to the next position.
  286        MoveFocusedPanelToNextPosition,
  287        /// Creates a new file.
  288        NewFile,
  289        /// Creates a new file in a vertical split.
  290        NewFileSplitVertical,
  291        /// Creates a new file in a horizontal split.
  292        NewFileSplitHorizontal,
  293        /// Opens a new search.
  294        NewSearch,
  295        /// Opens a new window.
  296        NewWindow,
  297        /// Opens multiple files.
  298        OpenFiles,
  299        /// Opens the current location in terminal.
  300        OpenInTerminal,
  301        /// Opens the component preview.
  302        OpenComponentPreview,
  303        /// Reloads the active item.
  304        ReloadActiveItem,
  305        /// Resets the active dock to its default size.
  306        ResetActiveDockSize,
  307        /// Resets all open docks to their default sizes.
  308        ResetOpenDocksSize,
  309        /// Reloads the application
  310        Reload,
  311        /// Formats and saves the current file, regardless of the format_on_save setting.
  312        FormatAndSave,
  313        /// Saves the current file with a new name.
  314        SaveAs,
  315        /// Saves without formatting.
  316        SaveWithoutFormat,
  317        /// Shuts down all debug adapters.
  318        ShutdownDebugAdapters,
  319        /// Suppresses the current notification.
  320        SuppressNotification,
  321        /// Toggles the bottom dock.
  322        ToggleBottomDock,
  323        /// Toggles centered layout mode.
  324        ToggleCenteredLayout,
  325        /// Toggles edit prediction feature globally for all files.
  326        ToggleEditPrediction,
  327        /// Toggles the left dock.
  328        ToggleLeftDock,
  329        /// Toggles the right dock.
  330        ToggleRightDock,
  331        /// Toggles zoom on the active pane.
  332        ToggleZoom,
  333        /// Toggles read-only mode for the active item (if supported by that item).
  334        ToggleReadOnlyFile,
  335        /// Zooms in on the active pane.
  336        ZoomIn,
  337        /// Zooms out of the active pane.
  338        ZoomOut,
  339        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  340        /// If the modal is shown already, closes it without trusting any worktree.
  341        ToggleWorktreeSecurity,
  342        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  343        /// Requires restart to take effect on already opened projects.
  344        ClearTrustedWorktrees,
  345        /// Stops following a collaborator.
  346        Unfollow,
  347        /// Restores the banner.
  348        RestoreBanner,
  349        /// Toggles expansion of the selected item.
  350        ToggleExpandItem,
  351    ]
  352);
  353
  354/// Activates a specific pane by its index.
  355#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  356#[action(namespace = workspace)]
  357pub struct ActivatePane(pub usize);
  358
  359/// Moves an item to a specific pane by index.
  360#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  361#[action(namespace = workspace)]
  362#[serde(deny_unknown_fields)]
  363pub struct MoveItemToPane {
  364    #[serde(default = "default_1")]
  365    pub destination: usize,
  366    #[serde(default = "default_true")]
  367    pub focus: bool,
  368    #[serde(default)]
  369    pub clone: bool,
  370}
  371
  372fn default_1() -> usize {
  373    1
  374}
  375
  376/// Moves an item to a pane in the specified direction.
  377#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  378#[action(namespace = workspace)]
  379#[serde(deny_unknown_fields)]
  380pub struct MoveItemToPaneInDirection {
  381    #[serde(default = "default_right")]
  382    pub direction: SplitDirection,
  383    #[serde(default = "default_true")]
  384    pub focus: bool,
  385    #[serde(default)]
  386    pub clone: bool,
  387}
  388
  389/// Creates a new file in a split of the desired direction.
  390#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  391#[action(namespace = workspace)]
  392#[serde(deny_unknown_fields)]
  393pub struct NewFileSplit(pub SplitDirection);
  394
  395fn default_right() -> SplitDirection {
  396    SplitDirection::Right
  397}
  398
  399/// Saves all open files in the workspace.
  400#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  401#[action(namespace = workspace)]
  402#[serde(deny_unknown_fields)]
  403pub struct SaveAll {
  404    #[serde(default)]
  405    pub save_intent: Option<SaveIntent>,
  406}
  407
  408/// Saves the current file with the specified options.
  409#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  410#[action(namespace = workspace)]
  411#[serde(deny_unknown_fields)]
  412pub struct Save {
  413    #[serde(default)]
  414    pub save_intent: Option<SaveIntent>,
  415}
  416
  417/// Moves Focus to the central panes in the workspace.
  418#[derive(Clone, Debug, PartialEq, Eq, Action)]
  419#[action(namespace = workspace)]
  420pub struct FocusCenterPane;
  421
  422///  Closes all items and panes in the workspace.
  423#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  424#[action(namespace = workspace)]
  425#[serde(deny_unknown_fields)]
  426pub struct CloseAllItemsAndPanes {
  427    #[serde(default)]
  428    pub save_intent: Option<SaveIntent>,
  429}
  430
  431/// Closes all inactive tabs and panes in the workspace.
  432#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  433#[action(namespace = workspace)]
  434#[serde(deny_unknown_fields)]
  435pub struct CloseInactiveTabsAndPanes {
  436    #[serde(default)]
  437    pub save_intent: Option<SaveIntent>,
  438}
  439
  440/// Closes the active item across all panes.
  441#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  442#[action(namespace = workspace)]
  443#[serde(deny_unknown_fields)]
  444pub struct CloseItemInAllPanes {
  445    #[serde(default)]
  446    pub save_intent: Option<SaveIntent>,
  447    #[serde(default)]
  448    pub close_pinned: bool,
  449}
  450
  451/// Sends a sequence of keystrokes to the active element.
  452#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  453#[action(namespace = workspace)]
  454pub struct SendKeystrokes(pub String);
  455
  456actions!(
  457    project_symbols,
  458    [
  459        /// Toggles the project symbols search.
  460        #[action(name = "Toggle")]
  461        ToggleProjectSymbols
  462    ]
  463);
  464
  465/// Toggles the file finder interface.
  466#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  467#[action(namespace = file_finder, name = "Toggle")]
  468#[serde(deny_unknown_fields)]
  469pub struct ToggleFileFinder {
  470    #[serde(default)]
  471    pub separate_history: bool,
  472}
  473
  474/// Opens a new terminal in the center.
  475#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  476#[action(namespace = workspace)]
  477#[serde(deny_unknown_fields)]
  478pub struct NewCenterTerminal {
  479    /// If true, creates a local terminal even in remote projects.
  480    #[serde(default)]
  481    pub local: bool,
  482}
  483
  484/// Opens a new terminal.
  485#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  486#[action(namespace = workspace)]
  487#[serde(deny_unknown_fields)]
  488pub struct NewTerminal {
  489    /// If true, creates a local terminal even in remote projects.
  490    #[serde(default)]
  491    pub local: bool,
  492}
  493
  494/// Increases size of a currently focused dock by a given amount of pixels.
  495#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  496#[action(namespace = workspace)]
  497#[serde(deny_unknown_fields)]
  498pub struct IncreaseActiveDockSize {
  499    /// For 0px parameter, uses UI font size value.
  500    #[serde(default)]
  501    pub px: u32,
  502}
  503
  504/// Decreases size of a currently focused dock by a given amount of pixels.
  505#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  506#[action(namespace = workspace)]
  507#[serde(deny_unknown_fields)]
  508pub struct DecreaseActiveDockSize {
  509    /// For 0px parameter, uses UI font size value.
  510    #[serde(default)]
  511    pub px: u32,
  512}
  513
  514/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  515#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  516#[action(namespace = workspace)]
  517#[serde(deny_unknown_fields)]
  518pub struct IncreaseOpenDocksSize {
  519    /// For 0px parameter, uses UI font size value.
  520    #[serde(default)]
  521    pub px: u32,
  522}
  523
  524/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  525#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  526#[action(namespace = workspace)]
  527#[serde(deny_unknown_fields)]
  528pub struct DecreaseOpenDocksSize {
  529    /// For 0px parameter, uses UI font size value.
  530    #[serde(default)]
  531    pub px: u32,
  532}
  533
  534actions!(
  535    workspace,
  536    [
  537        /// Activates the pane to the left.
  538        ActivatePaneLeft,
  539        /// Activates the pane to the right.
  540        ActivatePaneRight,
  541        /// Activates the pane above.
  542        ActivatePaneUp,
  543        /// Activates the pane below.
  544        ActivatePaneDown,
  545        /// Swaps the current pane with the one to the left.
  546        SwapPaneLeft,
  547        /// Swaps the current pane with the one to the right.
  548        SwapPaneRight,
  549        /// Swaps the current pane with the one above.
  550        SwapPaneUp,
  551        /// Swaps the current pane with the one below.
  552        SwapPaneDown,
  553        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  554        SwapPaneAdjacent,
  555        /// Move the current pane to be at the far left.
  556        MovePaneLeft,
  557        /// Move the current pane to be at the far right.
  558        MovePaneRight,
  559        /// Move the current pane to be at the very top.
  560        MovePaneUp,
  561        /// Move the current pane to be at the very bottom.
  562        MovePaneDown,
  563    ]
  564);
  565
  566#[derive(PartialEq, Eq, Debug)]
  567pub enum CloseIntent {
  568    /// Quit the program entirely.
  569    Quit,
  570    /// Close a window.
  571    CloseWindow,
  572    /// Replace the workspace in an existing window.
  573    ReplaceWindow,
  574}
  575
  576#[derive(Clone)]
  577pub struct Toast {
  578    id: NotificationId,
  579    msg: Cow<'static, str>,
  580    autohide: bool,
  581    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  582}
  583
  584impl Toast {
  585    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  586        Toast {
  587            id,
  588            msg: msg.into(),
  589            on_click: None,
  590            autohide: false,
  591        }
  592    }
  593
  594    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  595    where
  596        M: Into<Cow<'static, str>>,
  597        F: Fn(&mut Window, &mut App) + 'static,
  598    {
  599        self.on_click = Some((message.into(), Arc::new(on_click)));
  600        self
  601    }
  602
  603    pub fn autohide(mut self) -> Self {
  604        self.autohide = true;
  605        self
  606    }
  607}
  608
  609impl PartialEq for Toast {
  610    fn eq(&self, other: &Self) -> bool {
  611        self.id == other.id
  612            && self.msg == other.msg
  613            && self.on_click.is_some() == other.on_click.is_some()
  614    }
  615}
  616
  617/// Opens a new terminal with the specified working directory.
  618#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  619#[action(namespace = workspace)]
  620#[serde(deny_unknown_fields)]
  621pub struct OpenTerminal {
  622    pub working_directory: PathBuf,
  623    /// If true, creates a local terminal even in remote projects.
  624    #[serde(default)]
  625    pub local: bool,
  626}
  627
  628#[derive(
  629    Clone,
  630    Copy,
  631    Debug,
  632    Default,
  633    Hash,
  634    PartialEq,
  635    Eq,
  636    PartialOrd,
  637    Ord,
  638    serde::Serialize,
  639    serde::Deserialize,
  640)]
  641pub struct WorkspaceId(i64);
  642
  643impl WorkspaceId {
  644    pub fn from_i64(value: i64) -> Self {
  645        Self(value)
  646    }
  647}
  648
  649impl StaticColumnCount for WorkspaceId {}
  650impl Bind for WorkspaceId {
  651    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  652        self.0.bind(statement, start_index)
  653    }
  654}
  655impl Column for WorkspaceId {
  656    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  657        i64::column(statement, start_index)
  658            .map(|(i, next_index)| (Self(i), next_index))
  659            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  660    }
  661}
  662impl From<WorkspaceId> for i64 {
  663    fn from(val: WorkspaceId) -> Self {
  664        val.0
  665    }
  666}
  667
  668fn prompt_and_open_paths(
  669    app_state: Arc<AppState>,
  670    options: PathPromptOptions,
  671    create_new_window: bool,
  672    cx: &mut App,
  673) {
  674    if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
  675        workspace_window
  676            .update(cx, |multi_workspace, window, cx| {
  677                let workspace = multi_workspace.workspace().clone();
  678                workspace.update(cx, |workspace, cx| {
  679                    prompt_for_open_path_and_open(
  680                        workspace,
  681                        app_state,
  682                        options,
  683                        create_new_window,
  684                        window,
  685                        cx,
  686                    );
  687                });
  688            })
  689            .ok();
  690    } else {
  691        let task = Workspace::new_local(
  692            Vec::new(),
  693            app_state.clone(),
  694            None,
  695            None,
  696            None,
  697            OpenMode::Activate,
  698            cx,
  699        );
  700        cx.spawn(async move |cx| {
  701            let OpenResult { window, .. } = task.await?;
  702            window.update(cx, |multi_workspace, window, cx| {
  703                window.activate_window();
  704                let workspace = multi_workspace.workspace().clone();
  705                workspace.update(cx, |workspace, cx| {
  706                    prompt_for_open_path_and_open(
  707                        workspace,
  708                        app_state,
  709                        options,
  710                        create_new_window,
  711                        window,
  712                        cx,
  713                    );
  714                });
  715            })?;
  716            anyhow::Ok(())
  717        })
  718        .detach_and_log_err(cx);
  719    }
  720}
  721
  722pub fn prompt_for_open_path_and_open(
  723    workspace: &mut Workspace,
  724    app_state: Arc<AppState>,
  725    options: PathPromptOptions,
  726    create_new_window: bool,
  727    window: &mut Window,
  728    cx: &mut Context<Workspace>,
  729) {
  730    let paths = workspace.prompt_for_open_path(
  731        options,
  732        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  733        window,
  734        cx,
  735    );
  736    let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
  737    cx.spawn_in(window, async move |this, cx| {
  738        let Some(paths) = paths.await.log_err().flatten() else {
  739            return;
  740        };
  741        if !create_new_window {
  742            if let Some(handle) = multi_workspace_handle {
  743                if let Some(task) = handle
  744                    .update(cx, |multi_workspace, window, cx| {
  745                        multi_workspace.open_project(paths, OpenMode::Activate, window, cx)
  746                    })
  747                    .log_err()
  748                {
  749                    task.await.log_err();
  750                }
  751                return;
  752            }
  753        }
  754        if let Some(task) = this
  755            .update_in(cx, |this, window, cx| {
  756                this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
  757            })
  758            .log_err()
  759        {
  760            task.await.log_err();
  761        }
  762    })
  763    .detach();
  764}
  765
  766pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  767    component::init();
  768    theme_preview::init(cx);
  769    toast_layer::init(cx);
  770    history_manager::init(app_state.fs.clone(), cx);
  771
  772    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  773        .on_action(|_: &Reload, cx| reload(cx))
  774        .on_action(|action: &Open, cx: &mut App| {
  775            let app_state = AppState::global(cx);
  776            prompt_and_open_paths(
  777                app_state,
  778                PathPromptOptions {
  779                    files: true,
  780                    directories: true,
  781                    multiple: true,
  782                    prompt: None,
  783                },
  784                action.create_new_window,
  785                cx,
  786            );
  787        })
  788        .on_action(|_: &OpenFiles, cx: &mut App| {
  789            let directories = cx.can_select_mixed_files_and_dirs();
  790            let app_state = AppState::global(cx);
  791            prompt_and_open_paths(
  792                app_state,
  793                PathPromptOptions {
  794                    files: true,
  795                    directories,
  796                    multiple: true,
  797                    prompt: None,
  798                },
  799                true,
  800                cx,
  801            );
  802        });
  803}
  804
  805type BuildProjectItemFn =
  806    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  807
  808type BuildProjectItemForPathFn =
  809    fn(
  810        &Entity<Project>,
  811        &ProjectPath,
  812        &mut Window,
  813        &mut App,
  814    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  815
  816#[derive(Clone, Default)]
  817struct ProjectItemRegistry {
  818    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  819    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  820}
  821
  822impl ProjectItemRegistry {
  823    fn register<T: ProjectItem>(&mut self) {
  824        self.build_project_item_fns_by_type.insert(
  825            TypeId::of::<T::Item>(),
  826            |item, project, pane, window, cx| {
  827                let item = item.downcast().unwrap();
  828                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  829                    as Box<dyn ItemHandle>
  830            },
  831        );
  832        self.build_project_item_for_path_fns
  833            .push(|project, project_path, window, cx| {
  834                let project_path = project_path.clone();
  835                let is_file = project
  836                    .read(cx)
  837                    .entry_for_path(&project_path, cx)
  838                    .is_some_and(|entry| entry.is_file());
  839                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  840                let is_local = project.read(cx).is_local();
  841                let project_item =
  842                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  843                let project = project.clone();
  844                Some(window.spawn(cx, async move |cx| {
  845                    match project_item.await.with_context(|| {
  846                        format!(
  847                            "opening project path {:?}",
  848                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  849                        )
  850                    }) {
  851                        Ok(project_item) => {
  852                            let project_item = project_item;
  853                            let project_entry_id: Option<ProjectEntryId> =
  854                                project_item.read_with(cx, project::ProjectItem::entry_id);
  855                            let build_workspace_item = Box::new(
  856                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  857                                    Box::new(cx.new(|cx| {
  858                                        T::for_project_item(
  859                                            project,
  860                                            Some(pane),
  861                                            project_item,
  862                                            window,
  863                                            cx,
  864                                        )
  865                                    })) as Box<dyn ItemHandle>
  866                                },
  867                            ) as Box<_>;
  868                            Ok((project_entry_id, build_workspace_item))
  869                        }
  870                        Err(e) => {
  871                            log::warn!("Failed to open a project item: {e:#}");
  872                            if e.error_code() == ErrorCode::Internal {
  873                                if let Some(abs_path) =
  874                                    entry_abs_path.as_deref().filter(|_| is_file)
  875                                {
  876                                    if let Some(broken_project_item_view) =
  877                                        cx.update(|window, cx| {
  878                                            T::for_broken_project_item(
  879                                                abs_path, is_local, &e, window, cx,
  880                                            )
  881                                        })?
  882                                    {
  883                                        let build_workspace_item = Box::new(
  884                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  885                                                cx.new(|_| broken_project_item_view).boxed_clone()
  886                                            },
  887                                        )
  888                                        as Box<_>;
  889                                        return Ok((None, build_workspace_item));
  890                                    }
  891                                }
  892                            }
  893                            Err(e)
  894                        }
  895                    }
  896                }))
  897            });
  898    }
  899
  900    fn open_path(
  901        &self,
  902        project: &Entity<Project>,
  903        path: &ProjectPath,
  904        window: &mut Window,
  905        cx: &mut App,
  906    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  907        let Some(open_project_item) = self
  908            .build_project_item_for_path_fns
  909            .iter()
  910            .rev()
  911            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  912        else {
  913            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  914        };
  915        open_project_item
  916    }
  917
  918    fn build_item<T: project::ProjectItem>(
  919        &self,
  920        item: Entity<T>,
  921        project: Entity<Project>,
  922        pane: Option<&Pane>,
  923        window: &mut Window,
  924        cx: &mut App,
  925    ) -> Option<Box<dyn ItemHandle>> {
  926        let build = self
  927            .build_project_item_fns_by_type
  928            .get(&TypeId::of::<T>())?;
  929        Some(build(item.into_any(), project, pane, window, cx))
  930    }
  931}
  932
  933type WorkspaceItemBuilder =
  934    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  935
  936impl Global for ProjectItemRegistry {}
  937
  938/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  939/// items will get a chance to open the file, starting from the project item that
  940/// was added last.
  941pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  942    cx.default_global::<ProjectItemRegistry>().register::<I>();
  943}
  944
  945#[derive(Default)]
  946pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  947
  948struct FollowableViewDescriptor {
  949    from_state_proto: fn(
  950        Entity<Workspace>,
  951        ViewId,
  952        &mut Option<proto::view::Variant>,
  953        &mut Window,
  954        &mut App,
  955    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  956    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  957}
  958
  959impl Global for FollowableViewRegistry {}
  960
  961impl FollowableViewRegistry {
  962    pub fn register<I: FollowableItem>(cx: &mut App) {
  963        cx.default_global::<Self>().0.insert(
  964            TypeId::of::<I>(),
  965            FollowableViewDescriptor {
  966                from_state_proto: |workspace, id, state, window, cx| {
  967                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  968                        cx.foreground_executor()
  969                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  970                    })
  971                },
  972                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  973            },
  974        );
  975    }
  976
  977    pub fn from_state_proto(
  978        workspace: Entity<Workspace>,
  979        view_id: ViewId,
  980        mut state: Option<proto::view::Variant>,
  981        window: &mut Window,
  982        cx: &mut App,
  983    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  984        cx.update_default_global(|this: &mut Self, cx| {
  985            this.0.values().find_map(|descriptor| {
  986                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  987            })
  988        })
  989    }
  990
  991    pub fn to_followable_view(
  992        view: impl Into<AnyView>,
  993        cx: &App,
  994    ) -> Option<Box<dyn FollowableItemHandle>> {
  995        let this = cx.try_global::<Self>()?;
  996        let view = view.into();
  997        let descriptor = this.0.get(&view.entity_type())?;
  998        Some((descriptor.to_followable_view)(&view))
  999    }
 1000}
 1001
 1002#[derive(Copy, Clone)]
 1003struct SerializableItemDescriptor {
 1004    deserialize: fn(
 1005        Entity<Project>,
 1006        WeakEntity<Workspace>,
 1007        WorkspaceId,
 1008        ItemId,
 1009        &mut Window,
 1010        &mut Context<Pane>,
 1011    ) -> Task<Result<Box<dyn ItemHandle>>>,
 1012    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
 1013    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
 1014}
 1015
 1016#[derive(Default)]
 1017struct SerializableItemRegistry {
 1018    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
 1019    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
 1020}
 1021
 1022impl Global for SerializableItemRegistry {}
 1023
 1024impl SerializableItemRegistry {
 1025    fn deserialize(
 1026        item_kind: &str,
 1027        project: Entity<Project>,
 1028        workspace: WeakEntity<Workspace>,
 1029        workspace_id: WorkspaceId,
 1030        item_item: ItemId,
 1031        window: &mut Window,
 1032        cx: &mut Context<Pane>,
 1033    ) -> Task<Result<Box<dyn ItemHandle>>> {
 1034        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1035            return Task::ready(Err(anyhow!(
 1036                "cannot deserialize {}, descriptor not found",
 1037                item_kind
 1038            )));
 1039        };
 1040
 1041        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
 1042    }
 1043
 1044    fn cleanup(
 1045        item_kind: &str,
 1046        workspace_id: WorkspaceId,
 1047        loaded_items: Vec<ItemId>,
 1048        window: &mut Window,
 1049        cx: &mut App,
 1050    ) -> Task<Result<()>> {
 1051        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1052            return Task::ready(Err(anyhow!(
 1053                "cannot cleanup {}, descriptor not found",
 1054                item_kind
 1055            )));
 1056        };
 1057
 1058        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
 1059    }
 1060
 1061    fn view_to_serializable_item_handle(
 1062        view: AnyView,
 1063        cx: &App,
 1064    ) -> Option<Box<dyn SerializableItemHandle>> {
 1065        let this = cx.try_global::<Self>()?;
 1066        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
 1067        Some((descriptor.view_to_serializable_item)(view))
 1068    }
 1069
 1070    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
 1071        let this = cx.try_global::<Self>()?;
 1072        this.descriptors_by_kind.get(item_kind).copied()
 1073    }
 1074}
 1075
 1076pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
 1077    let serialized_item_kind = I::serialized_item_kind();
 1078
 1079    let registry = cx.default_global::<SerializableItemRegistry>();
 1080    let descriptor = SerializableItemDescriptor {
 1081        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
 1082            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
 1083            cx.foreground_executor()
 1084                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 1085        },
 1086        cleanup: |workspace_id, loaded_items, window, cx| {
 1087            I::cleanup(workspace_id, loaded_items, window, cx)
 1088        },
 1089        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1090    };
 1091    registry
 1092        .descriptors_by_kind
 1093        .insert(Arc::from(serialized_item_kind), descriptor);
 1094    registry
 1095        .descriptors_by_type
 1096        .insert(TypeId::of::<I>(), descriptor);
 1097}
 1098
 1099pub struct AppState {
 1100    pub languages: Arc<LanguageRegistry>,
 1101    pub client: Arc<Client>,
 1102    pub user_store: Entity<UserStore>,
 1103    pub workspace_store: Entity<WorkspaceStore>,
 1104    pub fs: Arc<dyn fs::Fs>,
 1105    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1106    pub node_runtime: NodeRuntime,
 1107    pub session: Entity<AppSession>,
 1108}
 1109
 1110struct GlobalAppState(Arc<AppState>);
 1111
 1112impl Global for GlobalAppState {}
 1113
 1114/// Tracks worktree creation progress for the workspace.
 1115/// Read by the title bar to show a loading indicator on the worktree button.
 1116#[derive(Default)]
 1117pub struct ActiveWorktreeCreation {
 1118    pub label: Option<SharedString>,
 1119    pub is_switch: bool,
 1120}
 1121
 1122/// Captured workspace state used when switching between worktrees.
 1123/// Stores the layout and open files so they can be restored in the new workspace.
 1124pub struct PreviousWorkspaceState {
 1125    pub dock_structure: DockStructure,
 1126    pub open_file_paths: Vec<PathBuf>,
 1127    pub active_file_path: Option<PathBuf>,
 1128    pub focused_dock: Option<DockPosition>,
 1129}
 1130
 1131pub struct WorkspaceStore {
 1132    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1133    client: Arc<Client>,
 1134    _subscriptions: Vec<client::Subscription>,
 1135}
 1136
 1137#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1138pub enum CollaboratorId {
 1139    PeerId(PeerId),
 1140    Agent,
 1141}
 1142
 1143impl From<PeerId> for CollaboratorId {
 1144    fn from(peer_id: PeerId) -> Self {
 1145        CollaboratorId::PeerId(peer_id)
 1146    }
 1147}
 1148
 1149impl From<&PeerId> for CollaboratorId {
 1150    fn from(peer_id: &PeerId) -> Self {
 1151        CollaboratorId::PeerId(*peer_id)
 1152    }
 1153}
 1154
 1155#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1156struct Follower {
 1157    project_id: Option<u64>,
 1158    peer_id: PeerId,
 1159}
 1160
 1161impl AppState {
 1162    #[track_caller]
 1163    pub fn global(cx: &App) -> Arc<Self> {
 1164        cx.global::<GlobalAppState>().0.clone()
 1165    }
 1166    pub fn try_global(cx: &App) -> Option<Arc<Self>> {
 1167        cx.try_global::<GlobalAppState>()
 1168            .map(|state| state.0.clone())
 1169    }
 1170    pub fn set_global(state: Arc<AppState>, cx: &mut App) {
 1171        cx.set_global(GlobalAppState(state));
 1172    }
 1173
 1174    #[cfg(any(test, feature = "test-support"))]
 1175    pub fn test(cx: &mut App) -> Arc<Self> {
 1176        use fs::Fs;
 1177        use node_runtime::NodeRuntime;
 1178        use session::Session;
 1179        use settings::SettingsStore;
 1180
 1181        if !cx.has_global::<SettingsStore>() {
 1182            let settings_store = SettingsStore::test(cx);
 1183            cx.set_global(settings_store);
 1184        }
 1185
 1186        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1187        <dyn Fs>::set_global(fs.clone(), cx);
 1188        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1189        let clock = Arc::new(clock::FakeSystemClock::new());
 1190        let http_client = http_client::FakeHttpClient::with_404_response();
 1191        let client = Client::new(clock, http_client, cx);
 1192        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1193        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1194        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1195
 1196        theme_settings::init(theme::LoadThemes::JustBase, cx);
 1197        client::init(&client, cx);
 1198
 1199        Arc::new(Self {
 1200            client,
 1201            fs,
 1202            languages,
 1203            user_store,
 1204            workspace_store,
 1205            node_runtime: NodeRuntime::unavailable(),
 1206            build_window_options: |_, _| Default::default(),
 1207            session,
 1208        })
 1209    }
 1210}
 1211
 1212struct DelayedDebouncedEditAction {
 1213    task: Option<Task<()>>,
 1214    cancel_channel: Option<oneshot::Sender<()>>,
 1215}
 1216
 1217impl DelayedDebouncedEditAction {
 1218    fn new() -> DelayedDebouncedEditAction {
 1219        DelayedDebouncedEditAction {
 1220            task: None,
 1221            cancel_channel: None,
 1222        }
 1223    }
 1224
 1225    fn fire_new<F>(
 1226        &mut self,
 1227        delay: Duration,
 1228        window: &mut Window,
 1229        cx: &mut Context<Workspace>,
 1230        func: F,
 1231    ) where
 1232        F: 'static
 1233            + Send
 1234            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1235    {
 1236        if let Some(channel) = self.cancel_channel.take() {
 1237            _ = channel.send(());
 1238        }
 1239
 1240        let (sender, mut receiver) = oneshot::channel::<()>();
 1241        self.cancel_channel = Some(sender);
 1242
 1243        let previous_task = self.task.take();
 1244        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1245            let mut timer = cx.background_executor().timer(delay).fuse();
 1246            if let Some(previous_task) = previous_task {
 1247                previous_task.await;
 1248            }
 1249
 1250            futures::select_biased! {
 1251                _ = receiver => return,
 1252                    _ = timer => {}
 1253            }
 1254
 1255            if let Some(result) = workspace
 1256                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1257                .log_err()
 1258            {
 1259                result.await.log_err();
 1260            }
 1261        }));
 1262    }
 1263}
 1264
 1265pub enum Event {
 1266    PaneAdded(Entity<Pane>),
 1267    PaneRemoved,
 1268    ItemAdded {
 1269        item: Box<dyn ItemHandle>,
 1270    },
 1271    ActiveItemChanged,
 1272    ItemRemoved {
 1273        item_id: EntityId,
 1274    },
 1275    UserSavedItem {
 1276        pane: WeakEntity<Pane>,
 1277        item: Box<dyn WeakItemHandle>,
 1278        save_intent: SaveIntent,
 1279    },
 1280    ContactRequestedJoin(u64),
 1281    WorkspaceCreated(WeakEntity<Workspace>),
 1282    OpenBundledFile {
 1283        text: Cow<'static, str>,
 1284        title: &'static str,
 1285        language: &'static str,
 1286    },
 1287    ZoomChanged,
 1288    ModalOpened,
 1289    Activate,
 1290    PanelAdded(AnyView),
 1291    WorktreeCreationChanged,
 1292}
 1293
 1294#[derive(Debug, Clone)]
 1295pub enum OpenVisible {
 1296    All,
 1297    None,
 1298    OnlyFiles,
 1299    OnlyDirectories,
 1300}
 1301
 1302enum WorkspaceLocation {
 1303    // Valid local paths or SSH project to serialize
 1304    Location(SerializedWorkspaceLocation, PathList),
 1305    // No valid location found hence clear session id
 1306    DetachFromSession,
 1307    // No valid location found to serialize
 1308    None,
 1309}
 1310
 1311type PromptForNewPath = Box<
 1312    dyn Fn(
 1313        &mut Workspace,
 1314        DirectoryLister,
 1315        Option<String>,
 1316        &mut Window,
 1317        &mut Context<Workspace>,
 1318    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1319>;
 1320
 1321type PromptForOpenPath = Box<
 1322    dyn Fn(
 1323        &mut Workspace,
 1324        DirectoryLister,
 1325        &mut Window,
 1326        &mut Context<Workspace>,
 1327    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1328>;
 1329
 1330#[derive(Default)]
 1331struct DispatchingKeystrokes {
 1332    dispatched: HashSet<Vec<Keystroke>>,
 1333    queue: VecDeque<Keystroke>,
 1334    task: Option<Shared<Task<()>>>,
 1335}
 1336
 1337/// Collects everything project-related for a certain window opened.
 1338/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1339///
 1340/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1341/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1342/// that can be used to register a global action to be triggered from any place in the window.
 1343pub struct Workspace {
 1344    weak_self: WeakEntity<Self>,
 1345    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1346    zoomed: Option<AnyWeakView>,
 1347    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1348    zoomed_position: Option<DockPosition>,
 1349    center: PaneGroup,
 1350    left_dock: Entity<Dock>,
 1351    bottom_dock: Entity<Dock>,
 1352    right_dock: Entity<Dock>,
 1353    panes: Vec<Entity<Pane>>,
 1354    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1355    active_pane: Entity<Pane>,
 1356    last_active_center_pane: Option<WeakEntity<Pane>>,
 1357    last_active_view_id: Option<proto::ViewId>,
 1358    status_bar: Entity<StatusBar>,
 1359    pub(crate) modal_layer: Entity<ModalLayer>,
 1360    toast_layer: Entity<ToastLayer>,
 1361    titlebar_item: Option<AnyView>,
 1362    notifications: Notifications,
 1363    suppressed_notifications: HashSet<NotificationId>,
 1364    project: Entity<Project>,
 1365    follower_states: HashMap<CollaboratorId, FollowerState>,
 1366    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1367    window_edited: bool,
 1368    last_window_title: Option<String>,
 1369    dirty_items: HashMap<EntityId, Subscription>,
 1370    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1371    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1372    database_id: Option<WorkspaceId>,
 1373    app_state: Arc<AppState>,
 1374    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1375    _subscriptions: Vec<Subscription>,
 1376    _apply_leader_updates: Task<Result<()>>,
 1377    _observe_current_user: Task<Result<()>>,
 1378    _schedule_serialize_workspace: Option<Task<()>>,
 1379    _serialize_workspace_task: Option<Task<()>>,
 1380    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1381    pane_history_timestamp: Arc<AtomicUsize>,
 1382    bounds: Bounds<Pixels>,
 1383    pub centered_layout: bool,
 1384    bounds_save_task_queued: Option<Task<()>>,
 1385    on_prompt_for_new_path: Option<PromptForNewPath>,
 1386    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1387    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1388    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1389    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1390    _items_serializer: Task<Result<()>>,
 1391    session_id: Option<String>,
 1392    scheduled_tasks: Vec<Task<()>>,
 1393    last_open_dock_positions: Vec<DockPosition>,
 1394    removing: bool,
 1395    open_in_dev_container: bool,
 1396    _dev_container_task: Option<Task<Result<()>>>,
 1397    _panels_task: Option<Task<Result<()>>>,
 1398    sidebar_focus_handle: Option<FocusHandle>,
 1399    multi_workspace: Option<WeakEntity<MultiWorkspace>>,
 1400    active_worktree_creation: ActiveWorktreeCreation,
 1401}
 1402
 1403impl EventEmitter<Event> for Workspace {}
 1404
 1405#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1406pub struct ViewId {
 1407    pub creator: CollaboratorId,
 1408    pub id: u64,
 1409}
 1410
 1411pub struct FollowerState {
 1412    center_pane: Entity<Pane>,
 1413    dock_pane: Option<Entity<Pane>>,
 1414    active_view_id: Option<ViewId>,
 1415    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1416}
 1417
 1418struct FollowerView {
 1419    view: Box<dyn FollowableItemHandle>,
 1420    location: Option<proto::PanelId>,
 1421}
 1422
 1423#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
 1424pub enum OpenMode {
 1425    /// Open the workspace in a new window.
 1426    NewWindow,
 1427    /// Add to the window's multi workspace without activating it (used during deserialization).
 1428    Add,
 1429    /// Add to the window's multi workspace and activate it.
 1430    #[default]
 1431    Activate,
 1432}
 1433
 1434impl Workspace {
 1435    pub fn new(
 1436        workspace_id: Option<WorkspaceId>,
 1437        project: Entity<Project>,
 1438        app_state: Arc<AppState>,
 1439        window: &mut Window,
 1440        cx: &mut Context<Self>,
 1441    ) -> Self {
 1442        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1443            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1444                if let TrustedWorktreesEvent::Trusted(..) = e {
 1445                    // Do not persist auto trusted worktrees
 1446                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1447                        worktrees_store.update(cx, |worktrees_store, cx| {
 1448                            worktrees_store.schedule_serialization(
 1449                                cx,
 1450                                |new_trusted_worktrees, cx| {
 1451                                    let timeout =
 1452                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1453                                    let db = WorkspaceDb::global(cx);
 1454                                    cx.background_spawn(async move {
 1455                                        timeout.await;
 1456                                        db.save_trusted_worktrees(new_trusted_worktrees)
 1457                                            .await
 1458                                            .log_err();
 1459                                    })
 1460                                },
 1461                            )
 1462                        });
 1463                    }
 1464                }
 1465            })
 1466            .detach();
 1467
 1468            cx.observe_global::<SettingsStore>(|_, cx| {
 1469                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1470                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1471                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1472                            trusted_worktrees.auto_trust_all(cx);
 1473                        })
 1474                    }
 1475                }
 1476            })
 1477            .detach();
 1478        }
 1479
 1480        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1481            match event {
 1482                project::Event::RemoteIdChanged(_) => {
 1483                    this.update_window_title(window, cx);
 1484                }
 1485
 1486                project::Event::CollaboratorLeft(peer_id) => {
 1487                    this.collaborator_left(*peer_id, window, cx);
 1488                }
 1489
 1490                &project::Event::WorktreeRemoved(_) => {
 1491                    this.update_window_title(window, cx);
 1492                    this.serialize_workspace(window, cx);
 1493                    this.update_history(cx);
 1494                }
 1495
 1496                &project::Event::WorktreeAdded(id) => {
 1497                    this.update_window_title(window, cx);
 1498                    if this
 1499                        .project()
 1500                        .read(cx)
 1501                        .worktree_for_id(id, cx)
 1502                        .is_some_and(|wt| wt.read(cx).is_visible())
 1503                    {
 1504                        this.serialize_workspace(window, cx);
 1505                        this.update_history(cx);
 1506                    }
 1507                }
 1508                project::Event::WorktreeUpdatedEntries(..) => {
 1509                    this.update_window_title(window, cx);
 1510                    this.serialize_workspace(window, cx);
 1511                }
 1512
 1513                project::Event::DisconnectedFromHost => {
 1514                    this.update_window_edited(window, cx);
 1515                    let leaders_to_unfollow =
 1516                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1517                    for leader_id in leaders_to_unfollow {
 1518                        this.unfollow(leader_id, window, cx);
 1519                    }
 1520                }
 1521
 1522                project::Event::DisconnectedFromRemote {
 1523                    server_not_running: _,
 1524                } => {
 1525                    this.update_window_edited(window, cx);
 1526                }
 1527
 1528                project::Event::Closed => {
 1529                    window.remove_window();
 1530                }
 1531
 1532                project::Event::DeletedEntry(_, entry_id) => {
 1533                    for pane in this.panes.iter() {
 1534                        pane.update(cx, |pane, cx| {
 1535                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1536                        });
 1537                    }
 1538                }
 1539
 1540                project::Event::Toast {
 1541                    notification_id,
 1542                    message,
 1543                    link,
 1544                } => this.show_notification(
 1545                    NotificationId::named(notification_id.clone()),
 1546                    cx,
 1547                    |cx| {
 1548                        let mut notification = MessageNotification::new(message.clone(), cx);
 1549                        if let Some(link) = link {
 1550                            notification = notification
 1551                                .more_info_message(link.label)
 1552                                .more_info_url(link.url);
 1553                        }
 1554
 1555                        cx.new(|_| notification)
 1556                    },
 1557                ),
 1558
 1559                project::Event::HideToast { notification_id } => {
 1560                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1561                }
 1562
 1563                project::Event::LanguageServerPrompt(request) => {
 1564                    struct LanguageServerPrompt;
 1565
 1566                    this.show_notification(
 1567                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1568                        cx,
 1569                        |cx| {
 1570                            cx.new(|cx| {
 1571                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1572                            })
 1573                        },
 1574                    );
 1575                }
 1576
 1577                project::Event::AgentLocationChanged => {
 1578                    this.handle_agent_location_changed(window, cx)
 1579                }
 1580
 1581                _ => {}
 1582            }
 1583            cx.notify()
 1584        })
 1585        .detach();
 1586
 1587        cx.subscribe_in(
 1588            &project.read(cx).breakpoint_store(),
 1589            window,
 1590            |workspace, _, event, window, cx| match event {
 1591                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1592                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1593                    workspace.serialize_workspace(window, cx);
 1594                }
 1595                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1596            },
 1597        )
 1598        .detach();
 1599        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1600            cx.subscribe_in(
 1601                &toolchain_store,
 1602                window,
 1603                |workspace, _, event, window, cx| match event {
 1604                    ToolchainStoreEvent::CustomToolchainsModified => {
 1605                        workspace.serialize_workspace(window, cx);
 1606                    }
 1607                    _ => {}
 1608                },
 1609            )
 1610            .detach();
 1611        }
 1612
 1613        cx.on_focus_lost(window, |this, window, cx| {
 1614            let focus_handle = this.focus_handle(cx);
 1615            window.focus(&focus_handle, cx);
 1616        })
 1617        .detach();
 1618
 1619        let weak_handle = cx.entity().downgrade();
 1620        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1621
 1622        let center_pane = cx.new(|cx| {
 1623            let mut center_pane = Pane::new(
 1624                weak_handle.clone(),
 1625                project.clone(),
 1626                pane_history_timestamp.clone(),
 1627                None,
 1628                NewFile.boxed_clone(),
 1629                true,
 1630                window,
 1631                cx,
 1632            );
 1633            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1634            center_pane.set_should_display_welcome_page(true);
 1635            center_pane
 1636        });
 1637        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1638            .detach();
 1639
 1640        window.focus(&center_pane.focus_handle(cx), cx);
 1641
 1642        cx.emit(Event::PaneAdded(center_pane.clone()));
 1643
 1644        let any_window_handle = window.window_handle();
 1645        app_state.workspace_store.update(cx, |store, _| {
 1646            store
 1647                .workspaces
 1648                .insert((any_window_handle, weak_handle.clone()));
 1649        });
 1650
 1651        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1652        let mut connection_status = app_state.client.status();
 1653        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1654            current_user.next().await;
 1655            connection_status.next().await;
 1656            let mut stream =
 1657                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1658
 1659            while stream.recv().await.is_some() {
 1660                this.update(cx, |_, cx| cx.notify())?;
 1661            }
 1662            anyhow::Ok(())
 1663        });
 1664
 1665        // All leader updates are enqueued and then processed in a single task, so
 1666        // that each asynchronous operation can be run in order.
 1667        let (leader_updates_tx, mut leader_updates_rx) =
 1668            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1669        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1670            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1671                Self::process_leader_update(&this, leader_id, update, cx)
 1672                    .await
 1673                    .log_err();
 1674            }
 1675
 1676            Ok(())
 1677        });
 1678
 1679        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1680        let modal_layer = cx.new(|_| ModalLayer::new());
 1681        let toast_layer = cx.new(|_| ToastLayer::new());
 1682        cx.subscribe(
 1683            &modal_layer,
 1684            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1685                cx.emit(Event::ModalOpened);
 1686            },
 1687        )
 1688        .detach();
 1689
 1690        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1691        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1692        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1693        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1694        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1695        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1696        let multi_workspace = window
 1697            .root::<MultiWorkspace>()
 1698            .flatten()
 1699            .map(|mw| mw.downgrade());
 1700        let status_bar = cx.new(|cx| {
 1701            let mut status_bar =
 1702                StatusBar::new(&center_pane.clone(), multi_workspace.clone(), window, cx);
 1703            status_bar.add_left_item(left_dock_buttons, window, cx);
 1704            status_bar.add_right_item(right_dock_buttons, window, cx);
 1705            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1706            status_bar
 1707        });
 1708
 1709        let session_id = app_state.session.read(cx).id().to_owned();
 1710
 1711        let mut active_call = None;
 1712        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1713            let subscriptions =
 1714                vec![
 1715                    call.0
 1716                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1717                ];
 1718            active_call = Some((call, subscriptions));
 1719        }
 1720
 1721        let (serializable_items_tx, serializable_items_rx) =
 1722            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1723        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1724            Self::serialize_items(&this, serializable_items_rx, cx).await
 1725        });
 1726
 1727        let subscriptions = vec![
 1728            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1729            cx.observe_window_bounds(window, move |this, window, cx| {
 1730                if this.bounds_save_task_queued.is_some() {
 1731                    return;
 1732                }
 1733                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1734                    cx.background_executor()
 1735                        .timer(Duration::from_millis(100))
 1736                        .await;
 1737                    this.update_in(cx, |this, window, cx| {
 1738                        this.save_window_bounds(window, cx).detach();
 1739                        this.bounds_save_task_queued.take();
 1740                    })
 1741                    .ok();
 1742                }));
 1743                cx.notify();
 1744            }),
 1745            cx.observe_window_appearance(window, |_, window, cx| {
 1746                let window_appearance = window.appearance();
 1747
 1748                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1749
 1750                theme_settings::reload_theme(cx);
 1751                theme_settings::reload_icon_theme(cx);
 1752            }),
 1753            cx.on_release({
 1754                let weak_handle = weak_handle.clone();
 1755                move |this, cx| {
 1756                    this.app_state.workspace_store.update(cx, move |store, _| {
 1757                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1758                    })
 1759                }
 1760            }),
 1761        ];
 1762
 1763        cx.defer_in(window, move |this, window, cx| {
 1764            this.update_window_title(window, cx);
 1765            this.show_initial_notifications(cx);
 1766        });
 1767
 1768        let mut center = PaneGroup::new(center_pane.clone());
 1769        center.set_is_center(true);
 1770        center.mark_positions(cx);
 1771
 1772        Workspace {
 1773            weak_self: weak_handle.clone(),
 1774            zoomed: None,
 1775            zoomed_position: None,
 1776            previous_dock_drag_coordinates: None,
 1777            center,
 1778            panes: vec![center_pane.clone()],
 1779            panes_by_item: Default::default(),
 1780            active_pane: center_pane.clone(),
 1781            last_active_center_pane: Some(center_pane.downgrade()),
 1782            last_active_view_id: None,
 1783            status_bar,
 1784            modal_layer,
 1785            toast_layer,
 1786            titlebar_item: None,
 1787            notifications: Notifications::default(),
 1788            suppressed_notifications: HashSet::default(),
 1789            left_dock,
 1790            bottom_dock,
 1791            right_dock,
 1792            _panels_task: None,
 1793            project: project.clone(),
 1794            follower_states: Default::default(),
 1795            last_leaders_by_pane: Default::default(),
 1796            dispatching_keystrokes: Default::default(),
 1797            window_edited: false,
 1798            last_window_title: None,
 1799            dirty_items: Default::default(),
 1800            active_call,
 1801            database_id: workspace_id,
 1802            app_state,
 1803            _observe_current_user,
 1804            _apply_leader_updates,
 1805            _schedule_serialize_workspace: None,
 1806            _serialize_workspace_task: None,
 1807            _schedule_serialize_ssh_paths: None,
 1808            leader_updates_tx,
 1809            _subscriptions: subscriptions,
 1810            pane_history_timestamp,
 1811            workspace_actions: Default::default(),
 1812            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1813            bounds: Default::default(),
 1814            centered_layout: false,
 1815            bounds_save_task_queued: None,
 1816            on_prompt_for_new_path: None,
 1817            on_prompt_for_open_path: None,
 1818            terminal_provider: None,
 1819            debugger_provider: None,
 1820            serializable_items_tx,
 1821            _items_serializer,
 1822            session_id: Some(session_id),
 1823
 1824            scheduled_tasks: Vec::new(),
 1825            last_open_dock_positions: Vec::new(),
 1826            removing: false,
 1827            sidebar_focus_handle: None,
 1828            multi_workspace,
 1829            active_worktree_creation: ActiveWorktreeCreation::default(),
 1830            open_in_dev_container: false,
 1831            _dev_container_task: None,
 1832        }
 1833    }
 1834
 1835    pub fn new_local(
 1836        abs_paths: Vec<PathBuf>,
 1837        app_state: Arc<AppState>,
 1838        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1839        env: Option<HashMap<String, String>>,
 1840        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1841        open_mode: OpenMode,
 1842        cx: &mut App,
 1843    ) -> Task<anyhow::Result<OpenResult>> {
 1844        let project_handle = Project::local(
 1845            app_state.client.clone(),
 1846            app_state.node_runtime.clone(),
 1847            app_state.user_store.clone(),
 1848            app_state.languages.clone(),
 1849            app_state.fs.clone(),
 1850            env,
 1851            Default::default(),
 1852            cx,
 1853        );
 1854
 1855        let db = WorkspaceDb::global(cx);
 1856        let kvp = db::kvp::KeyValueStore::global(cx);
 1857        cx.spawn(async move |cx| {
 1858            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1859            for path in abs_paths.into_iter() {
 1860                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1861                    paths_to_open.push(canonical)
 1862                } else {
 1863                    paths_to_open.push(path)
 1864                }
 1865            }
 1866
 1867            let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
 1868
 1869            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1870                paths_to_open = paths.ordered_paths().cloned().collect();
 1871                if !paths.is_lexicographically_ordered() {
 1872                    project_handle.update(cx, |project, cx| {
 1873                        project.set_worktrees_reordered(true, cx);
 1874                    });
 1875                }
 1876            }
 1877
 1878            // Get project paths for all of the abs_paths
 1879            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1880                Vec::with_capacity(paths_to_open.len());
 1881
 1882            for path in paths_to_open.into_iter() {
 1883                if let Some((_, project_entry)) = cx
 1884                    .update(|cx| {
 1885                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1886                    })
 1887                    .await
 1888                    .log_err()
 1889                {
 1890                    project_paths.push((path, Some(project_entry)));
 1891                } else {
 1892                    project_paths.push((path, None));
 1893                }
 1894            }
 1895
 1896            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1897                serialized_workspace.id
 1898            } else {
 1899                db.next_id().await.unwrap_or_else(|_| Default::default())
 1900            };
 1901
 1902            let toolchains = db.toolchains(workspace_id).await?;
 1903
 1904            for (toolchain, worktree_path, path) in toolchains {
 1905                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1906                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1907                    this.find_worktree(&worktree_path, cx)
 1908                        .and_then(|(worktree, rel_path)| {
 1909                            if rel_path.is_empty() {
 1910                                Some(worktree.read(cx).id())
 1911                            } else {
 1912                                None
 1913                            }
 1914                        })
 1915                }) else {
 1916                    // We did not find a worktree with a given path, but that's whatever.
 1917                    continue;
 1918                };
 1919                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1920                    continue;
 1921                }
 1922
 1923                project_handle
 1924                    .update(cx, |this, cx| {
 1925                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1926                    })
 1927                    .await;
 1928            }
 1929            if let Some(workspace) = serialized_workspace.as_ref() {
 1930                project_handle.update(cx, |this, cx| {
 1931                    for (scope, toolchains) in &workspace.user_toolchains {
 1932                        for toolchain in toolchains {
 1933                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1934                        }
 1935                    }
 1936                });
 1937            }
 1938
 1939            let window_to_replace = match open_mode {
 1940                OpenMode::NewWindow => None,
 1941                _ => requesting_window,
 1942            };
 1943
 1944            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1945                if let Some(window) = window_to_replace {
 1946                    let centered_layout = serialized_workspace
 1947                        .as_ref()
 1948                        .map(|w| w.centered_layout)
 1949                        .unwrap_or(false);
 1950
 1951                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1952                        let workspace = cx.new(|cx| {
 1953                            let mut workspace = Workspace::new(
 1954                                Some(workspace_id),
 1955                                project_handle.clone(),
 1956                                app_state.clone(),
 1957                                window,
 1958                                cx,
 1959                            );
 1960
 1961                            workspace.centered_layout = centered_layout;
 1962
 1963                            // Call init callback to add items before window renders
 1964                            if let Some(init) = init {
 1965                                init(&mut workspace, window, cx);
 1966                            }
 1967
 1968                            workspace
 1969                        });
 1970                        match open_mode {
 1971                            OpenMode::Activate => {
 1972                                multi_workspace.activate(workspace.clone(), None, window, cx);
 1973                            }
 1974                            OpenMode::Add => {
 1975                                multi_workspace.add(workspace.clone(), &*window, cx);
 1976                            }
 1977                            OpenMode::NewWindow => {
 1978                                unreachable!()
 1979                            }
 1980                        }
 1981                        workspace
 1982                    })?;
 1983                    (window, workspace)
 1984                } else {
 1985                    let window_bounds_override = window_bounds_env_override();
 1986
 1987                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1988                        (Some(WindowBounds::Windowed(bounds)), None)
 1989                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1990                        && let Some(display) = workspace.display
 1991                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1992                    {
 1993                        // Reopening an existing workspace - restore its saved bounds
 1994                        (Some(bounds.0), Some(display))
 1995                    } else if let Some((display, bounds)) =
 1996                        persistence::read_default_window_bounds(&kvp)
 1997                    {
 1998                        // New or empty workspace - use the last known window bounds
 1999                        (Some(bounds), Some(display))
 2000                    } else {
 2001                        // New window - let GPUI's default_bounds() handle cascading
 2002                        (None, None)
 2003                    };
 2004
 2005                    // Use the serialized workspace to construct the new window
 2006                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 2007                    options.window_bounds = window_bounds;
 2008                    let centered_layout = serialized_workspace
 2009                        .as_ref()
 2010                        .map(|w| w.centered_layout)
 2011                        .unwrap_or(false);
 2012                    let window = cx.open_window(options, {
 2013                        let app_state = app_state.clone();
 2014                        let project_handle = project_handle.clone();
 2015                        move |window, cx| {
 2016                            let workspace = cx.new(|cx| {
 2017                                let mut workspace = Workspace::new(
 2018                                    Some(workspace_id),
 2019                                    project_handle,
 2020                                    app_state,
 2021                                    window,
 2022                                    cx,
 2023                                );
 2024                                workspace.centered_layout = centered_layout;
 2025
 2026                                // Call init callback to add items before window renders
 2027                                if let Some(init) = init {
 2028                                    init(&mut workspace, window, cx);
 2029                                }
 2030
 2031                                workspace
 2032                            });
 2033                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 2034                        }
 2035                    })?;
 2036                    let workspace =
 2037                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 2038                            multi_workspace.workspace().clone()
 2039                        })?;
 2040                    (window, workspace)
 2041                };
 2042
 2043            notify_if_database_failed(window, cx);
 2044            // Check if this is an empty workspace (no paths to open)
 2045            // An empty workspace is one where project_paths is empty
 2046            let is_empty_workspace = project_paths.is_empty();
 2047            // Check if serialized workspace has paths before it's moved
 2048            let serialized_workspace_has_paths = serialized_workspace
 2049                .as_ref()
 2050                .map(|ws| !ws.paths.is_empty())
 2051                .unwrap_or(false);
 2052
 2053            let opened_items = window
 2054                .update(cx, |_, window, cx| {
 2055                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 2056                        open_items(serialized_workspace, project_paths, window, cx)
 2057                    })
 2058                })?
 2059                .await
 2060                .unwrap_or_default();
 2061
 2062            // Restore default dock state for empty workspaces
 2063            // Only restore if:
 2064            // 1. This is an empty workspace (no paths), AND
 2065            // 2. The serialized workspace either doesn't exist or has no paths
 2066            if is_empty_workspace && !serialized_workspace_has_paths {
 2067                if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
 2068                    window
 2069                        .update(cx, |_, window, cx| {
 2070                            workspace.update(cx, |workspace, cx| {
 2071                                for (dock, serialized_dock) in [
 2072                                    (&workspace.right_dock, &default_docks.right),
 2073                                    (&workspace.left_dock, &default_docks.left),
 2074                                    (&workspace.bottom_dock, &default_docks.bottom),
 2075                                ] {
 2076                                    dock.update(cx, |dock, cx| {
 2077                                        dock.serialized_dock = Some(serialized_dock.clone());
 2078                                        dock.restore_state(window, cx);
 2079                                    });
 2080                                }
 2081                                cx.notify();
 2082                            });
 2083                        })
 2084                        .log_err();
 2085                }
 2086            }
 2087
 2088            window
 2089                .update(cx, |_, _window, cx| {
 2090                    workspace.update(cx, |this: &mut Workspace, cx| {
 2091                        this.update_history(cx);
 2092                    });
 2093                })
 2094                .log_err();
 2095            Ok(OpenResult {
 2096                window,
 2097                workspace,
 2098                opened_items,
 2099            })
 2100        })
 2101    }
 2102
 2103    pub fn project_group_key(&self, cx: &App) -> ProjectGroupKey {
 2104        self.project.read(cx).project_group_key(cx)
 2105    }
 2106
 2107    pub fn weak_handle(&self) -> WeakEntity<Self> {
 2108        self.weak_self.clone()
 2109    }
 2110
 2111    pub fn left_dock(&self) -> &Entity<Dock> {
 2112        &self.left_dock
 2113    }
 2114
 2115    pub fn bottom_dock(&self) -> &Entity<Dock> {
 2116        &self.bottom_dock
 2117    }
 2118
 2119    pub fn set_bottom_dock_layout(
 2120        &mut self,
 2121        layout: BottomDockLayout,
 2122        window: &mut Window,
 2123        cx: &mut Context<Self>,
 2124    ) {
 2125        let fs = self.project().read(cx).fs();
 2126        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 2127            content.workspace.bottom_dock_layout = Some(layout);
 2128        });
 2129
 2130        cx.notify();
 2131        self.serialize_workspace(window, cx);
 2132    }
 2133
 2134    pub fn right_dock(&self) -> &Entity<Dock> {
 2135        &self.right_dock
 2136    }
 2137
 2138    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 2139        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 2140    }
 2141
 2142    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 2143        let left_dock = self.left_dock.read(cx);
 2144        let left_visible = left_dock.is_open();
 2145        let left_active_panel = left_dock
 2146            .active_panel()
 2147            .map(|panel| panel.persistent_name().to_string());
 2148        // `zoomed_position` is kept in sync with individual panel zoom state
 2149        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2150        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2151
 2152        let right_dock = self.right_dock.read(cx);
 2153        let right_visible = right_dock.is_open();
 2154        let right_active_panel = right_dock
 2155            .active_panel()
 2156            .map(|panel| panel.persistent_name().to_string());
 2157        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2158
 2159        let bottom_dock = self.bottom_dock.read(cx);
 2160        let bottom_visible = bottom_dock.is_open();
 2161        let bottom_active_panel = bottom_dock
 2162            .active_panel()
 2163            .map(|panel| panel.persistent_name().to_string());
 2164        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2165
 2166        DockStructure {
 2167            left: DockData {
 2168                visible: left_visible,
 2169                active_panel: left_active_panel,
 2170                zoom: left_dock_zoom,
 2171            },
 2172            right: DockData {
 2173                visible: right_visible,
 2174                active_panel: right_active_panel,
 2175                zoom: right_dock_zoom,
 2176            },
 2177            bottom: DockData {
 2178                visible: bottom_visible,
 2179                active_panel: bottom_active_panel,
 2180                zoom: bottom_dock_zoom,
 2181            },
 2182        }
 2183    }
 2184
 2185    pub fn set_dock_structure(
 2186        &self,
 2187        docks: DockStructure,
 2188        window: &mut Window,
 2189        cx: &mut Context<Self>,
 2190    ) {
 2191        for (dock, data) in [
 2192            (&self.left_dock, docks.left),
 2193            (&self.bottom_dock, docks.bottom),
 2194            (&self.right_dock, docks.right),
 2195        ] {
 2196            dock.update(cx, |dock, cx| {
 2197                dock.serialized_dock = Some(data);
 2198                dock.restore_state(window, cx);
 2199            });
 2200        }
 2201    }
 2202
 2203    /// Returns which dock currently has focus, or `None` if focus is in the
 2204    /// center pane or elsewhere. Does NOT fall back to any global state.
 2205    pub fn focused_dock_position(&self, window: &Window, cx: &App) -> Option<DockPosition> {
 2206        [
 2207            (DockPosition::Left, &self.left_dock),
 2208            (DockPosition::Right, &self.right_dock),
 2209            (DockPosition::Bottom, &self.bottom_dock),
 2210        ]
 2211        .into_iter()
 2212        .find(|(_, dock)| {
 2213            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 2214        })
 2215        .map(|(position, _)| position)
 2216    }
 2217
 2218    pub fn active_worktree_creation(&self) -> &ActiveWorktreeCreation {
 2219        &self.active_worktree_creation
 2220    }
 2221
 2222    pub fn set_active_worktree_creation(
 2223        &mut self,
 2224        label: Option<SharedString>,
 2225        is_switch: bool,
 2226        cx: &mut Context<Self>,
 2227    ) {
 2228        self.active_worktree_creation.label = label;
 2229        self.active_worktree_creation.is_switch = is_switch;
 2230        cx.emit(Event::WorktreeCreationChanged);
 2231        cx.notify();
 2232    }
 2233
 2234    /// Captures the current workspace state for restoring after a worktree switch.
 2235    /// This includes dock layout, open file paths, and the active file path.
 2236    pub fn capture_state_for_worktree_switch(
 2237        &self,
 2238        window: &Window,
 2239        fallback_focused_dock: Option<DockPosition>,
 2240        cx: &App,
 2241    ) -> PreviousWorkspaceState {
 2242        let dock_structure = self.capture_dock_state(window, cx);
 2243        let open_file_paths = self.open_item_abs_paths(cx);
 2244        let active_file_path = self
 2245            .active_item(cx)
 2246            .and_then(|item| item.project_path(cx))
 2247            .and_then(|pp| self.project().read(cx).absolute_path(&pp, cx));
 2248
 2249        let focused_dock = self
 2250            .focused_dock_position(window, cx)
 2251            .or(fallback_focused_dock);
 2252
 2253        PreviousWorkspaceState {
 2254            dock_structure,
 2255            open_file_paths,
 2256            active_file_path,
 2257            focused_dock,
 2258        }
 2259    }
 2260
 2261    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2262        self.items(cx)
 2263            .filter_map(|item| {
 2264                let project_path = item.project_path(cx)?;
 2265                self.project.read(cx).absolute_path(&project_path, cx)
 2266            })
 2267            .collect()
 2268    }
 2269
 2270    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2271        match position {
 2272            DockPosition::Left => &self.left_dock,
 2273            DockPosition::Bottom => &self.bottom_dock,
 2274            DockPosition::Right => &self.right_dock,
 2275        }
 2276    }
 2277
 2278    pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
 2279        self.all_docks().into_iter().find_map(|dock| {
 2280            let dock = dock.read(cx);
 2281            dock.has_agent_panel(cx).then_some(dock.position())
 2282        })
 2283    }
 2284
 2285    pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
 2286        self.all_docks().into_iter().find_map(|dock| {
 2287            let dock = dock.read(cx);
 2288            let panel = dock.panel::<T>()?;
 2289            dock.stored_panel_size_state(&panel)
 2290        })
 2291    }
 2292
 2293    pub fn persisted_panel_size_state(
 2294        &self,
 2295        panel_key: &'static str,
 2296        cx: &App,
 2297    ) -> Option<dock::PanelSizeState> {
 2298        dock::Dock::load_persisted_size_state(self, panel_key, cx)
 2299    }
 2300
 2301    pub fn persist_panel_size_state(
 2302        &self,
 2303        panel_key: &str,
 2304        size_state: dock::PanelSizeState,
 2305        cx: &mut App,
 2306    ) {
 2307        let Some(workspace_id) = self
 2308            .database_id()
 2309            .map(|id| i64::from(id).to_string())
 2310            .or(self.session_id())
 2311        else {
 2312            return;
 2313        };
 2314
 2315        let kvp = db::kvp::KeyValueStore::global(cx);
 2316        let panel_key = panel_key.to_string();
 2317        cx.background_spawn(async move {
 2318            let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
 2319            scope
 2320                .write(
 2321                    format!("{workspace_id}:{panel_key}"),
 2322                    serde_json::to_string(&size_state)?,
 2323                )
 2324                .await
 2325        })
 2326        .detach_and_log_err(cx);
 2327    }
 2328
 2329    pub fn set_panel_size_state<T: Panel>(
 2330        &mut self,
 2331        size_state: dock::PanelSizeState,
 2332        window: &mut Window,
 2333        cx: &mut Context<Self>,
 2334    ) -> bool {
 2335        let Some(panel) = self.panel::<T>(cx) else {
 2336            return false;
 2337        };
 2338
 2339        let dock = self.dock_at_position(panel.position(window, cx));
 2340        let did_set = dock.update(cx, |dock, cx| {
 2341            dock.set_panel_size_state(&panel, size_state, cx)
 2342        });
 2343
 2344        if did_set {
 2345            self.persist_panel_size_state(T::panel_key(), size_state, cx);
 2346        }
 2347
 2348        did_set
 2349    }
 2350
 2351    pub fn toggle_dock_panel_flexible_size(
 2352        &self,
 2353        dock: &Entity<Dock>,
 2354        panel: &dyn PanelHandle,
 2355        window: &mut Window,
 2356        cx: &mut App,
 2357    ) {
 2358        let position = dock.read(cx).position();
 2359        let current_size = self.dock_size(&dock.read(cx), window, cx);
 2360        let current_flex =
 2361            current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
 2362        dock.update(cx, |dock, cx| {
 2363            dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
 2364        });
 2365    }
 2366
 2367    fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
 2368        let panel = dock.active_panel()?;
 2369        let size_state = dock
 2370            .stored_panel_size_state(panel.as_ref())
 2371            .unwrap_or_default();
 2372        let position = dock.position();
 2373
 2374        let use_flex = panel.has_flexible_size(window, cx);
 2375
 2376        if position.axis() == Axis::Horizontal
 2377            && use_flex
 2378            && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
 2379        {
 2380            let workspace_width = self.bounds.size.width;
 2381            if workspace_width <= Pixels::ZERO {
 2382                return None;
 2383            }
 2384            let flex = flex.max(0.001);
 2385            let center_column_count = self.center_full_height_column_count();
 2386            let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2387            if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2388                let total_flex = flex + center_column_count + opposite_flex;
 2389                return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
 2390            } else {
 2391                let opposite_fixed = opposite
 2392                    .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2393                    .unwrap_or_default();
 2394                let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
 2395                return Some(
 2396                    (flex / (flex + center_column_count) * available).max(RESIZE_HANDLE_SIZE),
 2397                );
 2398            }
 2399        }
 2400
 2401        Some(
 2402            size_state
 2403                .size
 2404                .unwrap_or_else(|| panel.default_size(window, cx)),
 2405        )
 2406    }
 2407
 2408    pub fn dock_flex_for_size(
 2409        &self,
 2410        position: DockPosition,
 2411        size: Pixels,
 2412        window: &Window,
 2413        cx: &App,
 2414    ) -> Option<f32> {
 2415        if position.axis() != Axis::Horizontal {
 2416            return None;
 2417        }
 2418
 2419        let workspace_width = self.bounds.size.width;
 2420        if workspace_width <= Pixels::ZERO {
 2421            return None;
 2422        }
 2423
 2424        let center_column_count = self.center_full_height_column_count();
 2425        let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
 2426        if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
 2427            let size = size.clamp(px(0.), workspace_width - px(1.));
 2428            Some((size * (center_column_count + opposite_flex) / (workspace_width - size)).max(0.0))
 2429        } else {
 2430            let opposite_width = opposite
 2431                .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
 2432                .unwrap_or_default();
 2433            let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
 2434            let remaining = (available - size).max(px(1.));
 2435            Some((size * center_column_count / remaining).max(0.0))
 2436        }
 2437    }
 2438
 2439    fn opposite_dock_panel_and_size_state(
 2440        &self,
 2441        position: DockPosition,
 2442        window: &Window,
 2443        cx: &App,
 2444    ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
 2445        let opposite_position = match position {
 2446            DockPosition::Left => DockPosition::Right,
 2447            DockPosition::Right => DockPosition::Left,
 2448            DockPosition::Bottom => return None,
 2449        };
 2450
 2451        let opposite_dock = self.dock_at_position(opposite_position).read(cx);
 2452        let panel = opposite_dock.visible_panel()?;
 2453        let mut size_state = opposite_dock
 2454            .stored_panel_size_state(panel.as_ref())
 2455            .unwrap_or_default();
 2456        if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
 2457            size_state.flex = self.default_dock_flex(opposite_position);
 2458        }
 2459        Some((panel.clone(), size_state))
 2460    }
 2461
 2462    fn center_full_height_column_count(&self) -> f32 {
 2463        self.center.full_height_column_count().max(1) as f32
 2464    }
 2465
 2466    pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
 2467        if position.axis() != Axis::Horizontal {
 2468            return None;
 2469        }
 2470
 2471        Some(1.0)
 2472    }
 2473
 2474    pub fn is_edited(&self) -> bool {
 2475        self.window_edited
 2476    }
 2477
 2478    pub fn add_panel<T: Panel>(
 2479        &mut self,
 2480        panel: Entity<T>,
 2481        window: &mut Window,
 2482        cx: &mut Context<Self>,
 2483    ) {
 2484        let focus_handle = panel.panel_focus_handle(cx);
 2485        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2486            .detach();
 2487
 2488        let dock_position = panel.position(window, cx);
 2489        let dock = self.dock_at_position(dock_position);
 2490        let any_panel = panel.to_any();
 2491        let persisted_size_state =
 2492            self.persisted_panel_size_state(T::panel_key(), cx)
 2493                .or_else(|| {
 2494                    load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
 2495                        let state = dock::PanelSizeState {
 2496                            size: Some(size),
 2497                            flex: None,
 2498                        };
 2499                        self.persist_panel_size_state(T::panel_key(), state, cx);
 2500                        state
 2501                    })
 2502                });
 2503
 2504        dock.update(cx, |dock, cx| {
 2505            let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
 2506            if let Some(size_state) = persisted_size_state {
 2507                dock.set_panel_size_state(&panel, size_state, cx);
 2508            }
 2509            index
 2510        });
 2511
 2512        cx.emit(Event::PanelAdded(any_panel));
 2513    }
 2514
 2515    pub fn remove_panel<T: Panel>(
 2516        &mut self,
 2517        panel: &Entity<T>,
 2518        window: &mut Window,
 2519        cx: &mut Context<Self>,
 2520    ) {
 2521        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2522            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2523        }
 2524    }
 2525
 2526    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2527        &self.status_bar
 2528    }
 2529
 2530    pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
 2531        self.sidebar_focus_handle = handle;
 2532    }
 2533
 2534    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2535        StatusBarSettings::get_global(cx).show
 2536    }
 2537
 2538    pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
 2539        self.multi_workspace.as_ref()
 2540    }
 2541
 2542    pub fn set_multi_workspace(
 2543        &mut self,
 2544        multi_workspace: WeakEntity<MultiWorkspace>,
 2545        cx: &mut App,
 2546    ) {
 2547        self.status_bar.update(cx, |status_bar, cx| {
 2548            status_bar.set_multi_workspace(multi_workspace.clone(), cx);
 2549        });
 2550        self.multi_workspace = Some(multi_workspace);
 2551    }
 2552
 2553    pub fn app_state(&self) -> &Arc<AppState> {
 2554        &self.app_state
 2555    }
 2556
 2557    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2558        self._panels_task = Some(task);
 2559    }
 2560
 2561    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2562        self._panels_task.take()
 2563    }
 2564
 2565    pub fn user_store(&self) -> &Entity<UserStore> {
 2566        &self.app_state.user_store
 2567    }
 2568
 2569    pub fn project(&self) -> &Entity<Project> {
 2570        &self.project
 2571    }
 2572
 2573    pub fn path_style(&self, cx: &App) -> PathStyle {
 2574        self.project.read(cx).path_style(cx)
 2575    }
 2576
 2577    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2578        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2579
 2580        for pane_handle in &self.panes {
 2581            let pane = pane_handle.read(cx);
 2582
 2583            for entry in pane.activation_history() {
 2584                history.insert(
 2585                    entry.entity_id,
 2586                    history
 2587                        .get(&entry.entity_id)
 2588                        .cloned()
 2589                        .unwrap_or(0)
 2590                        .max(entry.timestamp),
 2591                );
 2592            }
 2593        }
 2594
 2595        history
 2596    }
 2597
 2598    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2599        let mut recent_item: Option<Entity<T>> = None;
 2600        let mut recent_timestamp = 0;
 2601        for pane_handle in &self.panes {
 2602            let pane = pane_handle.read(cx);
 2603            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2604                pane.items().map(|item| (item.item_id(), item)).collect();
 2605            for entry in pane.activation_history() {
 2606                if entry.timestamp > recent_timestamp
 2607                    && let Some(&item) = item_map.get(&entry.entity_id)
 2608                    && let Some(typed_item) = item.act_as::<T>(cx)
 2609                {
 2610                    recent_timestamp = entry.timestamp;
 2611                    recent_item = Some(typed_item);
 2612                }
 2613            }
 2614        }
 2615        recent_item
 2616    }
 2617
 2618    pub fn recent_navigation_history_iter(
 2619        &self,
 2620        cx: &App,
 2621    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2622        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2623        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2624
 2625        for pane in &self.panes {
 2626            let pane = pane.read(cx);
 2627
 2628            pane.nav_history()
 2629                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2630                    if let Some(fs_path) = &fs_path {
 2631                        abs_paths_opened
 2632                            .entry(fs_path.clone())
 2633                            .or_default()
 2634                            .insert(project_path.clone());
 2635                    }
 2636                    let timestamp = entry.timestamp;
 2637                    match history.entry(project_path) {
 2638                        hash_map::Entry::Occupied(mut entry) => {
 2639                            let (_, old_timestamp) = entry.get();
 2640                            if &timestamp > old_timestamp {
 2641                                entry.insert((fs_path, timestamp));
 2642                            }
 2643                        }
 2644                        hash_map::Entry::Vacant(entry) => {
 2645                            entry.insert((fs_path, timestamp));
 2646                        }
 2647                    }
 2648                });
 2649
 2650            if let Some(item) = pane.active_item()
 2651                && let Some(project_path) = item.project_path(cx)
 2652            {
 2653                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2654
 2655                if let Some(fs_path) = &fs_path {
 2656                    abs_paths_opened
 2657                        .entry(fs_path.clone())
 2658                        .or_default()
 2659                        .insert(project_path.clone());
 2660                }
 2661
 2662                history.insert(project_path, (fs_path, std::usize::MAX));
 2663            }
 2664        }
 2665
 2666        history
 2667            .into_iter()
 2668            .sorted_by_key(|(_, (_, order))| *order)
 2669            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2670            .rev()
 2671            .filter(move |(history_path, abs_path)| {
 2672                let latest_project_path_opened = abs_path
 2673                    .as_ref()
 2674                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2675                    .and_then(|project_paths| {
 2676                        project_paths
 2677                            .iter()
 2678                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2679                    });
 2680
 2681                latest_project_path_opened.is_none_or(|path| path == history_path)
 2682            })
 2683    }
 2684
 2685    pub fn recent_navigation_history(
 2686        &self,
 2687        limit: Option<usize>,
 2688        cx: &App,
 2689    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2690        self.recent_navigation_history_iter(cx)
 2691            .take(limit.unwrap_or(usize::MAX))
 2692            .collect()
 2693    }
 2694
 2695    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2696        for pane in &self.panes {
 2697            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2698        }
 2699    }
 2700
 2701    fn navigate_history(
 2702        &mut self,
 2703        pane: WeakEntity<Pane>,
 2704        mode: NavigationMode,
 2705        window: &mut Window,
 2706        cx: &mut Context<Workspace>,
 2707    ) -> Task<Result<()>> {
 2708        self.navigate_history_impl(
 2709            pane,
 2710            mode,
 2711            window,
 2712            &mut |history, cx| history.pop(mode, cx),
 2713            cx,
 2714        )
 2715    }
 2716
 2717    fn navigate_tag_history(
 2718        &mut self,
 2719        pane: WeakEntity<Pane>,
 2720        mode: TagNavigationMode,
 2721        window: &mut Window,
 2722        cx: &mut Context<Workspace>,
 2723    ) -> Task<Result<()>> {
 2724        self.navigate_history_impl(
 2725            pane,
 2726            NavigationMode::Normal,
 2727            window,
 2728            &mut |history, _cx| history.pop_tag(mode),
 2729            cx,
 2730        )
 2731    }
 2732
 2733    fn navigate_history_impl(
 2734        &mut self,
 2735        pane: WeakEntity<Pane>,
 2736        mode: NavigationMode,
 2737        window: &mut Window,
 2738        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2739        cx: &mut Context<Workspace>,
 2740    ) -> Task<Result<()>> {
 2741        let to_load = if let Some(pane) = pane.upgrade() {
 2742            pane.update(cx, |pane, cx| {
 2743                window.focus(&pane.focus_handle(cx), cx);
 2744                loop {
 2745                    // Retrieve the weak item handle from the history.
 2746                    let entry = cb(pane.nav_history_mut(), cx)?;
 2747
 2748                    // If the item is still present in this pane, then activate it.
 2749                    if let Some(index) = entry
 2750                        .item
 2751                        .upgrade()
 2752                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2753                    {
 2754                        let prev_active_item_index = pane.active_item_index();
 2755                        pane.nav_history_mut().set_mode(mode);
 2756                        pane.activate_item(index, true, true, window, cx);
 2757                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2758
 2759                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2760                        if let Some(data) = entry.data {
 2761                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2762                        }
 2763
 2764                        if navigated {
 2765                            break None;
 2766                        }
 2767                    } else {
 2768                        // If the item is no longer present in this pane, then retrieve its
 2769                        // path info in order to reopen it.
 2770                        break pane
 2771                            .nav_history()
 2772                            .path_for_item(entry.item.id())
 2773                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2774                    }
 2775                }
 2776            })
 2777        } else {
 2778            None
 2779        };
 2780
 2781        if let Some((project_path, abs_path, entry)) = to_load {
 2782            // If the item was no longer present, then load it again from its previous path, first try the local path
 2783            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2784
 2785            cx.spawn_in(window, async move  |workspace, cx| {
 2786                let open_by_project_path = open_by_project_path.await;
 2787                let mut navigated = false;
 2788                match open_by_project_path
 2789                    .with_context(|| format!("Navigating to {project_path:?}"))
 2790                {
 2791                    Ok((project_entry_id, build_item)) => {
 2792                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2793                            pane.nav_history_mut().set_mode(mode);
 2794                            pane.active_item().map(|p| p.item_id())
 2795                        })?;
 2796
 2797                        pane.update_in(cx, |pane, window, cx| {
 2798                            let item = pane.open_item(
 2799                                project_entry_id,
 2800                                project_path,
 2801                                true,
 2802                                entry.is_preview,
 2803                                true,
 2804                                None,
 2805                                window, cx,
 2806                                build_item,
 2807                            );
 2808                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2809                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2810                            if let Some(data) = entry.data {
 2811                                navigated |= item.navigate(data, window, cx);
 2812                            }
 2813                        })?;
 2814                    }
 2815                    Err(open_by_project_path_e) => {
 2816                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2817                        // and its worktree is now dropped
 2818                        if let Some(abs_path) = abs_path {
 2819                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2820                                pane.nav_history_mut().set_mode(mode);
 2821                                pane.active_item().map(|p| p.item_id())
 2822                            })?;
 2823                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2824                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2825                            })?;
 2826                            match open_by_abs_path
 2827                                .await
 2828                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2829                            {
 2830                                Ok(item) => {
 2831                                    pane.update_in(cx, |pane, window, cx| {
 2832                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2833                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2834                                        if let Some(data) = entry.data {
 2835                                            navigated |= item.navigate(data, window, cx);
 2836                                        }
 2837                                    })?;
 2838                                }
 2839                                Err(open_by_abs_path_e) => {
 2840                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2841                                }
 2842                            }
 2843                        }
 2844                    }
 2845                }
 2846
 2847                if !navigated {
 2848                    workspace
 2849                        .update_in(cx, |workspace, window, cx| {
 2850                            Self::navigate_history(workspace, pane, mode, window, cx)
 2851                        })?
 2852                        .await?;
 2853                }
 2854
 2855                Ok(())
 2856            })
 2857        } else {
 2858            Task::ready(Ok(()))
 2859        }
 2860    }
 2861
 2862    pub fn go_back(
 2863        &mut self,
 2864        pane: WeakEntity<Pane>,
 2865        window: &mut Window,
 2866        cx: &mut Context<Workspace>,
 2867    ) -> Task<Result<()>> {
 2868        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2869    }
 2870
 2871    pub fn go_forward(
 2872        &mut self,
 2873        pane: WeakEntity<Pane>,
 2874        window: &mut Window,
 2875        cx: &mut Context<Workspace>,
 2876    ) -> Task<Result<()>> {
 2877        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2878    }
 2879
 2880    pub fn reopen_closed_item(
 2881        &mut self,
 2882        window: &mut Window,
 2883        cx: &mut Context<Workspace>,
 2884    ) -> Task<Result<()>> {
 2885        self.navigate_history(
 2886            self.active_pane().downgrade(),
 2887            NavigationMode::ReopeningClosedItem,
 2888            window,
 2889            cx,
 2890        )
 2891    }
 2892
 2893    pub fn client(&self) -> &Arc<Client> {
 2894        &self.app_state.client
 2895    }
 2896
 2897    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2898        self.titlebar_item = Some(item);
 2899        cx.notify();
 2900    }
 2901
 2902    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2903        self.on_prompt_for_new_path = Some(prompt)
 2904    }
 2905
 2906    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2907        self.on_prompt_for_open_path = Some(prompt)
 2908    }
 2909
 2910    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2911        self.terminal_provider = Some(Box::new(provider));
 2912    }
 2913
 2914    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2915        self.debugger_provider = Some(Arc::new(provider));
 2916    }
 2917
 2918    pub fn set_open_in_dev_container(&mut self, value: bool) {
 2919        self.open_in_dev_container = value;
 2920    }
 2921
 2922    pub fn open_in_dev_container(&self) -> bool {
 2923        self.open_in_dev_container
 2924    }
 2925
 2926    pub fn set_dev_container_task(&mut self, task: Task<Result<()>>) {
 2927        self._dev_container_task = Some(task);
 2928    }
 2929
 2930    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2931        self.debugger_provider.clone()
 2932    }
 2933
 2934    pub fn prompt_for_open_path(
 2935        &mut self,
 2936        path_prompt_options: PathPromptOptions,
 2937        lister: DirectoryLister,
 2938        window: &mut Window,
 2939        cx: &mut Context<Self>,
 2940    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2941        // TODO: If `on_prompt_for_open_path` is set, we should always use it
 2942        // rather than gating on `use_system_path_prompts`. This would let tests
 2943        // inject a mock without also having to disable the setting.
 2944        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2945            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2946            let rx = prompt(self, lister, window, cx);
 2947            self.on_prompt_for_open_path = Some(prompt);
 2948            rx
 2949        } else {
 2950            let (tx, rx) = oneshot::channel();
 2951            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2952
 2953            cx.spawn_in(window, async move |workspace, cx| {
 2954                let Ok(result) = abs_path.await else {
 2955                    return Ok(());
 2956                };
 2957
 2958                match result {
 2959                    Ok(result) => {
 2960                        tx.send(result).ok();
 2961                    }
 2962                    Err(err) => {
 2963                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2964                            workspace.show_portal_error(err.to_string(), cx);
 2965                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2966                            let rx = prompt(workspace, lister, window, cx);
 2967                            workspace.on_prompt_for_open_path = Some(prompt);
 2968                            rx
 2969                        })?;
 2970                        if let Ok(path) = rx.await {
 2971                            tx.send(path).ok();
 2972                        }
 2973                    }
 2974                };
 2975                anyhow::Ok(())
 2976            })
 2977            .detach();
 2978
 2979            rx
 2980        }
 2981    }
 2982
 2983    pub fn prompt_for_new_path(
 2984        &mut self,
 2985        lister: DirectoryLister,
 2986        suggested_name: Option<String>,
 2987        window: &mut Window,
 2988        cx: &mut Context<Self>,
 2989    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2990        if self.project.read(cx).is_via_collab()
 2991            || self.project.read(cx).is_via_remote_server()
 2992            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2993        {
 2994            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2995            let rx = prompt(self, lister, suggested_name, window, cx);
 2996            self.on_prompt_for_new_path = Some(prompt);
 2997            return rx;
 2998        }
 2999
 3000        let (tx, rx) = oneshot::channel();
 3001        cx.spawn_in(window, async move |workspace, cx| {
 3002            let abs_path = workspace.update(cx, |workspace, cx| {
 3003                let relative_to = workspace
 3004                    .most_recent_active_path(cx)
 3005                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 3006                    .or_else(|| {
 3007                        let project = workspace.project.read(cx);
 3008                        project.visible_worktrees(cx).find_map(|worktree| {
 3009                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 3010                        })
 3011                    })
 3012                    .or_else(std::env::home_dir)
 3013                    .unwrap_or_else(|| PathBuf::from(""));
 3014                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 3015            })?;
 3016            let abs_path = match abs_path.await? {
 3017                Ok(path) => path,
 3018                Err(err) => {
 3019                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 3020                        workspace.show_portal_error(err.to_string(), cx);
 3021
 3022                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 3023                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 3024                        workspace.on_prompt_for_new_path = Some(prompt);
 3025                        rx
 3026                    })?;
 3027                    if let Ok(path) = rx.await {
 3028                        tx.send(path).ok();
 3029                    }
 3030                    return anyhow::Ok(());
 3031                }
 3032            };
 3033
 3034            tx.send(abs_path.map(|path| vec![path])).ok();
 3035            anyhow::Ok(())
 3036        })
 3037        .detach();
 3038
 3039        rx
 3040    }
 3041
 3042    pub fn titlebar_item(&self) -> Option<AnyView> {
 3043        self.titlebar_item.clone()
 3044    }
 3045
 3046    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 3047    ///
 3048    /// If the given workspace has a local project, then it will be passed
 3049    /// to the callback. Otherwise, a new empty window will be created.
 3050    pub fn with_local_workspace<T, F>(
 3051        &mut self,
 3052        window: &mut Window,
 3053        cx: &mut Context<Self>,
 3054        callback: F,
 3055    ) -> Task<Result<T>>
 3056    where
 3057        T: 'static,
 3058        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 3059    {
 3060        if self.project.read(cx).is_local() {
 3061            Task::ready(Ok(callback(self, window, cx)))
 3062        } else {
 3063            let env = self.project.read(cx).cli_environment(cx);
 3064            let task = Self::new_local(
 3065                Vec::new(),
 3066                self.app_state.clone(),
 3067                None,
 3068                env,
 3069                None,
 3070                OpenMode::Activate,
 3071                cx,
 3072            );
 3073            cx.spawn_in(window, async move |_vh, cx| {
 3074                let OpenResult {
 3075                    window: multi_workspace_window,
 3076                    ..
 3077                } = task.await?;
 3078                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 3079                    let workspace = multi_workspace.workspace().clone();
 3080                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 3081                })
 3082            })
 3083        }
 3084    }
 3085
 3086    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 3087    ///
 3088    /// If the given workspace has a local project, then it will be passed
 3089    /// to the callback. Otherwise, a new empty window will be created.
 3090    pub fn with_local_or_wsl_workspace<T, F>(
 3091        &mut self,
 3092        window: &mut Window,
 3093        cx: &mut Context<Self>,
 3094        callback: F,
 3095    ) -> Task<Result<T>>
 3096    where
 3097        T: 'static,
 3098        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 3099    {
 3100        let project = self.project.read(cx);
 3101        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 3102            Task::ready(Ok(callback(self, window, cx)))
 3103        } else {
 3104            let env = self.project.read(cx).cli_environment(cx);
 3105            let task = Self::new_local(
 3106                Vec::new(),
 3107                self.app_state.clone(),
 3108                None,
 3109                env,
 3110                None,
 3111                OpenMode::Activate,
 3112                cx,
 3113            );
 3114            cx.spawn_in(window, async move |_vh, cx| {
 3115                let OpenResult {
 3116                    window: multi_workspace_window,
 3117                    ..
 3118                } = task.await?;
 3119                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 3120                    let workspace = multi_workspace.workspace().clone();
 3121                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 3122                })
 3123            })
 3124        }
 3125    }
 3126
 3127    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3128        self.project.read(cx).worktrees(cx)
 3129    }
 3130
 3131    pub fn visible_worktrees<'a>(
 3132        &self,
 3133        cx: &'a App,
 3134    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 3135        self.project.read(cx).visible_worktrees(cx)
 3136    }
 3137
 3138    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 3139        let futures = self
 3140            .worktrees(cx)
 3141            .filter_map(|worktree| worktree.read(cx).as_local())
 3142            .map(|worktree| worktree.scan_complete())
 3143            .collect::<Vec<_>>();
 3144        async move {
 3145            for future in futures {
 3146                future.await;
 3147            }
 3148        }
 3149    }
 3150
 3151    pub fn close_global(cx: &mut App) {
 3152        cx.defer(|cx| {
 3153            cx.windows().iter().find(|window| {
 3154                window
 3155                    .update(cx, |_, window, _| {
 3156                        if window.is_window_active() {
 3157                            //This can only get called when the window's project connection has been lost
 3158                            //so we don't need to prompt the user for anything and instead just close the window
 3159                            window.remove_window();
 3160                            true
 3161                        } else {
 3162                            false
 3163                        }
 3164                    })
 3165                    .unwrap_or(false)
 3166            });
 3167        });
 3168    }
 3169
 3170    pub fn move_focused_panel_to_next_position(
 3171        &mut self,
 3172        _: &MoveFocusedPanelToNextPosition,
 3173        window: &mut Window,
 3174        cx: &mut Context<Self>,
 3175    ) {
 3176        let docks = self.all_docks();
 3177        let active_dock = docks
 3178            .into_iter()
 3179            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 3180
 3181        if let Some(dock) = active_dock {
 3182            dock.update(cx, |dock, cx| {
 3183                let active_panel = dock
 3184                    .active_panel()
 3185                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 3186
 3187                if let Some(panel) = active_panel {
 3188                    panel.move_to_next_position(window, cx);
 3189                }
 3190            })
 3191        }
 3192    }
 3193
 3194    pub fn prepare_to_close(
 3195        &mut self,
 3196        close_intent: CloseIntent,
 3197        window: &mut Window,
 3198        cx: &mut Context<Self>,
 3199    ) -> Task<Result<bool>> {
 3200        let active_call = self.active_global_call();
 3201
 3202        cx.spawn_in(window, async move |this, cx| {
 3203            this.update(cx, |this, _| {
 3204                if close_intent == CloseIntent::CloseWindow {
 3205                    this.removing = true;
 3206                }
 3207            })?;
 3208
 3209            let workspace_count = cx.update(|_window, cx| {
 3210                cx.windows()
 3211                    .iter()
 3212                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 3213                    .count()
 3214            })?;
 3215
 3216            #[cfg(target_os = "macos")]
 3217            let save_last_workspace = false;
 3218
 3219            // On Linux and Windows, closing the last window should restore the last workspace.
 3220            #[cfg(not(target_os = "macos"))]
 3221            let save_last_workspace = {
 3222                let remaining_workspaces = cx.update(|_window, cx| {
 3223                    cx.windows()
 3224                        .iter()
 3225                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 3226                        .filter_map(|multi_workspace| {
 3227                            multi_workspace
 3228                                .update(cx, |multi_workspace, _, cx| {
 3229                                    multi_workspace.workspace().read(cx).removing
 3230                                })
 3231                                .ok()
 3232                        })
 3233                        .filter(|removing| !removing)
 3234                        .count()
 3235                })?;
 3236
 3237                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 3238            };
 3239
 3240            if let Some(active_call) = active_call
 3241                && workspace_count == 1
 3242                && cx
 3243                    .update(|_window, cx| active_call.0.is_in_room(cx))
 3244                    .unwrap_or(false)
 3245            {
 3246                if close_intent == CloseIntent::CloseWindow {
 3247                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3248                    let answer = cx.update(|window, cx| {
 3249                        window.prompt(
 3250                            PromptLevel::Warning,
 3251                            "Do you want to leave the current call?",
 3252                            None,
 3253                            &["Close window and hang up", "Cancel"],
 3254                            cx,
 3255                        )
 3256                    })?;
 3257
 3258                    if answer.await.log_err() == Some(1) {
 3259                        return anyhow::Ok(false);
 3260                    } else {
 3261                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 3262                            task.await.log_err();
 3263                        }
 3264                    }
 3265                }
 3266                if close_intent == CloseIntent::ReplaceWindow {
 3267                    _ = cx.update(|_window, cx| {
 3268                        let multi_workspace = cx
 3269                            .windows()
 3270                            .iter()
 3271                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 3272                            .next()
 3273                            .unwrap();
 3274                        let project = multi_workspace
 3275                            .read(cx)?
 3276                            .workspace()
 3277                            .read(cx)
 3278                            .project
 3279                            .clone();
 3280                        if project.read(cx).is_shared() {
 3281                            active_call.0.unshare_project(project, cx)?;
 3282                        }
 3283                        Ok::<_, anyhow::Error>(())
 3284                    });
 3285                }
 3286            }
 3287
 3288            let save_result = this
 3289                .update_in(cx, |this, window, cx| {
 3290                    this.save_all_internal(SaveIntent::Close, window, cx)
 3291                })?
 3292                .await;
 3293
 3294            // If we're not quitting, but closing, we remove the workspace from
 3295            // the current session.
 3296            if close_intent != CloseIntent::Quit
 3297                && !save_last_workspace
 3298                && save_result.as_ref().is_ok_and(|&res| res)
 3299            {
 3300                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 3301                    .await;
 3302            }
 3303
 3304            save_result
 3305        })
 3306    }
 3307
 3308    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 3309        self.save_all_internal(
 3310            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 3311            window,
 3312            cx,
 3313        )
 3314        .detach_and_log_err(cx);
 3315    }
 3316
 3317    fn send_keystrokes(
 3318        &mut self,
 3319        action: &SendKeystrokes,
 3320        window: &mut Window,
 3321        cx: &mut Context<Self>,
 3322    ) {
 3323        let keystrokes: Vec<Keystroke> = action
 3324            .0
 3325            .split(' ')
 3326            .flat_map(|k| Keystroke::parse(k).log_err())
 3327            .map(|k| {
 3328                cx.keyboard_mapper()
 3329                    .map_key_equivalent(k, false)
 3330                    .inner()
 3331                    .clone()
 3332            })
 3333            .collect();
 3334        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 3335    }
 3336
 3337    pub fn send_keystrokes_impl(
 3338        &mut self,
 3339        keystrokes: Vec<Keystroke>,
 3340        window: &mut Window,
 3341        cx: &mut Context<Self>,
 3342    ) -> Shared<Task<()>> {
 3343        let mut state = self.dispatching_keystrokes.borrow_mut();
 3344        if !state.dispatched.insert(keystrokes.clone()) {
 3345            cx.propagate();
 3346            return state.task.clone().unwrap();
 3347        }
 3348
 3349        state.queue.extend(keystrokes);
 3350
 3351        let keystrokes = self.dispatching_keystrokes.clone();
 3352        if state.task.is_none() {
 3353            state.task = Some(
 3354                window
 3355                    .spawn(cx, async move |cx| {
 3356                        // limit to 100 keystrokes to avoid infinite recursion.
 3357                        for _ in 0..100 {
 3358                            let keystroke = {
 3359                                let mut state = keystrokes.borrow_mut();
 3360                                let Some(keystroke) = state.queue.pop_front() else {
 3361                                    state.dispatched.clear();
 3362                                    state.task.take();
 3363                                    return;
 3364                                };
 3365                                keystroke
 3366                            };
 3367                            let focus_changed = cx
 3368                                .update(|window, cx| {
 3369                                    let focused = window.focused(cx);
 3370                                    window.dispatch_keystroke(keystroke.clone(), cx);
 3371                                    if window.focused(cx) != focused {
 3372                                        // dispatch_keystroke may cause the focus to change.
 3373                                        // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3374                                        // And we need that to happen before the next keystroke to keep vim mode happy...
 3375                                        // (Note that the tests always do this implicitly, so you must manually test with something like:
 3376                                        //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3377                                        // )
 3378                                        window.draw(cx).clear();
 3379                                        return true;
 3380                                    }
 3381                                    false
 3382                                })
 3383                                .unwrap_or(false);
 3384
 3385                            if focus_changed {
 3386                                yield_now().await;
 3387                            }
 3388                        }
 3389
 3390                        *keystrokes.borrow_mut() = Default::default();
 3391                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3392                    })
 3393                    .shared(),
 3394            );
 3395        }
 3396        state.task.clone().unwrap()
 3397    }
 3398
 3399    /// Prompts the user to save or discard each dirty item, returning
 3400    /// `true` if they confirmed (saved/discarded everything) or `false`
 3401    /// if they cancelled. Used before removing worktree roots during
 3402    /// thread archival.
 3403    pub fn prompt_to_save_or_discard_dirty_items(
 3404        &mut self,
 3405        window: &mut Window,
 3406        cx: &mut Context<Self>,
 3407    ) -> Task<Result<bool>> {
 3408        self.save_all_internal(SaveIntent::Close, window, cx)
 3409    }
 3410
 3411    fn save_all_internal(
 3412        &mut self,
 3413        mut save_intent: SaveIntent,
 3414        window: &mut Window,
 3415        cx: &mut Context<Self>,
 3416    ) -> Task<Result<bool>> {
 3417        if self.project.read(cx).is_disconnected(cx) {
 3418            return Task::ready(Ok(true));
 3419        }
 3420        let dirty_items = self
 3421            .panes
 3422            .iter()
 3423            .flat_map(|pane| {
 3424                pane.read(cx).items().filter_map(|item| {
 3425                    if item.is_dirty(cx) {
 3426                        item.tab_content_text(0, cx);
 3427                        Some((pane.downgrade(), item.boxed_clone()))
 3428                    } else {
 3429                        None
 3430                    }
 3431                })
 3432            })
 3433            .collect::<Vec<_>>();
 3434
 3435        let project = self.project.clone();
 3436        cx.spawn_in(window, async move |workspace, cx| {
 3437            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3438                let (serialize_tasks, remaining_dirty_items) =
 3439                    workspace.update_in(cx, |workspace, window, cx| {
 3440                        let mut remaining_dirty_items = Vec::new();
 3441                        let mut serialize_tasks = Vec::new();
 3442                        for (pane, item) in dirty_items {
 3443                            if let Some(task) = item
 3444                                .to_serializable_item_handle(cx)
 3445                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3446                            {
 3447                                serialize_tasks.push(task);
 3448                            } else {
 3449                                remaining_dirty_items.push((pane, item));
 3450                            }
 3451                        }
 3452                        (serialize_tasks, remaining_dirty_items)
 3453                    })?;
 3454
 3455                futures::future::try_join_all(serialize_tasks).await?;
 3456
 3457                if !remaining_dirty_items.is_empty() {
 3458                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3459                }
 3460
 3461                if remaining_dirty_items.len() > 1 {
 3462                    let answer = workspace.update_in(cx, |_, window, cx| {
 3463                        cx.emit(Event::Activate);
 3464                        let detail = Pane::file_names_for_prompt(
 3465                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3466                            cx,
 3467                        );
 3468                        window.prompt(
 3469                            PromptLevel::Warning,
 3470                            "Do you want to save all changes in the following files?",
 3471                            Some(&detail),
 3472                            &["Save all", "Discard all", "Cancel"],
 3473                            cx,
 3474                        )
 3475                    })?;
 3476                    match answer.await.log_err() {
 3477                        Some(0) => save_intent = SaveIntent::SaveAll,
 3478                        Some(1) => save_intent = SaveIntent::Skip,
 3479                        Some(2) => return Ok(false),
 3480                        _ => {}
 3481                    }
 3482                }
 3483
 3484                remaining_dirty_items
 3485            } else {
 3486                dirty_items
 3487            };
 3488
 3489            for (pane, item) in dirty_items {
 3490                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3491                    (
 3492                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3493                        item.project_entry_ids(cx),
 3494                    )
 3495                })?;
 3496                if (singleton || !project_entry_ids.is_empty())
 3497                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3498                {
 3499                    return Ok(false);
 3500                }
 3501            }
 3502            Ok(true)
 3503        })
 3504    }
 3505
 3506    pub fn open_workspace_for_paths(
 3507        &mut self,
 3508        // replace_current_window: bool,
 3509        mut open_mode: OpenMode,
 3510        paths: Vec<PathBuf>,
 3511        window: &mut Window,
 3512        cx: &mut Context<Self>,
 3513    ) -> Task<Result<Entity<Workspace>>> {
 3514        let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
 3515        let is_remote = self.project.read(cx).is_via_collab();
 3516        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3517        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3518
 3519        let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
 3520        if workspace_is_empty {
 3521            open_mode = OpenMode::Activate;
 3522        }
 3523
 3524        let app_state = self.app_state.clone();
 3525
 3526        cx.spawn(async move |_, cx| {
 3527            let OpenResult { workspace, .. } = cx
 3528                .update(|cx| {
 3529                    open_paths(
 3530                        &paths,
 3531                        app_state,
 3532                        OpenOptions {
 3533                            requesting_window,
 3534                            open_mode,
 3535                            workspace_matching: if open_mode == OpenMode::NewWindow {
 3536                                WorkspaceMatching::None
 3537                            } else {
 3538                                WorkspaceMatching::default()
 3539                            },
 3540                            ..Default::default()
 3541                        },
 3542                        cx,
 3543                    )
 3544                })
 3545                .await?;
 3546            Ok(workspace)
 3547        })
 3548    }
 3549
 3550    #[allow(clippy::type_complexity)]
 3551    pub fn open_paths(
 3552        &mut self,
 3553        mut abs_paths: Vec<PathBuf>,
 3554        options: OpenOptions,
 3555        pane: Option<WeakEntity<Pane>>,
 3556        window: &mut Window,
 3557        cx: &mut Context<Self>,
 3558    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3559        let fs = self.app_state.fs.clone();
 3560
 3561        let caller_ordered_abs_paths = abs_paths.clone();
 3562
 3563        // Sort the paths to ensure we add worktrees for parents before their children.
 3564        abs_paths.sort_unstable();
 3565        cx.spawn_in(window, async move |this, cx| {
 3566            let mut tasks = Vec::with_capacity(abs_paths.len());
 3567
 3568            for abs_path in &abs_paths {
 3569                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3570                    OpenVisible::All => Some(true),
 3571                    OpenVisible::None => Some(false),
 3572                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3573                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3574                        Some(None) => Some(true),
 3575                        None => None,
 3576                    },
 3577                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3578                        Some(Some(metadata)) => Some(metadata.is_dir),
 3579                        Some(None) => Some(false),
 3580                        None => None,
 3581                    },
 3582                };
 3583                let project_path = match visible {
 3584                    Some(visible) => match this
 3585                        .update(cx, |this, cx| {
 3586                            Workspace::project_path_for_path(
 3587                                this.project.clone(),
 3588                                abs_path,
 3589                                visible,
 3590                                cx,
 3591                            )
 3592                        })
 3593                        .log_err()
 3594                    {
 3595                        Some(project_path) => project_path.await.log_err(),
 3596                        None => None,
 3597                    },
 3598                    None => None,
 3599                };
 3600
 3601                let this = this.clone();
 3602                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3603                let fs = fs.clone();
 3604                let pane = pane.clone();
 3605                let task = cx.spawn(async move |cx| {
 3606                    let (_worktree, project_path) = project_path?;
 3607                    if fs.is_dir(&abs_path).await {
 3608                        // Opening a directory should not race to update the active entry.
 3609                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3610                        None
 3611                    } else {
 3612                        Some(
 3613                            this.update_in(cx, |this, window, cx| {
 3614                                this.open_path(
 3615                                    project_path,
 3616                                    pane,
 3617                                    options.focus.unwrap_or(true),
 3618                                    window,
 3619                                    cx,
 3620                                )
 3621                            })
 3622                            .ok()?
 3623                            .await,
 3624                        )
 3625                    }
 3626                });
 3627                tasks.push(task);
 3628            }
 3629
 3630            let results = futures::future::join_all(tasks).await;
 3631
 3632            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3633            let mut winner: Option<(PathBuf, bool)> = None;
 3634            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3635                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3636                    if !metadata.is_dir {
 3637                        winner = Some((abs_path, false));
 3638                        break;
 3639                    }
 3640                    if winner.is_none() {
 3641                        winner = Some((abs_path, true));
 3642                    }
 3643                } else if winner.is_none() {
 3644                    winner = Some((abs_path, false));
 3645                }
 3646            }
 3647
 3648            // Compute the winner entry id on the foreground thread and emit once, after all
 3649            // paths finish opening. This avoids races between concurrently-opening paths
 3650            // (directories in particular) and makes the resulting project panel selection
 3651            // deterministic.
 3652            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3653                'emit_winner: {
 3654                    let winner_abs_path: Arc<Path> =
 3655                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3656
 3657                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3658                        OpenVisible::All => true,
 3659                        OpenVisible::None => false,
 3660                        OpenVisible::OnlyFiles => !winner_is_dir,
 3661                        OpenVisible::OnlyDirectories => winner_is_dir,
 3662                    };
 3663
 3664                    let Some(worktree_task) = this
 3665                        .update(cx, |workspace, cx| {
 3666                            workspace.project.update(cx, |project, cx| {
 3667                                project.find_or_create_worktree(
 3668                                    winner_abs_path.as_ref(),
 3669                                    visible,
 3670                                    cx,
 3671                                )
 3672                            })
 3673                        })
 3674                        .ok()
 3675                    else {
 3676                        break 'emit_winner;
 3677                    };
 3678
 3679                    let Ok((worktree, _)) = worktree_task.await else {
 3680                        break 'emit_winner;
 3681                    };
 3682
 3683                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3684                        let worktree = worktree.read(cx);
 3685                        let worktree_abs_path = worktree.abs_path();
 3686                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3687                            worktree.root_entry()
 3688                        } else {
 3689                            winner_abs_path
 3690                                .strip_prefix(worktree_abs_path.as_ref())
 3691                                .ok()
 3692                                .and_then(|relative_path| {
 3693                                    let relative_path =
 3694                                        RelPath::new(relative_path, PathStyle::local())
 3695                                            .log_err()?;
 3696                                    worktree.entry_for_path(&relative_path)
 3697                                })
 3698                        }?;
 3699                        Some(entry.id)
 3700                    }) else {
 3701                        break 'emit_winner;
 3702                    };
 3703
 3704                    this.update(cx, |workspace, cx| {
 3705                        workspace.project.update(cx, |_, cx| {
 3706                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3707                        });
 3708                    })
 3709                    .ok();
 3710                }
 3711            }
 3712
 3713            results
 3714        })
 3715    }
 3716
 3717    pub fn open_resolved_path(
 3718        &mut self,
 3719        path: ResolvedPath,
 3720        window: &mut Window,
 3721        cx: &mut Context<Self>,
 3722    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3723        match path {
 3724            ResolvedPath::ProjectPath { project_path, .. } => {
 3725                self.open_path(project_path, None, true, window, cx)
 3726            }
 3727            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3728                PathBuf::from(path),
 3729                OpenOptions {
 3730                    visible: Some(OpenVisible::None),
 3731                    ..Default::default()
 3732                },
 3733                window,
 3734                cx,
 3735            ),
 3736        }
 3737    }
 3738
 3739    pub fn absolute_path_of_worktree(
 3740        &self,
 3741        worktree_id: WorktreeId,
 3742        cx: &mut Context<Self>,
 3743    ) -> Option<PathBuf> {
 3744        self.project
 3745            .read(cx)
 3746            .worktree_for_id(worktree_id, cx)
 3747            // TODO: use `abs_path` or `root_dir`
 3748            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3749    }
 3750
 3751    pub fn add_folder_to_project(
 3752        &mut self,
 3753        _: &AddFolderToProject,
 3754        window: &mut Window,
 3755        cx: &mut Context<Self>,
 3756    ) {
 3757        let project = self.project.read(cx);
 3758        if project.is_via_collab() {
 3759            self.show_error(
 3760                &anyhow!("You cannot add folders to someone else's project"),
 3761                cx,
 3762            );
 3763            return;
 3764        }
 3765        let paths = self.prompt_for_open_path(
 3766            PathPromptOptions {
 3767                files: false,
 3768                directories: true,
 3769                multiple: true,
 3770                prompt: None,
 3771            },
 3772            DirectoryLister::Project(self.project.clone()),
 3773            window,
 3774            cx,
 3775        );
 3776        cx.spawn_in(window, async move |this, cx| {
 3777            if let Some(paths) = paths.await.log_err().flatten() {
 3778                let results = this
 3779                    .update_in(cx, |this, window, cx| {
 3780                        this.open_paths(
 3781                            paths,
 3782                            OpenOptions {
 3783                                visible: Some(OpenVisible::All),
 3784                                ..Default::default()
 3785                            },
 3786                            None,
 3787                            window,
 3788                            cx,
 3789                        )
 3790                    })?
 3791                    .await;
 3792                for result in results.into_iter().flatten() {
 3793                    result.log_err();
 3794                }
 3795            }
 3796            anyhow::Ok(())
 3797        })
 3798        .detach_and_log_err(cx);
 3799    }
 3800
 3801    pub fn project_path_for_path(
 3802        project: Entity<Project>,
 3803        abs_path: &Path,
 3804        visible: bool,
 3805        cx: &mut App,
 3806    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3807        let entry = project.update(cx, |project, cx| {
 3808            project.find_or_create_worktree(abs_path, visible, cx)
 3809        });
 3810        cx.spawn(async move |cx| {
 3811            let (worktree, path) = entry.await?;
 3812            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3813            Ok((worktree, ProjectPath { worktree_id, path }))
 3814        })
 3815    }
 3816
 3817    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3818        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3819    }
 3820
 3821    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3822        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3823    }
 3824
 3825    pub fn items_of_type<'a, T: Item>(
 3826        &'a self,
 3827        cx: &'a App,
 3828    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3829        self.panes
 3830            .iter()
 3831            .flat_map(|pane| pane.read(cx).items_of_type())
 3832    }
 3833
 3834    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3835        self.active_pane().read(cx).active_item()
 3836    }
 3837
 3838    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3839        let item = self.active_item(cx)?;
 3840        item.to_any_view().downcast::<I>().ok()
 3841    }
 3842
 3843    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3844        self.active_item(cx).and_then(|item| item.project_path(cx))
 3845    }
 3846
 3847    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3848        self.recent_navigation_history_iter(cx)
 3849            .filter_map(|(path, abs_path)| {
 3850                let worktree = self
 3851                    .project
 3852                    .read(cx)
 3853                    .worktree_for_id(path.worktree_id, cx)?;
 3854                if !worktree.read(cx).is_visible() {
 3855                    return None;
 3856                }
 3857                let settings_location = SettingsLocation {
 3858                    worktree_id: path.worktree_id,
 3859                    path: &path.path,
 3860                };
 3861                if WorktreeSettings::get(Some(settings_location), cx).is_path_read_only(&path.path)
 3862                {
 3863                    return None;
 3864                }
 3865                abs_path
 3866            })
 3867            .next()
 3868    }
 3869
 3870    pub fn save_active_item(
 3871        &mut self,
 3872        save_intent: SaveIntent,
 3873        window: &mut Window,
 3874        cx: &mut App,
 3875    ) -> Task<Result<()>> {
 3876        let project = self.project.clone();
 3877        let pane = self.active_pane();
 3878        let item = pane.read(cx).active_item();
 3879        let pane = pane.downgrade();
 3880
 3881        window.spawn(cx, async move |cx| {
 3882            if let Some(item) = item {
 3883                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3884                    .await
 3885                    .map(|_| ())
 3886            } else {
 3887                Ok(())
 3888            }
 3889        })
 3890    }
 3891
 3892    pub fn close_inactive_items_and_panes(
 3893        &mut self,
 3894        action: &CloseInactiveTabsAndPanes,
 3895        window: &mut Window,
 3896        cx: &mut Context<Self>,
 3897    ) {
 3898        if let Some(task) = self.close_all_internal(
 3899            true,
 3900            action.save_intent.unwrap_or(SaveIntent::Close),
 3901            window,
 3902            cx,
 3903        ) {
 3904            task.detach_and_log_err(cx)
 3905        }
 3906    }
 3907
 3908    pub fn close_all_items_and_panes(
 3909        &mut self,
 3910        action: &CloseAllItemsAndPanes,
 3911        window: &mut Window,
 3912        cx: &mut Context<Self>,
 3913    ) {
 3914        if let Some(task) = self.close_all_internal(
 3915            false,
 3916            action.save_intent.unwrap_or(SaveIntent::Close),
 3917            window,
 3918            cx,
 3919        ) {
 3920            task.detach_and_log_err(cx)
 3921        }
 3922    }
 3923
 3924    /// Closes the active item across all panes.
 3925    pub fn close_item_in_all_panes(
 3926        &mut self,
 3927        action: &CloseItemInAllPanes,
 3928        window: &mut Window,
 3929        cx: &mut Context<Self>,
 3930    ) {
 3931        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3932            return;
 3933        };
 3934
 3935        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3936        let close_pinned = action.close_pinned;
 3937
 3938        if let Some(project_path) = active_item.project_path(cx) {
 3939            self.close_items_with_project_path(
 3940                &project_path,
 3941                save_intent,
 3942                close_pinned,
 3943                window,
 3944                cx,
 3945            );
 3946        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3947            let item_id = active_item.item_id();
 3948            self.active_pane().update(cx, |pane, cx| {
 3949                pane.close_item_by_id(item_id, save_intent, window, cx)
 3950                    .detach_and_log_err(cx);
 3951            });
 3952        }
 3953    }
 3954
 3955    /// Closes all items with the given project path across all panes.
 3956    pub fn close_items_with_project_path(
 3957        &mut self,
 3958        project_path: &ProjectPath,
 3959        save_intent: SaveIntent,
 3960        close_pinned: bool,
 3961        window: &mut Window,
 3962        cx: &mut Context<Self>,
 3963    ) {
 3964        let panes = self.panes().to_vec();
 3965        for pane in panes {
 3966            pane.update(cx, |pane, cx| {
 3967                pane.close_items_for_project_path(
 3968                    project_path,
 3969                    save_intent,
 3970                    close_pinned,
 3971                    window,
 3972                    cx,
 3973                )
 3974                .detach_and_log_err(cx);
 3975            });
 3976        }
 3977    }
 3978
 3979    fn close_all_internal(
 3980        &mut self,
 3981        retain_active_pane: bool,
 3982        save_intent: SaveIntent,
 3983        window: &mut Window,
 3984        cx: &mut Context<Self>,
 3985    ) -> Option<Task<Result<()>>> {
 3986        let current_pane = self.active_pane();
 3987
 3988        let mut tasks = Vec::new();
 3989
 3990        if retain_active_pane {
 3991            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3992                pane.close_other_items(
 3993                    &CloseOtherItems {
 3994                        save_intent: None,
 3995                        close_pinned: false,
 3996                    },
 3997                    None,
 3998                    window,
 3999                    cx,
 4000                )
 4001            });
 4002
 4003            tasks.push(current_pane_close);
 4004        }
 4005
 4006        for pane in self.panes() {
 4007            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 4008                continue;
 4009            }
 4010
 4011            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 4012                pane.close_all_items(
 4013                    &CloseAllItems {
 4014                        save_intent: Some(save_intent),
 4015                        close_pinned: false,
 4016                    },
 4017                    window,
 4018                    cx,
 4019                )
 4020            });
 4021
 4022            tasks.push(close_pane_items)
 4023        }
 4024
 4025        if tasks.is_empty() {
 4026            None
 4027        } else {
 4028            Some(cx.spawn_in(window, async move |_, _| {
 4029                for task in tasks {
 4030                    task.await?
 4031                }
 4032                Ok(())
 4033            }))
 4034        }
 4035    }
 4036
 4037    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 4038        self.dock_at_position(position).read(cx).is_open()
 4039    }
 4040
 4041    pub fn toggle_dock(
 4042        &mut self,
 4043        dock_side: DockPosition,
 4044        window: &mut Window,
 4045        cx: &mut Context<Self>,
 4046    ) {
 4047        let mut focus_center = false;
 4048        let mut reveal_dock = false;
 4049
 4050        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 4051        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 4052
 4053        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 4054            telemetry::event!(
 4055                "Panel Button Clicked",
 4056                name = panel.persistent_name(),
 4057                toggle_state = !was_visible
 4058            );
 4059        }
 4060        if was_visible {
 4061            self.save_open_dock_positions(cx);
 4062        }
 4063
 4064        let dock = self.dock_at_position(dock_side);
 4065        dock.update(cx, |dock, cx| {
 4066            dock.set_open(!was_visible, window, cx);
 4067
 4068            if dock.active_panel().is_none() {
 4069                let Some(panel_ix) = dock
 4070                    .first_enabled_panel_idx(cx)
 4071                    .log_with_level(log::Level::Info)
 4072                else {
 4073                    return;
 4074                };
 4075                dock.activate_panel(panel_ix, window, cx);
 4076            }
 4077
 4078            if let Some(active_panel) = dock.active_panel() {
 4079                if was_visible {
 4080                    if active_panel
 4081                        .panel_focus_handle(cx)
 4082                        .contains_focused(window, cx)
 4083                    {
 4084                        focus_center = true;
 4085                    }
 4086                } else {
 4087                    let focus_handle = &active_panel.panel_focus_handle(cx);
 4088                    window.focus(focus_handle, cx);
 4089                    reveal_dock = true;
 4090                }
 4091            }
 4092        });
 4093
 4094        if reveal_dock {
 4095            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 4096        }
 4097
 4098        if focus_center {
 4099            self.active_pane
 4100                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4101        }
 4102
 4103        cx.notify();
 4104        self.serialize_workspace(window, cx);
 4105    }
 4106
 4107    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 4108        self.all_docks().into_iter().find(|&dock| {
 4109            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 4110        })
 4111    }
 4112
 4113    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 4114        if let Some(dock) = self.active_dock(window, cx).cloned() {
 4115            self.save_open_dock_positions(cx);
 4116            dock.update(cx, |dock, cx| {
 4117                dock.set_open(false, window, cx);
 4118            });
 4119            return true;
 4120        }
 4121        false
 4122    }
 4123
 4124    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4125        self.save_open_dock_positions(cx);
 4126        for dock in self.all_docks() {
 4127            dock.update(cx, |dock, cx| {
 4128                dock.set_open(false, window, cx);
 4129            });
 4130        }
 4131
 4132        cx.focus_self(window);
 4133        cx.notify();
 4134        self.serialize_workspace(window, cx);
 4135    }
 4136
 4137    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 4138        self.all_docks()
 4139            .into_iter()
 4140            .filter_map(|dock| {
 4141                let dock_ref = dock.read(cx);
 4142                if dock_ref.is_open() {
 4143                    Some(dock_ref.position())
 4144                } else {
 4145                    None
 4146                }
 4147            })
 4148            .collect()
 4149    }
 4150
 4151    /// Saves the positions of currently open docks.
 4152    ///
 4153    /// Updates `last_open_dock_positions` with positions of all currently open
 4154    /// docks, to later be restored by the 'Toggle All Docks' action.
 4155    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 4156        let open_dock_positions = self.get_open_dock_positions(cx);
 4157        if !open_dock_positions.is_empty() {
 4158            self.last_open_dock_positions = open_dock_positions;
 4159        }
 4160    }
 4161
 4162    /// Toggles all docks between open and closed states.
 4163    ///
 4164    /// If any docks are open, closes all and remembers their positions. If all
 4165    /// docks are closed, restores the last remembered dock configuration.
 4166    fn toggle_all_docks(
 4167        &mut self,
 4168        _: &ToggleAllDocks,
 4169        window: &mut Window,
 4170        cx: &mut Context<Self>,
 4171    ) {
 4172        let open_dock_positions = self.get_open_dock_positions(cx);
 4173
 4174        if !open_dock_positions.is_empty() {
 4175            self.close_all_docks(window, cx);
 4176        } else if !self.last_open_dock_positions.is_empty() {
 4177            self.restore_last_open_docks(window, cx);
 4178        }
 4179    }
 4180
 4181    /// Reopens docks from the most recently remembered configuration.
 4182    ///
 4183    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 4184    /// and clears the stored positions.
 4185    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4186        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 4187
 4188        for position in positions_to_open {
 4189            let dock = self.dock_at_position(position);
 4190            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 4191        }
 4192
 4193        cx.focus_self(window);
 4194        cx.notify();
 4195        self.serialize_workspace(window, cx);
 4196    }
 4197
 4198    /// Transfer focus to the panel of the given type.
 4199    pub fn focus_panel<T: Panel>(
 4200        &mut self,
 4201        window: &mut Window,
 4202        cx: &mut Context<Self>,
 4203    ) -> Option<Entity<T>> {
 4204        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 4205        panel.to_any().downcast().ok()
 4206    }
 4207
 4208    /// Focus the panel of the given type if it isn't already focused. If it is
 4209    /// already focused, then transfer focus back to the workspace center.
 4210    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 4211    /// panel when transferring focus back to the center.
 4212    pub fn toggle_panel_focus<T: Panel>(
 4213        &mut self,
 4214        window: &mut Window,
 4215        cx: &mut Context<Self>,
 4216    ) -> bool {
 4217        let mut did_focus_panel = false;
 4218        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 4219            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 4220            did_focus_panel
 4221        });
 4222
 4223        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 4224            self.close_panel::<T>(window, cx);
 4225        }
 4226
 4227        telemetry::event!(
 4228            "Panel Button Clicked",
 4229            name = T::persistent_name(),
 4230            toggle_state = did_focus_panel
 4231        );
 4232
 4233        did_focus_panel
 4234    }
 4235
 4236    pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4237        if let Some(item) = self.active_item(cx) {
 4238            item.item_focus_handle(cx).focus(window, cx);
 4239        } else {
 4240            log::error!("Could not find a focus target when switching focus to the center panes",);
 4241        }
 4242    }
 4243
 4244    pub fn activate_panel_for_proto_id(
 4245        &mut self,
 4246        panel_id: PanelId,
 4247        window: &mut Window,
 4248        cx: &mut Context<Self>,
 4249    ) -> Option<Arc<dyn PanelHandle>> {
 4250        let mut panel = None;
 4251        for dock in self.all_docks() {
 4252            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 4253                panel = dock.update(cx, |dock, cx| {
 4254                    dock.activate_panel(panel_index, window, cx);
 4255                    dock.set_open(true, window, cx);
 4256                    dock.active_panel().cloned()
 4257                });
 4258                break;
 4259            }
 4260        }
 4261
 4262        if panel.is_some() {
 4263            cx.notify();
 4264            self.serialize_workspace(window, cx);
 4265        }
 4266
 4267        panel
 4268    }
 4269
 4270    /// Focus or unfocus the given panel type, depending on the given callback.
 4271    fn focus_or_unfocus_panel<T: Panel>(
 4272        &mut self,
 4273        window: &mut Window,
 4274        cx: &mut Context<Self>,
 4275        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 4276    ) -> Option<Arc<dyn PanelHandle>> {
 4277        let mut result_panel = None;
 4278        let mut serialize = false;
 4279        for dock in self.all_docks() {
 4280            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4281                let mut focus_center = false;
 4282                let panel = dock.update(cx, |dock, cx| {
 4283                    dock.activate_panel(panel_index, window, cx);
 4284
 4285                    let panel = dock.active_panel().cloned();
 4286                    if let Some(panel) = panel.as_ref() {
 4287                        if should_focus(&**panel, window, cx) {
 4288                            dock.set_open(true, window, cx);
 4289                            panel.panel_focus_handle(cx).focus(window, cx);
 4290                        } else {
 4291                            focus_center = true;
 4292                        }
 4293                    }
 4294                    panel
 4295                });
 4296
 4297                if focus_center {
 4298                    self.active_pane
 4299                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4300                }
 4301
 4302                result_panel = panel;
 4303                serialize = true;
 4304                break;
 4305            }
 4306        }
 4307
 4308        if serialize {
 4309            self.serialize_workspace(window, cx);
 4310        }
 4311
 4312        cx.notify();
 4313        result_panel
 4314    }
 4315
 4316    /// Open the panel of the given type
 4317    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4318        for dock in self.all_docks() {
 4319            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4320                dock.update(cx, |dock, cx| {
 4321                    dock.activate_panel(panel_index, window, cx);
 4322                    dock.set_open(true, window, cx);
 4323                });
 4324            }
 4325        }
 4326    }
 4327
 4328    /// Open the panel of the given type, dismissing any zoomed items that
 4329    /// would obscure it (e.g. a zoomed terminal).
 4330    pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4331        let dock_position = self.all_docks().iter().find_map(|dock| {
 4332            let dock = dock.read(cx);
 4333            dock.panel_index_for_type::<T>().map(|_| dock.position())
 4334        });
 4335        self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
 4336        self.open_panel::<T>(window, cx);
 4337    }
 4338
 4339    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 4340        for dock in self.all_docks().iter() {
 4341            dock.update(cx, |dock, cx| {
 4342                if dock.panel::<T>().is_some() {
 4343                    dock.set_open(false, window, cx)
 4344                }
 4345            })
 4346        }
 4347    }
 4348
 4349    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 4350        self.all_docks()
 4351            .iter()
 4352            .find_map(|dock| dock.read(cx).panel::<T>())
 4353    }
 4354
 4355    fn dismiss_zoomed_items_to_reveal(
 4356        &mut self,
 4357        dock_to_reveal: Option<DockPosition>,
 4358        window: &mut Window,
 4359        cx: &mut Context<Self>,
 4360    ) {
 4361        // If a center pane is zoomed, unzoom it.
 4362        for pane in &self.panes {
 4363            if pane != &self.active_pane || dock_to_reveal.is_some() {
 4364                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4365            }
 4366        }
 4367
 4368        // If another dock is zoomed, hide it.
 4369        let mut focus_center = false;
 4370        for dock in self.all_docks() {
 4371            dock.update(cx, |dock, cx| {
 4372                if Some(dock.position()) != dock_to_reveal
 4373                    && let Some(panel) = dock.active_panel()
 4374                    && panel.is_zoomed(window, cx)
 4375                {
 4376                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 4377                    dock.set_open(false, window, cx);
 4378                }
 4379            });
 4380        }
 4381
 4382        if focus_center {
 4383            self.active_pane
 4384                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4385        }
 4386
 4387        if self.zoomed_position != dock_to_reveal {
 4388            self.zoomed = None;
 4389            self.zoomed_position = None;
 4390            cx.emit(Event::ZoomChanged);
 4391        }
 4392
 4393        cx.notify();
 4394    }
 4395
 4396    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4397        let pane = cx.new(|cx| {
 4398            let mut pane = Pane::new(
 4399                self.weak_handle(),
 4400                self.project.clone(),
 4401                self.pane_history_timestamp.clone(),
 4402                None,
 4403                NewFile.boxed_clone(),
 4404                true,
 4405                window,
 4406                cx,
 4407            );
 4408            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4409            pane
 4410        });
 4411        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4412            .detach();
 4413        self.panes.push(pane.clone());
 4414
 4415        window.focus(&pane.focus_handle(cx), cx);
 4416
 4417        cx.emit(Event::PaneAdded(pane.clone()));
 4418        pane
 4419    }
 4420
 4421    pub fn add_item_to_center(
 4422        &mut self,
 4423        item: Box<dyn ItemHandle>,
 4424        window: &mut Window,
 4425        cx: &mut Context<Self>,
 4426    ) -> bool {
 4427        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4428            if let Some(center_pane) = center_pane.upgrade() {
 4429                center_pane.update(cx, |pane, cx| {
 4430                    pane.add_item(item, true, true, None, window, cx)
 4431                });
 4432                true
 4433            } else {
 4434                false
 4435            }
 4436        } else {
 4437            false
 4438        }
 4439    }
 4440
 4441    pub fn add_item_to_active_pane(
 4442        &mut self,
 4443        item: Box<dyn ItemHandle>,
 4444        destination_index: Option<usize>,
 4445        focus_item: bool,
 4446        window: &mut Window,
 4447        cx: &mut App,
 4448    ) {
 4449        self.add_item(
 4450            self.active_pane.clone(),
 4451            item,
 4452            destination_index,
 4453            false,
 4454            focus_item,
 4455            window,
 4456            cx,
 4457        )
 4458    }
 4459
 4460    pub fn add_item(
 4461        &mut self,
 4462        pane: Entity<Pane>,
 4463        item: Box<dyn ItemHandle>,
 4464        destination_index: Option<usize>,
 4465        activate_pane: bool,
 4466        focus_item: bool,
 4467        window: &mut Window,
 4468        cx: &mut App,
 4469    ) {
 4470        pane.update(cx, |pane, cx| {
 4471            pane.add_item(
 4472                item,
 4473                activate_pane,
 4474                focus_item,
 4475                destination_index,
 4476                window,
 4477                cx,
 4478            )
 4479        });
 4480    }
 4481
 4482    pub fn split_item(
 4483        &mut self,
 4484        split_direction: SplitDirection,
 4485        item: Box<dyn ItemHandle>,
 4486        window: &mut Window,
 4487        cx: &mut Context<Self>,
 4488    ) {
 4489        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4490        self.add_item(new_pane, item, None, true, true, window, cx);
 4491    }
 4492
 4493    pub fn open_abs_path(
 4494        &mut self,
 4495        abs_path: PathBuf,
 4496        options: OpenOptions,
 4497        window: &mut Window,
 4498        cx: &mut Context<Self>,
 4499    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4500        cx.spawn_in(window, async move |workspace, cx| {
 4501            let open_paths_task_result = workspace
 4502                .update_in(cx, |workspace, window, cx| {
 4503                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4504                })
 4505                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4506                .await;
 4507            anyhow::ensure!(
 4508                open_paths_task_result.len() == 1,
 4509                "open abs path {abs_path:?} task returned incorrect number of results"
 4510            );
 4511            match open_paths_task_result
 4512                .into_iter()
 4513                .next()
 4514                .expect("ensured single task result")
 4515            {
 4516                Some(open_result) => {
 4517                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4518                }
 4519                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4520            }
 4521        })
 4522    }
 4523
 4524    pub fn split_abs_path(
 4525        &mut self,
 4526        abs_path: PathBuf,
 4527        visible: bool,
 4528        window: &mut Window,
 4529        cx: &mut Context<Self>,
 4530    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4531        let project_path_task =
 4532            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4533        cx.spawn_in(window, async move |this, cx| {
 4534            let (_, path) = project_path_task.await?;
 4535            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4536                .await
 4537        })
 4538    }
 4539
 4540    pub fn open_path(
 4541        &mut self,
 4542        path: impl Into<ProjectPath>,
 4543        pane: Option<WeakEntity<Pane>>,
 4544        focus_item: bool,
 4545        window: &mut Window,
 4546        cx: &mut App,
 4547    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4548        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4549    }
 4550
 4551    pub fn open_path_preview(
 4552        &mut self,
 4553        path: impl Into<ProjectPath>,
 4554        pane: Option<WeakEntity<Pane>>,
 4555        focus_item: bool,
 4556        allow_preview: bool,
 4557        activate: bool,
 4558        window: &mut Window,
 4559        cx: &mut App,
 4560    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4561        let pane = pane.unwrap_or_else(|| {
 4562            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4563                self.panes
 4564                    .first()
 4565                    .expect("There must be an active pane")
 4566                    .downgrade()
 4567            })
 4568        });
 4569
 4570        let project_path = path.into();
 4571        let task = self.load_path(project_path.clone(), window, cx);
 4572        window.spawn(cx, async move |cx| {
 4573            let (project_entry_id, build_item) = task.await?;
 4574
 4575            pane.update_in(cx, |pane, window, cx| {
 4576                pane.open_item(
 4577                    project_entry_id,
 4578                    project_path,
 4579                    focus_item,
 4580                    allow_preview,
 4581                    activate,
 4582                    None,
 4583                    window,
 4584                    cx,
 4585                    build_item,
 4586                )
 4587            })
 4588        })
 4589    }
 4590
 4591    pub fn split_path(
 4592        &mut self,
 4593        path: impl Into<ProjectPath>,
 4594        window: &mut Window,
 4595        cx: &mut Context<Self>,
 4596    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4597        self.split_path_preview(path, false, None, window, cx)
 4598    }
 4599
 4600    pub fn split_path_preview(
 4601        &mut self,
 4602        path: impl Into<ProjectPath>,
 4603        allow_preview: bool,
 4604        split_direction: Option<SplitDirection>,
 4605        window: &mut Window,
 4606        cx: &mut Context<Self>,
 4607    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4608        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4609            self.panes
 4610                .first()
 4611                .expect("There must be an active pane")
 4612                .downgrade()
 4613        });
 4614
 4615        if let Member::Pane(center_pane) = &self.center.root
 4616            && center_pane.read(cx).items_len() == 0
 4617        {
 4618            return self.open_path(path, Some(pane), true, window, cx);
 4619        }
 4620
 4621        let project_path = path.into();
 4622        let task = self.load_path(project_path.clone(), window, cx);
 4623        cx.spawn_in(window, async move |this, cx| {
 4624            let (project_entry_id, build_item) = task.await?;
 4625            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4626                let pane = pane.upgrade()?;
 4627                let new_pane = this.split_pane(
 4628                    pane,
 4629                    split_direction.unwrap_or(SplitDirection::Right),
 4630                    window,
 4631                    cx,
 4632                );
 4633                new_pane.update(cx, |new_pane, cx| {
 4634                    Some(new_pane.open_item(
 4635                        project_entry_id,
 4636                        project_path,
 4637                        true,
 4638                        allow_preview,
 4639                        true,
 4640                        None,
 4641                        window,
 4642                        cx,
 4643                        build_item,
 4644                    ))
 4645                })
 4646            })
 4647            .map(|option| option.context("pane was dropped"))?
 4648        })
 4649    }
 4650
 4651    fn load_path(
 4652        &mut self,
 4653        path: ProjectPath,
 4654        window: &mut Window,
 4655        cx: &mut App,
 4656    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4657        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4658        registry.open_path(self.project(), &path, window, cx)
 4659    }
 4660
 4661    pub fn find_project_item<T>(
 4662        &self,
 4663        pane: &Entity<Pane>,
 4664        project_item: &Entity<T::Item>,
 4665        cx: &App,
 4666    ) -> Option<Entity<T>>
 4667    where
 4668        T: ProjectItem,
 4669    {
 4670        use project::ProjectItem as _;
 4671        let project_item = project_item.read(cx);
 4672        let entry_id = project_item.entry_id(cx);
 4673        let project_path = project_item.project_path(cx);
 4674
 4675        let mut item = None;
 4676        if let Some(entry_id) = entry_id {
 4677            item = pane.read(cx).item_for_entry(entry_id, cx);
 4678        }
 4679        if item.is_none()
 4680            && let Some(project_path) = project_path
 4681        {
 4682            item = pane.read(cx).item_for_path(project_path, cx);
 4683        }
 4684
 4685        item.and_then(|item| item.downcast::<T>())
 4686    }
 4687
 4688    pub fn is_project_item_open<T>(
 4689        &self,
 4690        pane: &Entity<Pane>,
 4691        project_item: &Entity<T::Item>,
 4692        cx: &App,
 4693    ) -> bool
 4694    where
 4695        T: ProjectItem,
 4696    {
 4697        self.find_project_item::<T>(pane, project_item, cx)
 4698            .is_some()
 4699    }
 4700
 4701    pub fn open_project_item<T>(
 4702        &mut self,
 4703        pane: Entity<Pane>,
 4704        project_item: Entity<T::Item>,
 4705        activate_pane: bool,
 4706        focus_item: bool,
 4707        keep_old_preview: bool,
 4708        allow_new_preview: bool,
 4709        window: &mut Window,
 4710        cx: &mut Context<Self>,
 4711    ) -> Entity<T>
 4712    where
 4713        T: ProjectItem,
 4714    {
 4715        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4716
 4717        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4718            if !keep_old_preview
 4719                && let Some(old_id) = old_item_id
 4720                && old_id != item.item_id()
 4721            {
 4722                // switching to a different item, so unpreview old active item
 4723                pane.update(cx, |pane, _| {
 4724                    pane.unpreview_item_if_preview(old_id);
 4725                });
 4726            }
 4727
 4728            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4729            if !allow_new_preview {
 4730                pane.update(cx, |pane, _| {
 4731                    pane.unpreview_item_if_preview(item.item_id());
 4732                });
 4733            }
 4734            return item;
 4735        }
 4736
 4737        let item = pane.update(cx, |pane, cx| {
 4738            cx.new(|cx| {
 4739                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4740            })
 4741        });
 4742        let mut destination_index = None;
 4743        pane.update(cx, |pane, cx| {
 4744            if !keep_old_preview && let Some(old_id) = old_item_id {
 4745                pane.unpreview_item_if_preview(old_id);
 4746            }
 4747            if allow_new_preview {
 4748                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4749            }
 4750        });
 4751
 4752        self.add_item(
 4753            pane,
 4754            Box::new(item.clone()),
 4755            destination_index,
 4756            activate_pane,
 4757            focus_item,
 4758            window,
 4759            cx,
 4760        );
 4761        item
 4762    }
 4763
 4764    pub fn open_shared_screen(
 4765        &mut self,
 4766        peer_id: PeerId,
 4767        window: &mut Window,
 4768        cx: &mut Context<Self>,
 4769    ) {
 4770        if let Some(shared_screen) =
 4771            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4772        {
 4773            self.active_pane.update(cx, |pane, cx| {
 4774                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4775            });
 4776        }
 4777    }
 4778
 4779    pub fn activate_item(
 4780        &mut self,
 4781        item: &dyn ItemHandle,
 4782        activate_pane: bool,
 4783        focus_item: bool,
 4784        window: &mut Window,
 4785        cx: &mut App,
 4786    ) -> bool {
 4787        let result = self.panes.iter().find_map(|pane| {
 4788            pane.read(cx)
 4789                .index_for_item(item)
 4790                .map(|ix| (pane.clone(), ix))
 4791        });
 4792        if let Some((pane, ix)) = result {
 4793            pane.update(cx, |pane, cx| {
 4794                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4795            });
 4796            true
 4797        } else {
 4798            false
 4799        }
 4800    }
 4801
 4802    fn activate_pane_at_index(
 4803        &mut self,
 4804        action: &ActivatePane,
 4805        window: &mut Window,
 4806        cx: &mut Context<Self>,
 4807    ) {
 4808        let panes = self.center.panes();
 4809        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4810            window.focus(&pane.focus_handle(cx), cx);
 4811        } else {
 4812            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4813                .detach();
 4814        }
 4815    }
 4816
 4817    fn move_item_to_pane_at_index(
 4818        &mut self,
 4819        action: &MoveItemToPane,
 4820        window: &mut Window,
 4821        cx: &mut Context<Self>,
 4822    ) {
 4823        let panes = self.center.panes();
 4824        let destination = match panes.get(action.destination) {
 4825            Some(&destination) => destination.clone(),
 4826            None => {
 4827                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4828                    return;
 4829                }
 4830                let direction = SplitDirection::Right;
 4831                let split_off_pane = self
 4832                    .find_pane_in_direction(direction, cx)
 4833                    .unwrap_or_else(|| self.active_pane.clone());
 4834                let new_pane = self.add_pane(window, cx);
 4835                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4836                new_pane
 4837            }
 4838        };
 4839
 4840        if action.clone {
 4841            if self
 4842                .active_pane
 4843                .read(cx)
 4844                .active_item()
 4845                .is_some_and(|item| item.can_split(cx))
 4846            {
 4847                clone_active_item(
 4848                    self.database_id(),
 4849                    &self.active_pane,
 4850                    &destination,
 4851                    action.focus,
 4852                    window,
 4853                    cx,
 4854                );
 4855                return;
 4856            }
 4857        }
 4858        move_active_item(
 4859            &self.active_pane,
 4860            &destination,
 4861            action.focus,
 4862            true,
 4863            window,
 4864            cx,
 4865        )
 4866    }
 4867
 4868    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4869        let panes = self.center.panes();
 4870        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4871            let next_ix = (ix + 1) % panes.len();
 4872            let next_pane = panes[next_ix].clone();
 4873            window.focus(&next_pane.focus_handle(cx), cx);
 4874        }
 4875    }
 4876
 4877    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4878        let panes = self.center.panes();
 4879        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4880            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4881            let prev_pane = panes[prev_ix].clone();
 4882            window.focus(&prev_pane.focus_handle(cx), cx);
 4883        }
 4884    }
 4885
 4886    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4887        let last_pane = self.center.last_pane();
 4888        window.focus(&last_pane.focus_handle(cx), cx);
 4889    }
 4890
 4891    pub fn activate_pane_in_direction(
 4892        &mut self,
 4893        direction: SplitDirection,
 4894        window: &mut Window,
 4895        cx: &mut App,
 4896    ) {
 4897        use ActivateInDirectionTarget as Target;
 4898        enum Origin {
 4899            Sidebar,
 4900            LeftDock,
 4901            RightDock,
 4902            BottomDock,
 4903            Center,
 4904        }
 4905
 4906        let origin: Origin = if self
 4907            .sidebar_focus_handle
 4908            .as_ref()
 4909            .is_some_and(|h| h.contains_focused(window, cx))
 4910        {
 4911            Origin::Sidebar
 4912        } else {
 4913            [
 4914                (&self.left_dock, Origin::LeftDock),
 4915                (&self.right_dock, Origin::RightDock),
 4916                (&self.bottom_dock, Origin::BottomDock),
 4917            ]
 4918            .into_iter()
 4919            .find_map(|(dock, origin)| {
 4920                if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4921                    Some(origin)
 4922                } else {
 4923                    None
 4924                }
 4925            })
 4926            .unwrap_or(Origin::Center)
 4927        };
 4928
 4929        let get_last_active_pane = || {
 4930            let pane = self
 4931                .last_active_center_pane
 4932                .clone()
 4933                .unwrap_or_else(|| {
 4934                    self.panes
 4935                        .first()
 4936                        .expect("There must be an active pane")
 4937                        .downgrade()
 4938                })
 4939                .upgrade()?;
 4940            (pane.read(cx).items_len() != 0).then_some(pane)
 4941        };
 4942
 4943        let try_dock =
 4944            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4945
 4946        let sidebar_target = self
 4947            .sidebar_focus_handle
 4948            .as_ref()
 4949            .map(|h| Target::Sidebar(h.clone()));
 4950
 4951        let sidebar_on_right = self
 4952            .multi_workspace
 4953            .as_ref()
 4954            .and_then(|mw| mw.upgrade())
 4955            .map_or(false, |mw| {
 4956                mw.read(cx).sidebar_side(cx) == SidebarSide::Right
 4957            });
 4958
 4959        let away_from_sidebar = if sidebar_on_right {
 4960            SplitDirection::Left
 4961        } else {
 4962            SplitDirection::Right
 4963        };
 4964
 4965        let (near_dock, far_dock) = if sidebar_on_right {
 4966            (&self.right_dock, &self.left_dock)
 4967        } else {
 4968            (&self.left_dock, &self.right_dock)
 4969        };
 4970
 4971        let target = match (origin, direction) {
 4972            (Origin::Sidebar, dir) if dir == away_from_sidebar => try_dock(near_dock)
 4973                .or_else(|| get_last_active_pane().map(Target::Pane))
 4974                .or_else(|| try_dock(&self.bottom_dock))
 4975                .or_else(|| try_dock(far_dock)),
 4976
 4977            (Origin::Sidebar, _) => None,
 4978
 4979            // We're in the center, so we first try to go to a different pane,
 4980            // otherwise try to go to a dock.
 4981            (Origin::Center, direction) => {
 4982                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4983                    Some(Target::Pane(pane))
 4984                } else {
 4985                    match direction {
 4986                        SplitDirection::Up => None,
 4987                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4988                        SplitDirection::Left => {
 4989                            let dock_target = try_dock(&self.left_dock);
 4990                            if sidebar_on_right {
 4991                                dock_target
 4992                            } else {
 4993                                dock_target.or(sidebar_target)
 4994                            }
 4995                        }
 4996                        SplitDirection::Right => {
 4997                            let dock_target = try_dock(&self.right_dock);
 4998                            if sidebar_on_right {
 4999                                dock_target.or(sidebar_target)
 5000                            } else {
 5001                                dock_target
 5002                            }
 5003                        }
 5004                    }
 5005                }
 5006            }
 5007
 5008            (Origin::LeftDock, SplitDirection::Right) => {
 5009                if let Some(last_active_pane) = get_last_active_pane() {
 5010                    Some(Target::Pane(last_active_pane))
 5011                } else {
 5012                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 5013                }
 5014            }
 5015
 5016            (Origin::LeftDock, SplitDirection::Left) => {
 5017                if sidebar_on_right {
 5018                    None
 5019                } else {
 5020                    sidebar_target
 5021                }
 5022            }
 5023
 5024            (Origin::LeftDock, SplitDirection::Down)
 5025            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 5026
 5027            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 5028            (Origin::BottomDock, SplitDirection::Left) => {
 5029                let dock_target = try_dock(&self.left_dock);
 5030                if sidebar_on_right {
 5031                    dock_target
 5032                } else {
 5033                    dock_target.or(sidebar_target)
 5034                }
 5035            }
 5036            (Origin::BottomDock, SplitDirection::Right) => {
 5037                let dock_target = try_dock(&self.right_dock);
 5038                if sidebar_on_right {
 5039                    dock_target.or(sidebar_target)
 5040                } else {
 5041                    dock_target
 5042                }
 5043            }
 5044
 5045            (Origin::RightDock, SplitDirection::Left) => {
 5046                if let Some(last_active_pane) = get_last_active_pane() {
 5047                    Some(Target::Pane(last_active_pane))
 5048                } else {
 5049                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 5050                }
 5051            }
 5052
 5053            (Origin::RightDock, SplitDirection::Right) => {
 5054                if sidebar_on_right {
 5055                    sidebar_target
 5056                } else {
 5057                    None
 5058                }
 5059            }
 5060
 5061            _ => None,
 5062        };
 5063
 5064        match target {
 5065            Some(ActivateInDirectionTarget::Pane(pane)) => {
 5066                let pane = pane.read(cx);
 5067                if let Some(item) = pane.active_item() {
 5068                    item.item_focus_handle(cx).focus(window, cx);
 5069                } else {
 5070                    log::error!(
 5071                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 5072                    );
 5073                }
 5074            }
 5075            Some(ActivateInDirectionTarget::Dock(dock)) => {
 5076                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 5077                window.defer(cx, move |window, cx| {
 5078                    let dock = dock.read(cx);
 5079                    if let Some(panel) = dock.active_panel() {
 5080                        panel.panel_focus_handle(cx).focus(window, cx);
 5081                    } else {
 5082                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 5083                    }
 5084                })
 5085            }
 5086            Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
 5087                focus_handle.focus(window, cx);
 5088            }
 5089            None => {}
 5090        }
 5091    }
 5092
 5093    pub fn move_item_to_pane_in_direction(
 5094        &mut self,
 5095        action: &MoveItemToPaneInDirection,
 5096        window: &mut Window,
 5097        cx: &mut Context<Self>,
 5098    ) {
 5099        let destination = match self.find_pane_in_direction(action.direction, cx) {
 5100            Some(destination) => destination,
 5101            None => {
 5102                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 5103                    return;
 5104                }
 5105                let new_pane = self.add_pane(window, cx);
 5106                self.center
 5107                    .split(&self.active_pane, &new_pane, action.direction, cx);
 5108                new_pane
 5109            }
 5110        };
 5111
 5112        if action.clone {
 5113            if self
 5114                .active_pane
 5115                .read(cx)
 5116                .active_item()
 5117                .is_some_and(|item| item.can_split(cx))
 5118            {
 5119                clone_active_item(
 5120                    self.database_id(),
 5121                    &self.active_pane,
 5122                    &destination,
 5123                    action.focus,
 5124                    window,
 5125                    cx,
 5126                );
 5127                return;
 5128            }
 5129        }
 5130        move_active_item(
 5131            &self.active_pane,
 5132            &destination,
 5133            action.focus,
 5134            true,
 5135            window,
 5136            cx,
 5137        );
 5138    }
 5139
 5140    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 5141        self.center.bounding_box_for_pane(pane)
 5142    }
 5143
 5144    pub fn find_pane_in_direction(
 5145        &mut self,
 5146        direction: SplitDirection,
 5147        cx: &App,
 5148    ) -> Option<Entity<Pane>> {
 5149        self.center
 5150            .find_pane_in_direction(&self.active_pane, direction, cx)
 5151            .cloned()
 5152    }
 5153
 5154    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 5155        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 5156            self.center.swap(&self.active_pane, &to, cx);
 5157            cx.notify();
 5158        }
 5159    }
 5160
 5161    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 5162        if self
 5163            .center
 5164            .move_to_border(&self.active_pane, direction, cx)
 5165            .unwrap()
 5166        {
 5167            cx.notify();
 5168        }
 5169    }
 5170
 5171    pub fn resize_pane(
 5172        &mut self,
 5173        axis: gpui::Axis,
 5174        amount: Pixels,
 5175        window: &mut Window,
 5176        cx: &mut Context<Self>,
 5177    ) {
 5178        let docks = self.all_docks();
 5179        let active_dock = docks
 5180            .into_iter()
 5181            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 5182
 5183        if let Some(dock_entity) = active_dock {
 5184            let dock = dock_entity.read(cx);
 5185            let Some(panel_size) = self.dock_size(&dock, window, cx) else {
 5186                return;
 5187            };
 5188            match dock.position() {
 5189                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 5190                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 5191                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 5192            }
 5193        } else {
 5194            self.center
 5195                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 5196        }
 5197        cx.notify();
 5198    }
 5199
 5200    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 5201        self.center.reset_pane_sizes(cx);
 5202        cx.notify();
 5203    }
 5204
 5205    fn handle_pane_focused(
 5206        &mut self,
 5207        pane: Entity<Pane>,
 5208        window: &mut Window,
 5209        cx: &mut Context<Self>,
 5210    ) {
 5211        // This is explicitly hoisted out of the following check for pane identity as
 5212        // terminal panel panes are not registered as a center panes.
 5213        self.status_bar.update(cx, |status_bar, cx| {
 5214            status_bar.set_active_pane(&pane, window, cx);
 5215        });
 5216        if self.active_pane != pane {
 5217            self.set_active_pane(&pane, window, cx);
 5218        }
 5219
 5220        if self.last_active_center_pane.is_none() {
 5221            self.last_active_center_pane = Some(pane.downgrade());
 5222        }
 5223
 5224        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 5225        // This prevents the dock from closing when focus events fire during window activation.
 5226        // We also preserve any dock whose active panel itself has focus — this covers
 5227        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 5228        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 5229            let dock_read = dock.read(cx);
 5230            if let Some(panel) = dock_read.active_panel() {
 5231                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 5232                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 5233                {
 5234                    return Some(dock_read.position());
 5235                }
 5236            }
 5237            None
 5238        });
 5239
 5240        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 5241        if pane.read(cx).is_zoomed() {
 5242            self.zoomed = Some(pane.downgrade().into());
 5243        } else {
 5244            self.zoomed = None;
 5245        }
 5246        self.zoomed_position = None;
 5247        cx.emit(Event::ZoomChanged);
 5248        self.update_active_view_for_followers(window, cx);
 5249        pane.update(cx, |pane, _| {
 5250            pane.track_alternate_file_items();
 5251        });
 5252
 5253        cx.notify();
 5254    }
 5255
 5256    fn set_active_pane(
 5257        &mut self,
 5258        pane: &Entity<Pane>,
 5259        window: &mut Window,
 5260        cx: &mut Context<Self>,
 5261    ) {
 5262        self.active_pane = pane.clone();
 5263        self.active_item_path_changed(true, window, cx);
 5264        self.last_active_center_pane = Some(pane.downgrade());
 5265    }
 5266
 5267    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5268        self.update_active_view_for_followers(window, cx);
 5269    }
 5270
 5271    fn handle_pane_event(
 5272        &mut self,
 5273        pane: &Entity<Pane>,
 5274        event: &pane::Event,
 5275        window: &mut Window,
 5276        cx: &mut Context<Self>,
 5277    ) {
 5278        let mut serialize_workspace = true;
 5279        match event {
 5280            pane::Event::AddItem { item } => {
 5281                item.added_to_pane(self, pane.clone(), window, cx);
 5282                cx.emit(Event::ItemAdded {
 5283                    item: item.boxed_clone(),
 5284                });
 5285            }
 5286            pane::Event::Split { direction, mode } => {
 5287                match mode {
 5288                    SplitMode::ClonePane => {
 5289                        self.split_and_clone(pane.clone(), *direction, window, cx)
 5290                            .detach();
 5291                    }
 5292                    SplitMode::EmptyPane => {
 5293                        self.split_pane(pane.clone(), *direction, window, cx);
 5294                    }
 5295                    SplitMode::MovePane => {
 5296                        self.split_and_move(pane.clone(), *direction, window, cx);
 5297                    }
 5298                };
 5299            }
 5300            pane::Event::JoinIntoNext => {
 5301                self.join_pane_into_next(pane.clone(), window, cx);
 5302            }
 5303            pane::Event::JoinAll => {
 5304                self.join_all_panes(window, cx);
 5305            }
 5306            pane::Event::Remove { focus_on_pane } => {
 5307                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 5308            }
 5309            pane::Event::ActivateItem {
 5310                local,
 5311                focus_changed,
 5312            } => {
 5313                window.invalidate_character_coordinates();
 5314
 5315                pane.update(cx, |pane, _| {
 5316                    pane.track_alternate_file_items();
 5317                });
 5318                if *local {
 5319                    self.unfollow_in_pane(pane, window, cx);
 5320                }
 5321                serialize_workspace = *focus_changed || pane != self.active_pane();
 5322                if pane == self.active_pane() {
 5323                    self.active_item_path_changed(*focus_changed, window, cx);
 5324                    self.update_active_view_for_followers(window, cx);
 5325                } else if *local {
 5326                    self.set_active_pane(pane, window, cx);
 5327                }
 5328            }
 5329            pane::Event::UserSavedItem { item, save_intent } => {
 5330                cx.emit(Event::UserSavedItem {
 5331                    pane: pane.downgrade(),
 5332                    item: item.boxed_clone(),
 5333                    save_intent: *save_intent,
 5334                });
 5335                serialize_workspace = false;
 5336            }
 5337            pane::Event::ChangeItemTitle => {
 5338                if *pane == self.active_pane {
 5339                    self.active_item_path_changed(false, window, cx);
 5340                }
 5341                serialize_workspace = false;
 5342            }
 5343            pane::Event::RemovedItem { item } => {
 5344                cx.emit(Event::ActiveItemChanged);
 5345                self.update_window_edited(window, cx);
 5346                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 5347                    && entry.get().entity_id() == pane.entity_id()
 5348                {
 5349                    entry.remove();
 5350                }
 5351                cx.emit(Event::ItemRemoved {
 5352                    item_id: item.item_id(),
 5353                });
 5354            }
 5355            pane::Event::Focus => {
 5356                window.invalidate_character_coordinates();
 5357                self.handle_pane_focused(pane.clone(), window, cx);
 5358            }
 5359            pane::Event::ZoomIn => {
 5360                if *pane == self.active_pane {
 5361                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 5362                    if pane.read(cx).has_focus(window, cx) {
 5363                        self.zoomed = Some(pane.downgrade().into());
 5364                        self.zoomed_position = None;
 5365                        cx.emit(Event::ZoomChanged);
 5366                    }
 5367                    cx.notify();
 5368                }
 5369            }
 5370            pane::Event::ZoomOut => {
 5371                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 5372                if self.zoomed_position.is_none() {
 5373                    self.zoomed = None;
 5374                    cx.emit(Event::ZoomChanged);
 5375                }
 5376                cx.notify();
 5377            }
 5378            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 5379        }
 5380
 5381        if serialize_workspace {
 5382            self.serialize_workspace(window, cx);
 5383        }
 5384    }
 5385
 5386    pub fn unfollow_in_pane(
 5387        &mut self,
 5388        pane: &Entity<Pane>,
 5389        window: &mut Window,
 5390        cx: &mut Context<Workspace>,
 5391    ) -> Option<CollaboratorId> {
 5392        let leader_id = self.leader_for_pane(pane)?;
 5393        self.unfollow(leader_id, window, cx);
 5394        Some(leader_id)
 5395    }
 5396
 5397    pub fn split_pane(
 5398        &mut self,
 5399        pane_to_split: Entity<Pane>,
 5400        split_direction: SplitDirection,
 5401        window: &mut Window,
 5402        cx: &mut Context<Self>,
 5403    ) -> Entity<Pane> {
 5404        let new_pane = self.add_pane(window, cx);
 5405        self.center
 5406            .split(&pane_to_split, &new_pane, split_direction, cx);
 5407        cx.notify();
 5408        new_pane
 5409    }
 5410
 5411    pub fn split_and_move(
 5412        &mut self,
 5413        pane: Entity<Pane>,
 5414        direction: SplitDirection,
 5415        window: &mut Window,
 5416        cx: &mut Context<Self>,
 5417    ) {
 5418        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 5419            return;
 5420        };
 5421        let new_pane = self.add_pane(window, cx);
 5422        new_pane.update(cx, |pane, cx| {
 5423            pane.add_item(item, true, true, None, window, cx)
 5424        });
 5425        self.center.split(&pane, &new_pane, direction, cx);
 5426        cx.notify();
 5427    }
 5428
 5429    pub fn split_and_clone(
 5430        &mut self,
 5431        pane: Entity<Pane>,
 5432        direction: SplitDirection,
 5433        window: &mut Window,
 5434        cx: &mut Context<Self>,
 5435    ) -> Task<Option<Entity<Pane>>> {
 5436        let Some(item) = pane.read(cx).active_item() else {
 5437            return Task::ready(None);
 5438        };
 5439        if !item.can_split(cx) {
 5440            return Task::ready(None);
 5441        }
 5442        let task = item.clone_on_split(self.database_id(), window, cx);
 5443        cx.spawn_in(window, async move |this, cx| {
 5444            if let Some(clone) = task.await {
 5445                this.update_in(cx, |this, window, cx| {
 5446                    let new_pane = this.add_pane(window, cx);
 5447                    let nav_history = pane.read(cx).fork_nav_history();
 5448                    new_pane.update(cx, |pane, cx| {
 5449                        pane.set_nav_history(nav_history, cx);
 5450                        pane.add_item(clone, true, true, None, window, cx)
 5451                    });
 5452                    this.center.split(&pane, &new_pane, direction, cx);
 5453                    cx.notify();
 5454                    new_pane
 5455                })
 5456                .ok()
 5457            } else {
 5458                None
 5459            }
 5460        })
 5461    }
 5462
 5463    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5464        let active_item = self.active_pane.read(cx).active_item();
 5465        for pane in &self.panes {
 5466            join_pane_into_active(&self.active_pane, pane, window, cx);
 5467        }
 5468        if let Some(active_item) = active_item {
 5469            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5470        }
 5471        cx.notify();
 5472    }
 5473
 5474    pub fn join_pane_into_next(
 5475        &mut self,
 5476        pane: Entity<Pane>,
 5477        window: &mut Window,
 5478        cx: &mut Context<Self>,
 5479    ) {
 5480        let next_pane = self
 5481            .find_pane_in_direction(SplitDirection::Right, cx)
 5482            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5483            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5484            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5485        let Some(next_pane) = next_pane else {
 5486            return;
 5487        };
 5488        move_all_items(&pane, &next_pane, window, cx);
 5489        cx.notify();
 5490    }
 5491
 5492    fn remove_pane(
 5493        &mut self,
 5494        pane: Entity<Pane>,
 5495        focus_on: Option<Entity<Pane>>,
 5496        window: &mut Window,
 5497        cx: &mut Context<Self>,
 5498    ) {
 5499        if self.center.remove(&pane, cx).unwrap() {
 5500            self.force_remove_pane(&pane, &focus_on, window, cx);
 5501            self.unfollow_in_pane(&pane, window, cx);
 5502            self.last_leaders_by_pane.remove(&pane.downgrade());
 5503            for removed_item in pane.read(cx).items() {
 5504                self.panes_by_item.remove(&removed_item.item_id());
 5505            }
 5506
 5507            cx.notify();
 5508        } else {
 5509            self.active_item_path_changed(true, window, cx);
 5510        }
 5511        cx.emit(Event::PaneRemoved);
 5512    }
 5513
 5514    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5515        &mut self.panes
 5516    }
 5517
 5518    pub fn panes(&self) -> &[Entity<Pane>] {
 5519        &self.panes
 5520    }
 5521
 5522    pub fn active_pane(&self) -> &Entity<Pane> {
 5523        &self.active_pane
 5524    }
 5525
 5526    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5527        for dock in self.all_docks() {
 5528            if dock.focus_handle(cx).contains_focused(window, cx)
 5529                && let Some(pane) = dock
 5530                    .read(cx)
 5531                    .active_panel()
 5532                    .and_then(|panel| panel.pane(cx))
 5533            {
 5534                return pane;
 5535            }
 5536        }
 5537        self.active_pane().clone()
 5538    }
 5539
 5540    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5541        self.find_pane_in_direction(SplitDirection::Right, cx)
 5542            .unwrap_or_else(|| {
 5543                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5544            })
 5545    }
 5546
 5547    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5548        self.pane_for_item_id(handle.item_id())
 5549    }
 5550
 5551    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5552        let weak_pane = self.panes_by_item.get(&item_id)?;
 5553        weak_pane.upgrade()
 5554    }
 5555
 5556    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5557        self.panes
 5558            .iter()
 5559            .find(|pane| pane.entity_id() == entity_id)
 5560            .cloned()
 5561    }
 5562
 5563    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5564        self.follower_states.retain(|leader_id, state| {
 5565            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5566                for item in state.items_by_leader_view_id.values() {
 5567                    item.view.set_leader_id(None, window, cx);
 5568                }
 5569                false
 5570            } else {
 5571                true
 5572            }
 5573        });
 5574        cx.notify();
 5575    }
 5576
 5577    pub fn start_following(
 5578        &mut self,
 5579        leader_id: impl Into<CollaboratorId>,
 5580        window: &mut Window,
 5581        cx: &mut Context<Self>,
 5582    ) -> Option<Task<Result<()>>> {
 5583        let leader_id = leader_id.into();
 5584        let pane = self.active_pane().clone();
 5585
 5586        self.last_leaders_by_pane
 5587            .insert(pane.downgrade(), leader_id);
 5588        self.unfollow(leader_id, window, cx);
 5589        self.unfollow_in_pane(&pane, window, cx);
 5590        self.follower_states.insert(
 5591            leader_id,
 5592            FollowerState {
 5593                center_pane: pane.clone(),
 5594                dock_pane: None,
 5595                active_view_id: None,
 5596                items_by_leader_view_id: Default::default(),
 5597            },
 5598        );
 5599        cx.notify();
 5600
 5601        match leader_id {
 5602            CollaboratorId::PeerId(leader_peer_id) => {
 5603                let room_id = self.active_call()?.room_id(cx)?;
 5604                let project_id = self.project.read(cx).remote_id();
 5605                let request = self.app_state.client.request(proto::Follow {
 5606                    room_id,
 5607                    project_id,
 5608                    leader_id: Some(leader_peer_id),
 5609                });
 5610
 5611                Some(cx.spawn_in(window, async move |this, cx| {
 5612                    let response = request.await?;
 5613                    this.update(cx, |this, _| {
 5614                        let state = this
 5615                            .follower_states
 5616                            .get_mut(&leader_id)
 5617                            .context("following interrupted")?;
 5618                        state.active_view_id = response
 5619                            .active_view
 5620                            .as_ref()
 5621                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5622                        anyhow::Ok(())
 5623                    })??;
 5624                    if let Some(view) = response.active_view {
 5625                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5626                    }
 5627                    this.update_in(cx, |this, window, cx| {
 5628                        this.leader_updated(leader_id, window, cx)
 5629                    })?;
 5630                    Ok(())
 5631                }))
 5632            }
 5633            CollaboratorId::Agent => {
 5634                self.leader_updated(leader_id, window, cx)?;
 5635                Some(Task::ready(Ok(())))
 5636            }
 5637        }
 5638    }
 5639
 5640    pub fn follow_next_collaborator(
 5641        &mut self,
 5642        _: &FollowNextCollaborator,
 5643        window: &mut Window,
 5644        cx: &mut Context<Self>,
 5645    ) {
 5646        let collaborators = self.project.read(cx).collaborators();
 5647        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5648            let mut collaborators = collaborators.keys().copied();
 5649            for peer_id in collaborators.by_ref() {
 5650                if CollaboratorId::PeerId(peer_id) == leader_id {
 5651                    break;
 5652                }
 5653            }
 5654            collaborators.next().map(CollaboratorId::PeerId)
 5655        } else if let Some(last_leader_id) =
 5656            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5657        {
 5658            match last_leader_id {
 5659                CollaboratorId::PeerId(peer_id) => {
 5660                    if collaborators.contains_key(peer_id) {
 5661                        Some(*last_leader_id)
 5662                    } else {
 5663                        None
 5664                    }
 5665                }
 5666                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5667            }
 5668        } else {
 5669            None
 5670        };
 5671
 5672        let pane = self.active_pane.clone();
 5673        let Some(leader_id) = next_leader_id.or_else(|| {
 5674            Some(CollaboratorId::PeerId(
 5675                collaborators.keys().copied().next()?,
 5676            ))
 5677        }) else {
 5678            return;
 5679        };
 5680        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5681            return;
 5682        }
 5683        if let Some(task) = self.start_following(leader_id, window, cx) {
 5684            task.detach_and_log_err(cx)
 5685        }
 5686    }
 5687
 5688    pub fn follow(
 5689        &mut self,
 5690        leader_id: impl Into<CollaboratorId>,
 5691        window: &mut Window,
 5692        cx: &mut Context<Self>,
 5693    ) {
 5694        let leader_id = leader_id.into();
 5695
 5696        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5697            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5698                return;
 5699            };
 5700            let Some(remote_participant) =
 5701                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5702            else {
 5703                return;
 5704            };
 5705
 5706            let project = self.project.read(cx);
 5707
 5708            let other_project_id = match remote_participant.location {
 5709                ParticipantLocation::External => None,
 5710                ParticipantLocation::UnsharedProject => None,
 5711                ParticipantLocation::SharedProject { project_id } => {
 5712                    if Some(project_id) == project.remote_id() {
 5713                        None
 5714                    } else {
 5715                        Some(project_id)
 5716                    }
 5717                }
 5718            };
 5719
 5720            // if they are active in another project, follow there.
 5721            if let Some(project_id) = other_project_id {
 5722                let app_state = self.app_state.clone();
 5723                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5724                    .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
 5725                        Some(format!("{error:#}"))
 5726                    });
 5727            }
 5728        }
 5729
 5730        // if you're already following, find the right pane and focus it.
 5731        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5732            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5733
 5734            return;
 5735        }
 5736
 5737        // Otherwise, follow.
 5738        if let Some(task) = self.start_following(leader_id, window, cx) {
 5739            task.detach_and_log_err(cx)
 5740        }
 5741    }
 5742
 5743    pub fn unfollow(
 5744        &mut self,
 5745        leader_id: impl Into<CollaboratorId>,
 5746        window: &mut Window,
 5747        cx: &mut Context<Self>,
 5748    ) -> Option<()> {
 5749        cx.notify();
 5750
 5751        let leader_id = leader_id.into();
 5752        let state = self.follower_states.remove(&leader_id)?;
 5753        for (_, item) in state.items_by_leader_view_id {
 5754            item.view.set_leader_id(None, window, cx);
 5755        }
 5756
 5757        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5758            let project_id = self.project.read(cx).remote_id();
 5759            let room_id = self.active_call()?.room_id(cx)?;
 5760            self.app_state
 5761                .client
 5762                .send(proto::Unfollow {
 5763                    room_id,
 5764                    project_id,
 5765                    leader_id: Some(leader_peer_id),
 5766                })
 5767                .log_err();
 5768        }
 5769
 5770        Some(())
 5771    }
 5772
 5773    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5774        self.follower_states.contains_key(&id.into())
 5775    }
 5776
 5777    fn active_item_path_changed(
 5778        &mut self,
 5779        focus_changed: bool,
 5780        window: &mut Window,
 5781        cx: &mut Context<Self>,
 5782    ) {
 5783        cx.emit(Event::ActiveItemChanged);
 5784        let active_entry = self.active_project_path(cx);
 5785        self.project.update(cx, |project, cx| {
 5786            project.set_active_path(active_entry.clone(), cx)
 5787        });
 5788
 5789        if focus_changed && let Some(project_path) = &active_entry {
 5790            let git_store_entity = self.project.read(cx).git_store().clone();
 5791            git_store_entity.update(cx, |git_store, cx| {
 5792                git_store.set_active_repo_for_path(project_path, cx);
 5793            });
 5794        }
 5795
 5796        self.update_window_title(window, cx);
 5797    }
 5798
 5799    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5800        let project = self.project().read(cx);
 5801        let mut title = String::new();
 5802
 5803        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5804            let name = {
 5805                let settings_location = SettingsLocation {
 5806                    worktree_id: worktree.read(cx).id(),
 5807                    path: RelPath::empty(),
 5808                };
 5809
 5810                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5811                match &settings.project_name {
 5812                    Some(name) => name.as_str(),
 5813                    None => worktree.read(cx).root_name_str(),
 5814                }
 5815            };
 5816            if i > 0 {
 5817                title.push_str(", ");
 5818            }
 5819            title.push_str(name);
 5820        }
 5821
 5822        if title.is_empty() {
 5823            title = "empty project".to_string();
 5824        }
 5825
 5826        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5827            let filename = path.path.file_name().or_else(|| {
 5828                Some(
 5829                    project
 5830                        .worktree_for_id(path.worktree_id, cx)?
 5831                        .read(cx)
 5832                        .root_name_str(),
 5833                )
 5834            });
 5835
 5836            if let Some(filename) = filename {
 5837                title.push_str("");
 5838                title.push_str(filename.as_ref());
 5839            }
 5840        }
 5841
 5842        if project.is_via_collab() {
 5843            title.push_str("");
 5844        } else if project.is_shared() {
 5845            title.push_str("");
 5846        }
 5847
 5848        if let Some(last_title) = self.last_window_title.as_ref()
 5849            && &title == last_title
 5850        {
 5851            return;
 5852        }
 5853        window.set_window_title(&title);
 5854        SystemWindowTabController::update_tab_title(
 5855            cx,
 5856            window.window_handle().window_id(),
 5857            SharedString::from(&title),
 5858        );
 5859        self.last_window_title = Some(title);
 5860    }
 5861
 5862    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5863        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5864        if is_edited != self.window_edited {
 5865            self.window_edited = is_edited;
 5866            window.set_window_edited(self.window_edited)
 5867        }
 5868    }
 5869
 5870    fn update_item_dirty_state(
 5871        &mut self,
 5872        item: &dyn ItemHandle,
 5873        window: &mut Window,
 5874        cx: &mut App,
 5875    ) {
 5876        let is_dirty = item.is_dirty(cx);
 5877        let item_id = item.item_id();
 5878        let was_dirty = self.dirty_items.contains_key(&item_id);
 5879        if is_dirty == was_dirty {
 5880            return;
 5881        }
 5882        if was_dirty {
 5883            self.dirty_items.remove(&item_id);
 5884            self.update_window_edited(window, cx);
 5885            return;
 5886        }
 5887
 5888        let workspace = self.weak_handle();
 5889        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5890            return;
 5891        };
 5892        let on_release_callback = Box::new(move |cx: &mut App| {
 5893            window_handle
 5894                .update(cx, |_, window, cx| {
 5895                    workspace
 5896                        .update(cx, |workspace, cx| {
 5897                            workspace.dirty_items.remove(&item_id);
 5898                            workspace.update_window_edited(window, cx)
 5899                        })
 5900                        .ok();
 5901                })
 5902                .ok();
 5903        });
 5904
 5905        let s = item.on_release(cx, on_release_callback);
 5906        self.dirty_items.insert(item_id, s);
 5907        self.update_window_edited(window, cx);
 5908    }
 5909
 5910    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5911        if self.notifications.is_empty() {
 5912            None
 5913        } else {
 5914            Some(
 5915                div()
 5916                    .absolute()
 5917                    .right_3()
 5918                    .bottom_3()
 5919                    .w_112()
 5920                    .h_full()
 5921                    .flex()
 5922                    .flex_col()
 5923                    .justify_end()
 5924                    .gap_2()
 5925                    .children(
 5926                        self.notifications
 5927                            .iter()
 5928                            .map(|(_, notification)| notification.clone().into_any()),
 5929                    ),
 5930            )
 5931        }
 5932    }
 5933
 5934    // RPC handlers
 5935
 5936    fn active_view_for_follower(
 5937        &self,
 5938        follower_project_id: Option<u64>,
 5939        window: &mut Window,
 5940        cx: &mut Context<Self>,
 5941    ) -> Option<proto::View> {
 5942        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5943        let item = item?;
 5944        let leader_id = self
 5945            .pane_for(&*item)
 5946            .and_then(|pane| self.leader_for_pane(&pane));
 5947        let leader_peer_id = match leader_id {
 5948            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5949            Some(CollaboratorId::Agent) | None => None,
 5950        };
 5951
 5952        let item_handle = item.to_followable_item_handle(cx)?;
 5953        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5954        let variant = item_handle.to_state_proto(window, cx)?;
 5955
 5956        if item_handle.is_project_item(window, cx)
 5957            && (follower_project_id.is_none()
 5958                || follower_project_id != self.project.read(cx).remote_id())
 5959        {
 5960            return None;
 5961        }
 5962
 5963        Some(proto::View {
 5964            id: id.to_proto(),
 5965            leader_id: leader_peer_id,
 5966            variant: Some(variant),
 5967            panel_id: panel_id.map(|id| id as i32),
 5968        })
 5969    }
 5970
 5971    fn handle_follow(
 5972        &mut self,
 5973        follower_project_id: Option<u64>,
 5974        window: &mut Window,
 5975        cx: &mut Context<Self>,
 5976    ) -> proto::FollowResponse {
 5977        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5978
 5979        cx.notify();
 5980        proto::FollowResponse {
 5981            views: active_view.iter().cloned().collect(),
 5982            active_view,
 5983        }
 5984    }
 5985
 5986    fn handle_update_followers(
 5987        &mut self,
 5988        leader_id: PeerId,
 5989        message: proto::UpdateFollowers,
 5990        _window: &mut Window,
 5991        _cx: &mut Context<Self>,
 5992    ) {
 5993        self.leader_updates_tx
 5994            .unbounded_send((leader_id, message))
 5995            .ok();
 5996    }
 5997
 5998    async fn process_leader_update(
 5999        this: &WeakEntity<Self>,
 6000        leader_id: PeerId,
 6001        update: proto::UpdateFollowers,
 6002        cx: &mut AsyncWindowContext,
 6003    ) -> Result<()> {
 6004        match update.variant.context("invalid update")? {
 6005            proto::update_followers::Variant::CreateView(view) => {
 6006                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 6007                let should_add_view = this.update(cx, |this, _| {
 6008                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 6009                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 6010                    } else {
 6011                        anyhow::Ok(false)
 6012                    }
 6013                })??;
 6014
 6015                if should_add_view {
 6016                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 6017                }
 6018            }
 6019            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 6020                let should_add_view = this.update(cx, |this, _| {
 6021                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 6022                        state.active_view_id = update_active_view
 6023                            .view
 6024                            .as_ref()
 6025                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 6026
 6027                        if state.active_view_id.is_some_and(|view_id| {
 6028                            !state.items_by_leader_view_id.contains_key(&view_id)
 6029                        }) {
 6030                            anyhow::Ok(true)
 6031                        } else {
 6032                            anyhow::Ok(false)
 6033                        }
 6034                    } else {
 6035                        anyhow::Ok(false)
 6036                    }
 6037                })??;
 6038
 6039                if should_add_view && let Some(view) = update_active_view.view {
 6040                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 6041                }
 6042            }
 6043            proto::update_followers::Variant::UpdateView(update_view) => {
 6044                let variant = update_view.variant.context("missing update view variant")?;
 6045                let id = update_view.id.context("missing update view id")?;
 6046                let mut tasks = Vec::new();
 6047                this.update_in(cx, |this, window, cx| {
 6048                    let project = this.project.clone();
 6049                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 6050                        let view_id = ViewId::from_proto(id.clone())?;
 6051                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 6052                            tasks.push(item.view.apply_update_proto(
 6053                                &project,
 6054                                variant.clone(),
 6055                                window,
 6056                                cx,
 6057                            ));
 6058                        }
 6059                    }
 6060                    anyhow::Ok(())
 6061                })??;
 6062                try_join_all(tasks).await.log_err();
 6063            }
 6064        }
 6065        this.update_in(cx, |this, window, cx| {
 6066            this.leader_updated(leader_id, window, cx)
 6067        })?;
 6068        Ok(())
 6069    }
 6070
 6071    async fn add_view_from_leader(
 6072        this: WeakEntity<Self>,
 6073        leader_id: PeerId,
 6074        view: &proto::View,
 6075        cx: &mut AsyncWindowContext,
 6076    ) -> Result<()> {
 6077        let this = this.upgrade().context("workspace dropped")?;
 6078
 6079        let Some(id) = view.id.clone() else {
 6080            anyhow::bail!("no id for view");
 6081        };
 6082        let id = ViewId::from_proto(id)?;
 6083        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 6084
 6085        let pane = this.update(cx, |this, _cx| {
 6086            let state = this
 6087                .follower_states
 6088                .get(&leader_id.into())
 6089                .context("stopped following")?;
 6090            anyhow::Ok(state.pane().clone())
 6091        })?;
 6092        let existing_item = pane.update_in(cx, |pane, window, cx| {
 6093            let client = this.read(cx).client().clone();
 6094            pane.items().find_map(|item| {
 6095                let item = item.to_followable_item_handle(cx)?;
 6096                if item.remote_id(&client, window, cx) == Some(id) {
 6097                    Some(item)
 6098                } else {
 6099                    None
 6100                }
 6101            })
 6102        })?;
 6103        let item = if let Some(existing_item) = existing_item {
 6104            existing_item
 6105        } else {
 6106            let variant = view.variant.clone();
 6107            anyhow::ensure!(variant.is_some(), "missing view variant");
 6108
 6109            let task = cx.update(|window, cx| {
 6110                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 6111            })?;
 6112
 6113            let Some(task) = task else {
 6114                anyhow::bail!(
 6115                    "failed to construct view from leader (maybe from a different version of zed?)"
 6116                );
 6117            };
 6118
 6119            let mut new_item = task.await?;
 6120            pane.update_in(cx, |pane, window, cx| {
 6121                let mut item_to_remove = None;
 6122                for (ix, item) in pane.items().enumerate() {
 6123                    if let Some(item) = item.to_followable_item_handle(cx) {
 6124                        match new_item.dedup(item.as_ref(), window, cx) {
 6125                            Some(item::Dedup::KeepExisting) => {
 6126                                new_item =
 6127                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 6128                                break;
 6129                            }
 6130                            Some(item::Dedup::ReplaceExisting) => {
 6131                                item_to_remove = Some((ix, item.item_id()));
 6132                                break;
 6133                            }
 6134                            None => {}
 6135                        }
 6136                    }
 6137                }
 6138
 6139                if let Some((ix, id)) = item_to_remove {
 6140                    pane.remove_item(id, false, false, window, cx);
 6141                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 6142                }
 6143            })?;
 6144
 6145            new_item
 6146        };
 6147
 6148        this.update_in(cx, |this, window, cx| {
 6149            let state = this.follower_states.get_mut(&leader_id.into())?;
 6150            item.set_leader_id(Some(leader_id.into()), window, cx);
 6151            state.items_by_leader_view_id.insert(
 6152                id,
 6153                FollowerView {
 6154                    view: item,
 6155                    location: panel_id,
 6156                },
 6157            );
 6158
 6159            Some(())
 6160        })
 6161        .context("no follower state")?;
 6162
 6163        Ok(())
 6164    }
 6165
 6166    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6167        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 6168            return;
 6169        };
 6170
 6171        if let Some(agent_location) = self.project.read(cx).agent_location() {
 6172            let buffer_entity_id = agent_location.buffer.entity_id();
 6173            let view_id = ViewId {
 6174                creator: CollaboratorId::Agent,
 6175                id: buffer_entity_id.as_u64(),
 6176            };
 6177            follower_state.active_view_id = Some(view_id);
 6178
 6179            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 6180                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 6181                hash_map::Entry::Vacant(entry) => {
 6182                    let existing_view =
 6183                        follower_state
 6184                            .center_pane
 6185                            .read(cx)
 6186                            .items()
 6187                            .find_map(|item| {
 6188                                let item = item.to_followable_item_handle(cx)?;
 6189                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 6190                                    && item.project_item_model_ids(cx).as_slice()
 6191                                        == [buffer_entity_id]
 6192                                {
 6193                                    Some(item)
 6194                                } else {
 6195                                    None
 6196                                }
 6197                            });
 6198                    let view = existing_view.or_else(|| {
 6199                        agent_location.buffer.upgrade().and_then(|buffer| {
 6200                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 6201                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 6202                            })?
 6203                            .to_followable_item_handle(cx)
 6204                        })
 6205                    });
 6206
 6207                    view.map(|view| {
 6208                        entry.insert(FollowerView {
 6209                            view,
 6210                            location: None,
 6211                        })
 6212                    })
 6213                }
 6214            };
 6215
 6216            if let Some(item) = item {
 6217                item.view
 6218                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 6219                item.view
 6220                    .update_agent_location(agent_location.position, window, cx);
 6221            }
 6222        } else {
 6223            follower_state.active_view_id = None;
 6224        }
 6225
 6226        self.leader_updated(CollaboratorId::Agent, window, cx);
 6227    }
 6228
 6229    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 6230        let mut is_project_item = true;
 6231        let mut update = proto::UpdateActiveView::default();
 6232        if window.is_window_active() {
 6233            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 6234
 6235            if let Some(item) = active_item
 6236                && item.item_focus_handle(cx).contains_focused(window, cx)
 6237            {
 6238                let leader_id = self
 6239                    .pane_for(&*item)
 6240                    .and_then(|pane| self.leader_for_pane(&pane));
 6241                let leader_peer_id = match leader_id {
 6242                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 6243                    Some(CollaboratorId::Agent) | None => None,
 6244                };
 6245
 6246                if let Some(item) = item.to_followable_item_handle(cx) {
 6247                    let id = item
 6248                        .remote_id(&self.app_state.client, window, cx)
 6249                        .map(|id| id.to_proto());
 6250
 6251                    if let Some(id) = id
 6252                        && let Some(variant) = item.to_state_proto(window, cx)
 6253                    {
 6254                        let view = Some(proto::View {
 6255                            id,
 6256                            leader_id: leader_peer_id,
 6257                            variant: Some(variant),
 6258                            panel_id: panel_id.map(|id| id as i32),
 6259                        });
 6260
 6261                        is_project_item = item.is_project_item(window, cx);
 6262                        update = proto::UpdateActiveView { view };
 6263                    };
 6264                }
 6265            }
 6266        }
 6267
 6268        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 6269        if active_view_id != self.last_active_view_id.as_ref() {
 6270            self.last_active_view_id = active_view_id.cloned();
 6271            self.update_followers(
 6272                is_project_item,
 6273                proto::update_followers::Variant::UpdateActiveView(update),
 6274                window,
 6275                cx,
 6276            );
 6277        }
 6278    }
 6279
 6280    fn active_item_for_followers(
 6281        &self,
 6282        window: &mut Window,
 6283        cx: &mut App,
 6284    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 6285        let mut active_item = None;
 6286        let mut panel_id = None;
 6287        for dock in self.all_docks() {
 6288            if dock.focus_handle(cx).contains_focused(window, cx)
 6289                && let Some(panel) = dock.read(cx).active_panel()
 6290                && let Some(pane) = panel.pane(cx)
 6291                && let Some(item) = pane.read(cx).active_item()
 6292            {
 6293                active_item = Some(item);
 6294                panel_id = panel.remote_id();
 6295                break;
 6296            }
 6297        }
 6298
 6299        if active_item.is_none() {
 6300            active_item = self.active_pane().read(cx).active_item();
 6301        }
 6302        (active_item, panel_id)
 6303    }
 6304
 6305    fn update_followers(
 6306        &self,
 6307        project_only: bool,
 6308        update: proto::update_followers::Variant,
 6309        _: &mut Window,
 6310        cx: &mut App,
 6311    ) -> Option<()> {
 6312        // If this update only applies to for followers in the current project,
 6313        // then skip it unless this project is shared. If it applies to all
 6314        // followers, regardless of project, then set `project_id` to none,
 6315        // indicating that it goes to all followers.
 6316        let project_id = if project_only {
 6317            Some(self.project.read(cx).remote_id()?)
 6318        } else {
 6319            None
 6320        };
 6321        self.app_state().workspace_store.update(cx, |store, cx| {
 6322            store.update_followers(project_id, update, cx)
 6323        })
 6324    }
 6325
 6326    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 6327        self.follower_states.iter().find_map(|(leader_id, state)| {
 6328            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 6329                Some(*leader_id)
 6330            } else {
 6331                None
 6332            }
 6333        })
 6334    }
 6335
 6336    fn leader_updated(
 6337        &mut self,
 6338        leader_id: impl Into<CollaboratorId>,
 6339        window: &mut Window,
 6340        cx: &mut Context<Self>,
 6341    ) -> Option<Box<dyn ItemHandle>> {
 6342        cx.notify();
 6343
 6344        let leader_id = leader_id.into();
 6345        let (panel_id, item) = match leader_id {
 6346            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 6347            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 6348        };
 6349
 6350        let state = self.follower_states.get(&leader_id)?;
 6351        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 6352        let pane;
 6353        if let Some(panel_id) = panel_id {
 6354            pane = self
 6355                .activate_panel_for_proto_id(panel_id, window, cx)?
 6356                .pane(cx)?;
 6357            let state = self.follower_states.get_mut(&leader_id)?;
 6358            state.dock_pane = Some(pane.clone());
 6359        } else {
 6360            pane = state.center_pane.clone();
 6361            let state = self.follower_states.get_mut(&leader_id)?;
 6362            if let Some(dock_pane) = state.dock_pane.take() {
 6363                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 6364            }
 6365        }
 6366
 6367        pane.update(cx, |pane, cx| {
 6368            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 6369            if let Some(index) = pane.index_for_item(item.as_ref()) {
 6370                pane.activate_item(index, false, false, window, cx);
 6371            } else {
 6372                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 6373            }
 6374
 6375            if focus_active_item {
 6376                pane.focus_active_item(window, cx)
 6377            }
 6378        });
 6379
 6380        Some(item)
 6381    }
 6382
 6383    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 6384        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 6385        let active_view_id = state.active_view_id?;
 6386        Some(
 6387            state
 6388                .items_by_leader_view_id
 6389                .get(&active_view_id)?
 6390                .view
 6391                .boxed_clone(),
 6392        )
 6393    }
 6394
 6395    fn active_item_for_peer(
 6396        &self,
 6397        peer_id: PeerId,
 6398        window: &mut Window,
 6399        cx: &mut Context<Self>,
 6400    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 6401        let call = self.active_call()?;
 6402        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 6403        let leader_in_this_app;
 6404        let leader_in_this_project;
 6405        match participant.location {
 6406            ParticipantLocation::SharedProject { project_id } => {
 6407                leader_in_this_app = true;
 6408                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 6409            }
 6410            ParticipantLocation::UnsharedProject => {
 6411                leader_in_this_app = true;
 6412                leader_in_this_project = false;
 6413            }
 6414            ParticipantLocation::External => {
 6415                leader_in_this_app = false;
 6416                leader_in_this_project = false;
 6417            }
 6418        };
 6419        let state = self.follower_states.get(&peer_id.into())?;
 6420        let mut item_to_activate = None;
 6421        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 6422            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 6423                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 6424            {
 6425                item_to_activate = Some((item.location, item.view.boxed_clone()));
 6426            }
 6427        } else if let Some(shared_screen) =
 6428            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 6429        {
 6430            item_to_activate = Some((None, Box::new(shared_screen)));
 6431        }
 6432        item_to_activate
 6433    }
 6434
 6435    fn shared_screen_for_peer(
 6436        &self,
 6437        peer_id: PeerId,
 6438        pane: &Entity<Pane>,
 6439        window: &mut Window,
 6440        cx: &mut App,
 6441    ) -> Option<Entity<SharedScreen>> {
 6442        self.active_call()?
 6443            .create_shared_screen(peer_id, pane, window, cx)
 6444    }
 6445
 6446    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6447        if window.is_window_active() {
 6448            self.update_active_view_for_followers(window, cx);
 6449
 6450            if let Some(database_id) = self.database_id {
 6451                let db = WorkspaceDb::global(cx);
 6452                cx.background_spawn(async move { db.update_timestamp(database_id).await })
 6453                    .detach();
 6454            }
 6455        } else {
 6456            for pane in &self.panes {
 6457                pane.update(cx, |pane, cx| {
 6458                    if let Some(item) = pane.active_item() {
 6459                        item.workspace_deactivated(window, cx);
 6460                    }
 6461                    for item in pane.items() {
 6462                        if matches!(
 6463                            item.workspace_settings(cx).autosave,
 6464                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6465                        ) {
 6466                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6467                                .detach_and_log_err(cx);
 6468                        }
 6469                    }
 6470                });
 6471            }
 6472        }
 6473    }
 6474
 6475    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6476        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6477    }
 6478
 6479    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6480        self.active_call.as_ref().map(|(call, _)| call.clone())
 6481    }
 6482
 6483    fn on_active_call_event(
 6484        &mut self,
 6485        event: &ActiveCallEvent,
 6486        window: &mut Window,
 6487        cx: &mut Context<Self>,
 6488    ) {
 6489        match event {
 6490            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6491            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6492                self.leader_updated(participant_id, window, cx);
 6493            }
 6494        }
 6495    }
 6496
 6497    pub fn database_id(&self) -> Option<WorkspaceId> {
 6498        self.database_id
 6499    }
 6500
 6501    #[cfg(any(test, feature = "test-support"))]
 6502    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6503        self.database_id = Some(id);
 6504    }
 6505
 6506    pub fn session_id(&self) -> Option<String> {
 6507        self.session_id.clone()
 6508    }
 6509
 6510    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6511        let Some(display) = window.display(cx) else {
 6512            return Task::ready(());
 6513        };
 6514        let Ok(display_uuid) = display.uuid() else {
 6515            return Task::ready(());
 6516        };
 6517
 6518        let window_bounds = window.inner_window_bounds();
 6519        let database_id = self.database_id;
 6520        let has_paths = !self.root_paths(cx).is_empty();
 6521        let db = WorkspaceDb::global(cx);
 6522        let kvp = db::kvp::KeyValueStore::global(cx);
 6523
 6524        cx.background_executor().spawn(async move {
 6525            if !has_paths {
 6526                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6527                    .await
 6528                    .log_err();
 6529            }
 6530            if let Some(database_id) = database_id {
 6531                db.set_window_open_status(
 6532                    database_id,
 6533                    SerializedWindowBounds(window_bounds),
 6534                    display_uuid,
 6535                )
 6536                .await
 6537                .log_err();
 6538            } else {
 6539                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6540                    .await
 6541                    .log_err();
 6542            }
 6543        })
 6544    }
 6545
 6546    /// Bypass the 200ms serialization throttle and write workspace state to
 6547    /// the DB immediately. Returns a task the caller can await to ensure the
 6548    /// write completes. Used by the quit handler so the most recent state
 6549    /// isn't lost to a pending throttle timer when the process exits.
 6550    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6551        self._schedule_serialize_workspace.take();
 6552        self._serialize_workspace_task.take();
 6553        self.bounds_save_task_queued.take();
 6554
 6555        let bounds_task = self.save_window_bounds(window, cx);
 6556        let serialize_task = self.serialize_workspace_internal(window, cx);
 6557        cx.spawn(async move |_| {
 6558            bounds_task.await;
 6559            serialize_task.await;
 6560        })
 6561    }
 6562
 6563    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6564        let project = self.project().read(cx);
 6565        project
 6566            .visible_worktrees(cx)
 6567            .map(|worktree| worktree.read(cx).abs_path())
 6568            .collect::<Vec<_>>()
 6569    }
 6570
 6571    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6572        match member {
 6573            Member::Axis(PaneAxis { members, .. }) => {
 6574                for child in members.iter() {
 6575                    self.remove_panes(child.clone(), window, cx)
 6576                }
 6577            }
 6578            Member::Pane(pane) => {
 6579                self.force_remove_pane(&pane, &None, window, cx);
 6580            }
 6581        }
 6582    }
 6583
 6584    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6585        self.session_id.take();
 6586        self.serialize_workspace_internal(window, cx)
 6587    }
 6588
 6589    fn force_remove_pane(
 6590        &mut self,
 6591        pane: &Entity<Pane>,
 6592        focus_on: &Option<Entity<Pane>>,
 6593        window: &mut Window,
 6594        cx: &mut Context<Workspace>,
 6595    ) {
 6596        self.panes.retain(|p| p != pane);
 6597        if let Some(focus_on) = focus_on {
 6598            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6599        } else if self.active_pane() == pane {
 6600            let fallback_pane = self.panes.last().unwrap().clone();
 6601            if self.has_active_modal(window, cx) {
 6602                self.set_active_pane(&fallback_pane, window, cx);
 6603            } else {
 6604                fallback_pane.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6605            }
 6606        }
 6607        if self.last_active_center_pane == Some(pane.downgrade()) {
 6608            self.last_active_center_pane = None;
 6609        }
 6610        cx.notify();
 6611    }
 6612
 6613    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6614        if self._schedule_serialize_workspace.is_none() {
 6615            self._schedule_serialize_workspace =
 6616                Some(cx.spawn_in(window, async move |this, cx| {
 6617                    cx.background_executor()
 6618                        .timer(SERIALIZATION_THROTTLE_TIME)
 6619                        .await;
 6620                    this.update_in(cx, |this, window, cx| {
 6621                        this._serialize_workspace_task =
 6622                            Some(this.serialize_workspace_internal(window, cx));
 6623                        this._schedule_serialize_workspace.take();
 6624                    })
 6625                    .log_err();
 6626                }));
 6627        }
 6628    }
 6629
 6630    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6631        let Some(database_id) = self.database_id() else {
 6632            return Task::ready(());
 6633        };
 6634
 6635        fn serialize_pane_handle(
 6636            pane_handle: &Entity<Pane>,
 6637            window: &mut Window,
 6638            cx: &mut App,
 6639        ) -> SerializedPane {
 6640            let (items, active, pinned_count) = {
 6641                let pane = pane_handle.read(cx);
 6642                let active_item_id = pane.active_item().map(|item| item.item_id());
 6643                (
 6644                    pane.items()
 6645                        .filter_map(|handle| {
 6646                            let handle = handle.to_serializable_item_handle(cx)?;
 6647
 6648                            Some(SerializedItem {
 6649                                kind: Arc::from(handle.serialized_item_kind()),
 6650                                item_id: handle.item_id().as_u64(),
 6651                                active: Some(handle.item_id()) == active_item_id,
 6652                                preview: pane.is_active_preview_item(handle.item_id()),
 6653                            })
 6654                        })
 6655                        .collect::<Vec<_>>(),
 6656                    pane.has_focus(window, cx),
 6657                    pane.pinned_count(),
 6658                )
 6659            };
 6660
 6661            SerializedPane::new(items, active, pinned_count)
 6662        }
 6663
 6664        fn build_serialized_pane_group(
 6665            pane_group: &Member,
 6666            window: &mut Window,
 6667            cx: &mut App,
 6668        ) -> SerializedPaneGroup {
 6669            match pane_group {
 6670                Member::Axis(PaneAxis {
 6671                    axis,
 6672                    members,
 6673                    flexes,
 6674                    bounding_boxes: _,
 6675                }) => SerializedPaneGroup::Group {
 6676                    axis: SerializedAxis(*axis),
 6677                    children: members
 6678                        .iter()
 6679                        .map(|member| build_serialized_pane_group(member, window, cx))
 6680                        .collect::<Vec<_>>(),
 6681                    flexes: Some(flexes.lock().clone()),
 6682                },
 6683                Member::Pane(pane_handle) => {
 6684                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6685                }
 6686            }
 6687        }
 6688
 6689        fn build_serialized_docks(
 6690            this: &Workspace,
 6691            window: &mut Window,
 6692            cx: &mut App,
 6693        ) -> DockStructure {
 6694            this.capture_dock_state(window, cx)
 6695        }
 6696
 6697        match self.workspace_location(cx) {
 6698            WorkspaceLocation::Location(location, paths) => {
 6699                let bookmarks = self.project.update(cx, |project, cx| {
 6700                    project
 6701                        .bookmark_store()
 6702                        .read(cx)
 6703                        .all_serialized_bookmarks(cx)
 6704                });
 6705
 6706                let breakpoints = self.project.update(cx, |project, cx| {
 6707                    project
 6708                        .breakpoint_store()
 6709                        .read(cx)
 6710                        .all_source_breakpoints(cx)
 6711                });
 6712                let user_toolchains = self
 6713                    .project
 6714                    .read(cx)
 6715                    .user_toolchains(cx)
 6716                    .unwrap_or_default();
 6717
 6718                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6719                let docks = build_serialized_docks(self, window, cx);
 6720                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6721
 6722                let serialized_workspace = SerializedWorkspace {
 6723                    id: database_id,
 6724                    location,
 6725                    paths,
 6726                    center_group,
 6727                    window_bounds,
 6728                    display: Default::default(),
 6729                    docks,
 6730                    centered_layout: self.centered_layout,
 6731                    session_id: self.session_id.clone(),
 6732                    bookmarks,
 6733                    breakpoints,
 6734                    window_id: Some(window.window_handle().window_id().as_u64()),
 6735                    user_toolchains,
 6736                };
 6737
 6738                let db = WorkspaceDb::global(cx);
 6739                window.spawn(cx, async move |_| {
 6740                    db.save_workspace(serialized_workspace).await;
 6741                })
 6742            }
 6743            WorkspaceLocation::DetachFromSession => {
 6744                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6745                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6746                // Save dock state for empty local workspaces
 6747                let docks = build_serialized_docks(self, window, cx);
 6748                let db = WorkspaceDb::global(cx);
 6749                let kvp = db::kvp::KeyValueStore::global(cx);
 6750                window.spawn(cx, async move |_| {
 6751                    db.set_window_open_status(
 6752                        database_id,
 6753                        window_bounds,
 6754                        display.unwrap_or_default(),
 6755                    )
 6756                    .await
 6757                    .log_err();
 6758                    db.set_session_id(database_id, None).await.log_err();
 6759                    persistence::write_default_dock_state(&kvp, docks)
 6760                        .await
 6761                        .log_err();
 6762                })
 6763            }
 6764            WorkspaceLocation::None => {
 6765                // Save dock state for empty non-local workspaces
 6766                let docks = build_serialized_docks(self, window, cx);
 6767                let kvp = db::kvp::KeyValueStore::global(cx);
 6768                window.spawn(cx, async move |_| {
 6769                    persistence::write_default_dock_state(&kvp, docks)
 6770                        .await
 6771                        .log_err();
 6772                })
 6773            }
 6774        }
 6775    }
 6776
 6777    fn has_any_items_open(&self, cx: &App) -> bool {
 6778        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6779    }
 6780
 6781    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6782        let paths = PathList::new(&self.root_paths(cx));
 6783        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6784            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6785        } else if self.project.read(cx).is_local() {
 6786            if !paths.is_empty() || self.has_any_items_open(cx) {
 6787                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6788            } else {
 6789                WorkspaceLocation::DetachFromSession
 6790            }
 6791        } else {
 6792            WorkspaceLocation::None
 6793        }
 6794    }
 6795
 6796    fn update_history(&self, cx: &mut App) {
 6797        let Some(id) = self.database_id() else {
 6798            return;
 6799        };
 6800        if !self.project.read(cx).is_local() {
 6801            return;
 6802        }
 6803        if let Some(manager) = HistoryManager::global(cx) {
 6804            let paths = PathList::new(&self.root_paths(cx));
 6805            manager.update(cx, |this, cx| {
 6806                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6807            });
 6808        }
 6809    }
 6810
 6811    async fn serialize_items(
 6812        this: &WeakEntity<Self>,
 6813        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6814        cx: &mut AsyncWindowContext,
 6815    ) -> Result<()> {
 6816        const CHUNK_SIZE: usize = 200;
 6817
 6818        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6819
 6820        while let Some(items_received) = serializable_items.next().await {
 6821            let unique_items =
 6822                items_received
 6823                    .into_iter()
 6824                    .fold(HashMap::default(), |mut acc, item| {
 6825                        acc.entry(item.item_id()).or_insert(item);
 6826                        acc
 6827                    });
 6828
 6829            // We use into_iter() here so that the references to the items are moved into
 6830            // the tasks and not kept alive while we're sleeping.
 6831            for (_, item) in unique_items.into_iter() {
 6832                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6833                    item.serialize(workspace, false, window, cx)
 6834                }) {
 6835                    cx.background_spawn(async move { task.await.log_err() })
 6836                        .detach();
 6837                }
 6838            }
 6839
 6840            cx.background_executor()
 6841                .timer(SERIALIZATION_THROTTLE_TIME)
 6842                .await;
 6843        }
 6844
 6845        Ok(())
 6846    }
 6847
 6848    pub(crate) fn enqueue_item_serialization(
 6849        &mut self,
 6850        item: Box<dyn SerializableItemHandle>,
 6851    ) -> Result<()> {
 6852        self.serializable_items_tx
 6853            .unbounded_send(item)
 6854            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6855    }
 6856
 6857    pub(crate) fn load_workspace(
 6858        serialized_workspace: SerializedWorkspace,
 6859        paths_to_open: Vec<Option<ProjectPath>>,
 6860        window: &mut Window,
 6861        cx: &mut Context<Workspace>,
 6862    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6863        cx.spawn_in(window, async move |workspace, cx| {
 6864            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6865
 6866            let mut center_group = None;
 6867            let mut center_items = None;
 6868
 6869            // Traverse the splits tree and add to things
 6870            if let Some((group, active_pane, items)) = serialized_workspace
 6871                .center_group
 6872                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6873                .await
 6874            {
 6875                center_items = Some(items);
 6876                center_group = Some((group, active_pane))
 6877            }
 6878
 6879            let mut items_by_project_path = HashMap::default();
 6880            let mut item_ids_by_kind = HashMap::default();
 6881            let mut all_deserialized_items = Vec::default();
 6882            cx.update(|_, cx| {
 6883                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6884                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6885                        item_ids_by_kind
 6886                            .entry(serializable_item_handle.serialized_item_kind())
 6887                            .or_insert(Vec::new())
 6888                            .push(item.item_id().as_u64() as ItemId);
 6889                    }
 6890
 6891                    if let Some(project_path) = item.project_path(cx) {
 6892                        items_by_project_path.insert(project_path, item.clone());
 6893                    }
 6894                    all_deserialized_items.push(item);
 6895                }
 6896            })?;
 6897
 6898            let opened_items = paths_to_open
 6899                .into_iter()
 6900                .map(|path_to_open| {
 6901                    path_to_open
 6902                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6903                })
 6904                .collect::<Vec<_>>();
 6905
 6906            // Remove old panes from workspace panes list
 6907            workspace.update_in(cx, |workspace, window, cx| {
 6908                if let Some((center_group, active_pane)) = center_group {
 6909                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6910
 6911                    // Swap workspace center group
 6912                    workspace.center = PaneGroup::with_root(center_group);
 6913                    workspace.center.set_is_center(true);
 6914                    workspace.center.mark_positions(cx);
 6915
 6916                    if let Some(active_pane) = active_pane {
 6917                        workspace.set_active_pane(&active_pane, window, cx);
 6918                        cx.focus_self(window);
 6919                    } else {
 6920                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6921                    }
 6922                }
 6923
 6924                let docks = serialized_workspace.docks;
 6925
 6926                for (dock, serialized_dock) in [
 6927                    (&mut workspace.right_dock, docks.right),
 6928                    (&mut workspace.left_dock, docks.left),
 6929                    (&mut workspace.bottom_dock, docks.bottom),
 6930                ]
 6931                .iter_mut()
 6932                {
 6933                    dock.update(cx, |dock, cx| {
 6934                        dock.serialized_dock = Some(serialized_dock.clone());
 6935                        dock.restore_state(window, cx);
 6936                    });
 6937                }
 6938
 6939                cx.notify();
 6940            })?;
 6941
 6942            project
 6943                .update(cx, |project, cx| {
 6944                    project.bookmark_store().update(cx, |bookmark_store, cx| {
 6945                        bookmark_store.load_serialized_bookmarks(serialized_workspace.bookmarks, cx)
 6946                    })
 6947                })
 6948                .await
 6949                .log_err();
 6950
 6951            let _ = project
 6952                .update(cx, |project, cx| {
 6953                    project
 6954                        .breakpoint_store()
 6955                        .update(cx, |breakpoint_store, cx| {
 6956                            breakpoint_store
 6957                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6958                        })
 6959                })
 6960                .await;
 6961
 6962            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6963            // after loading the items, we might have different items and in order to avoid
 6964            // the database filling up, we delete items that haven't been loaded now.
 6965            //
 6966            // The items that have been loaded, have been saved after they've been added to the workspace.
 6967            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6968                item_ids_by_kind
 6969                    .into_iter()
 6970                    .map(|(item_kind, loaded_items)| {
 6971                        SerializableItemRegistry::cleanup(
 6972                            item_kind,
 6973                            serialized_workspace.id,
 6974                            loaded_items,
 6975                            window,
 6976                            cx,
 6977                        )
 6978                        .log_err()
 6979                    })
 6980                    .collect::<Vec<_>>()
 6981            })?;
 6982
 6983            futures::future::join_all(clean_up_tasks).await;
 6984
 6985            workspace
 6986                .update_in(cx, |workspace, window, cx| {
 6987                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6988                    workspace.serialize_workspace_internal(window, cx).detach();
 6989
 6990                    // Ensure that we mark the window as edited if we did load dirty items
 6991                    workspace.update_window_edited(window, cx);
 6992                })
 6993                .ok();
 6994
 6995            Ok(opened_items)
 6996        })
 6997    }
 6998
 6999    pub fn key_context(&self, cx: &App) -> KeyContext {
 7000        let mut context = KeyContext::new_with_defaults();
 7001        context.add("Workspace");
 7002        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 7003        if let Some(status) = self
 7004            .debugger_provider
 7005            .as_ref()
 7006            .and_then(|provider| provider.active_thread_state(cx))
 7007        {
 7008            match status {
 7009                ThreadStatus::Running | ThreadStatus::Stepping => {
 7010                    context.add("debugger_running");
 7011                }
 7012                ThreadStatus::Stopped => context.add("debugger_stopped"),
 7013                ThreadStatus::Exited | ThreadStatus::Ended => {}
 7014            }
 7015        }
 7016
 7017        if self.left_dock.read(cx).is_open() {
 7018            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 7019                context.set("left_dock", active_panel.panel_key());
 7020            }
 7021        }
 7022
 7023        if self.right_dock.read(cx).is_open() {
 7024            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 7025                context.set("right_dock", active_panel.panel_key());
 7026            }
 7027        }
 7028
 7029        if self.bottom_dock.read(cx).is_open() {
 7030            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 7031                context.set("bottom_dock", active_panel.panel_key());
 7032            }
 7033        }
 7034
 7035        context
 7036    }
 7037
 7038    /// Multiworkspace uses this to add workspace action handling to itself
 7039    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 7040        self.add_workspace_actions_listeners(div, window, cx)
 7041            .on_action(cx.listener(
 7042                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 7043                    for action in &action_sequence.0 {
 7044                        window.dispatch_action(action.boxed_clone(), cx);
 7045                    }
 7046                },
 7047            ))
 7048            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 7049            .on_action(cx.listener(Self::close_all_items_and_panes))
 7050            .on_action(cx.listener(Self::close_item_in_all_panes))
 7051            .on_action(cx.listener(Self::save_all))
 7052            .on_action(cx.listener(Self::send_keystrokes))
 7053            .on_action(cx.listener(Self::add_folder_to_project))
 7054            .on_action(cx.listener(Self::follow_next_collaborator))
 7055            .on_action(cx.listener(Self::activate_pane_at_index))
 7056            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 7057            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 7058            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 7059            .on_action(cx.listener(Self::toggle_theme_mode))
 7060            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 7061                let pane = workspace.active_pane().clone();
 7062                workspace.unfollow_in_pane(&pane, window, cx);
 7063            }))
 7064            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 7065                workspace
 7066                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 7067                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 7068            }))
 7069            .on_action(cx.listener(|workspace, _: &FormatAndSave, window, cx| {
 7070                workspace
 7071                    .save_active_item(SaveIntent::FormatAndSave, window, cx)
 7072                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 7073            }))
 7074            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 7075                workspace
 7076                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 7077                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 7078            }))
 7079            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 7080                workspace
 7081                    .save_active_item(SaveIntent::SaveAs, window, cx)
 7082                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 7083            }))
 7084            .on_action(
 7085                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 7086                    workspace.activate_previous_pane(window, cx)
 7087                }),
 7088            )
 7089            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 7090                workspace.activate_next_pane(window, cx)
 7091            }))
 7092            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 7093                workspace.activate_last_pane(window, cx)
 7094            }))
 7095            .on_action(
 7096                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 7097                    workspace.activate_next_window(cx)
 7098                }),
 7099            )
 7100            .on_action(
 7101                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 7102                    workspace.activate_previous_window(cx)
 7103                }),
 7104            )
 7105            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 7106                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 7107            }))
 7108            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 7109                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 7110            }))
 7111            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 7112                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 7113            }))
 7114            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 7115                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 7116            }))
 7117            .on_action(cx.listener(
 7118                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 7119                    workspace.move_item_to_pane_in_direction(action, window, cx)
 7120                },
 7121            ))
 7122            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 7123                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 7124            }))
 7125            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 7126                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 7127            }))
 7128            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 7129                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 7130            }))
 7131            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 7132                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 7133            }))
 7134            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 7135                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 7136                    SplitDirection::Down,
 7137                    SplitDirection::Up,
 7138                    SplitDirection::Right,
 7139                    SplitDirection::Left,
 7140                ];
 7141                for dir in DIRECTION_PRIORITY {
 7142                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 7143                        workspace.swap_pane_in_direction(dir, cx);
 7144                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 7145                        break;
 7146                    }
 7147                }
 7148            }))
 7149            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 7150                workspace.move_pane_to_border(SplitDirection::Left, cx)
 7151            }))
 7152            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 7153                workspace.move_pane_to_border(SplitDirection::Right, cx)
 7154            }))
 7155            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 7156                workspace.move_pane_to_border(SplitDirection::Up, cx)
 7157            }))
 7158            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 7159                workspace.move_pane_to_border(SplitDirection::Down, cx)
 7160            }))
 7161            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 7162                this.toggle_dock(DockPosition::Left, window, cx);
 7163            }))
 7164            .on_action(cx.listener(
 7165                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 7166                    workspace.toggle_dock(DockPosition::Right, window, cx);
 7167                },
 7168            ))
 7169            .on_action(cx.listener(
 7170                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 7171                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 7172                },
 7173            ))
 7174            .on_action(cx.listener(
 7175                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 7176                    if !workspace.close_active_dock(window, cx) {
 7177                        cx.propagate();
 7178                    }
 7179                },
 7180            ))
 7181            .on_action(
 7182                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 7183                    workspace.close_all_docks(window, cx);
 7184                }),
 7185            )
 7186            .on_action(cx.listener(Self::toggle_all_docks))
 7187            .on_action(cx.listener(
 7188                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 7189                    workspace.clear_all_notifications(cx);
 7190                },
 7191            ))
 7192            .on_action(cx.listener(
 7193                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 7194                    workspace.clear_navigation_history(window, cx);
 7195                },
 7196            ))
 7197            .on_action(cx.listener(
 7198                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 7199                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 7200                        workspace.suppress_notification(&notification_id, cx);
 7201                    }
 7202                },
 7203            ))
 7204            .on_action(cx.listener(
 7205                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 7206                    workspace.show_worktree_trust_security_modal(true, window, cx);
 7207                },
 7208            ))
 7209            .on_action(
 7210                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 7211                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 7212                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 7213                            trusted_worktrees.clear_trusted_paths()
 7214                        });
 7215                        let db = WorkspaceDb::global(cx);
 7216                        cx.spawn(async move |_, cx| {
 7217                            if db.clear_trusted_worktrees().await.log_err().is_some() {
 7218                                cx.update(|cx| reload(cx));
 7219                            }
 7220                        })
 7221                        .detach();
 7222                    }
 7223                }),
 7224            )
 7225            .on_action(cx.listener(
 7226                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 7227                    workspace.reopen_closed_item(window, cx).detach();
 7228                },
 7229            ))
 7230            .on_action(cx.listener(
 7231                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 7232                    for dock in workspace.all_docks() {
 7233                        if dock.focus_handle(cx).contains_focused(window, cx) {
 7234                            let panel = dock.read(cx).active_panel().cloned();
 7235                            if let Some(panel) = panel {
 7236                                dock.update(cx, |dock, cx| {
 7237                                    dock.set_panel_size_state(
 7238                                        panel.as_ref(),
 7239                                        dock::PanelSizeState::default(),
 7240                                        cx,
 7241                                    );
 7242                                });
 7243                            }
 7244                            return;
 7245                        }
 7246                    }
 7247                },
 7248            ))
 7249            .on_action(cx.listener(
 7250                |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
 7251                    for dock in workspace.all_docks() {
 7252                        let panel = dock.read(cx).visible_panel().cloned();
 7253                        if let Some(panel) = panel {
 7254                            dock.update(cx, |dock, cx| {
 7255                                dock.set_panel_size_state(
 7256                                    panel.as_ref(),
 7257                                    dock::PanelSizeState::default(),
 7258                                    cx,
 7259                                );
 7260                            });
 7261                        }
 7262                    }
 7263                },
 7264            ))
 7265            .on_action(cx.listener(
 7266                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 7267                    adjust_active_dock_size_by_px(
 7268                        px_with_ui_font_fallback(act.px, cx),
 7269                        workspace,
 7270                        window,
 7271                        cx,
 7272                    );
 7273                },
 7274            ))
 7275            .on_action(cx.listener(
 7276                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 7277                    adjust_active_dock_size_by_px(
 7278                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7279                        workspace,
 7280                        window,
 7281                        cx,
 7282                    );
 7283                },
 7284            ))
 7285            .on_action(cx.listener(
 7286                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 7287                    adjust_open_docks_size_by_px(
 7288                        px_with_ui_font_fallback(act.px, cx),
 7289                        workspace,
 7290                        window,
 7291                        cx,
 7292                    );
 7293                },
 7294            ))
 7295            .on_action(cx.listener(
 7296                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 7297                    adjust_open_docks_size_by_px(
 7298                        px_with_ui_font_fallback(act.px, cx) * -1.,
 7299                        workspace,
 7300                        window,
 7301                        cx,
 7302                    );
 7303                },
 7304            ))
 7305            .on_action(cx.listener(Workspace::toggle_centered_layout))
 7306            .on_action(cx.listener(
 7307                |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
 7308                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7309                        let dock = active_dock.read(cx);
 7310                        if let Some(active_panel) = dock.active_panel() {
 7311                            if active_panel.pane(cx).is_none() {
 7312                                let mut recent_pane: Option<Entity<Pane>> = None;
 7313                                let mut recent_timestamp = 0;
 7314                                for pane_handle in workspace.panes() {
 7315                                    let pane = pane_handle.read(cx);
 7316                                    for entry in pane.activation_history() {
 7317                                        if entry.timestamp > recent_timestamp {
 7318                                            recent_timestamp = entry.timestamp;
 7319                                            recent_pane = Some(pane_handle.clone());
 7320                                        }
 7321                                    }
 7322                                }
 7323
 7324                                if let Some(pane) = recent_pane {
 7325                                    let wrap_around = action.wrap_around;
 7326                                    pane.update(cx, |pane, cx| {
 7327                                        let current_index = pane.active_item_index();
 7328                                        let items_len = pane.items_len();
 7329                                        if items_len > 0 {
 7330                                            let next_index = if current_index + 1 < items_len {
 7331                                                current_index + 1
 7332                                            } else if wrap_around {
 7333                                                0
 7334                                            } else {
 7335                                                return;
 7336                                            };
 7337                                            pane.activate_item(
 7338                                                next_index, false, false, window, cx,
 7339                                            );
 7340                                        }
 7341                                    });
 7342                                    return;
 7343                                }
 7344                            }
 7345                        }
 7346                    }
 7347                    cx.propagate();
 7348                },
 7349            ))
 7350            .on_action(cx.listener(
 7351                |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
 7352                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7353                        let dock = active_dock.read(cx);
 7354                        if let Some(active_panel) = dock.active_panel() {
 7355                            if active_panel.pane(cx).is_none() {
 7356                                let mut recent_pane: Option<Entity<Pane>> = None;
 7357                                let mut recent_timestamp = 0;
 7358                                for pane_handle in workspace.panes() {
 7359                                    let pane = pane_handle.read(cx);
 7360                                    for entry in pane.activation_history() {
 7361                                        if entry.timestamp > recent_timestamp {
 7362                                            recent_timestamp = entry.timestamp;
 7363                                            recent_pane = Some(pane_handle.clone());
 7364                                        }
 7365                                    }
 7366                                }
 7367
 7368                                if let Some(pane) = recent_pane {
 7369                                    let wrap_around = action.wrap_around;
 7370                                    pane.update(cx, |pane, cx| {
 7371                                        let current_index = pane.active_item_index();
 7372                                        let items_len = pane.items_len();
 7373                                        if items_len > 0 {
 7374                                            let prev_index = if current_index > 0 {
 7375                                                current_index - 1
 7376                                            } else if wrap_around {
 7377                                                items_len.saturating_sub(1)
 7378                                            } else {
 7379                                                return;
 7380                                            };
 7381                                            pane.activate_item(
 7382                                                prev_index, false, false, window, cx,
 7383                                            );
 7384                                        }
 7385                                    });
 7386                                    return;
 7387                                }
 7388                            }
 7389                        }
 7390                    }
 7391                    cx.propagate();
 7392                },
 7393            ))
 7394            .on_action(cx.listener(
 7395                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 7396                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7397                        let dock = active_dock.read(cx);
 7398                        if let Some(active_panel) = dock.active_panel() {
 7399                            if active_panel.pane(cx).is_none() {
 7400                                let active_pane = workspace.active_pane().clone();
 7401                                active_pane.update(cx, |pane, cx| {
 7402                                    pane.close_active_item(action, window, cx)
 7403                                        .detach_and_log_err(cx);
 7404                                });
 7405                                return;
 7406                            }
 7407                        }
 7408                    }
 7409                    cx.propagate();
 7410                },
 7411            ))
 7412            .on_action(
 7413                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 7414                    let pane = workspace.active_pane().clone();
 7415                    if let Some(item) = pane.read(cx).active_item() {
 7416                        item.toggle_read_only(window, cx);
 7417                    }
 7418                }),
 7419            )
 7420            .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
 7421                workspace.focus_center_pane(window, cx);
 7422            }))
 7423            .on_action(cx.listener(Workspace::clear_bookmarks))
 7424            .on_action(cx.listener(Workspace::cancel))
 7425    }
 7426
 7427    #[cfg(any(test, feature = "test-support"))]
 7428    pub fn set_random_database_id(&mut self) {
 7429        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 7430    }
 7431
 7432    #[cfg(any(test, feature = "test-support"))]
 7433    pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 7434        use node_runtime::NodeRuntime;
 7435        use session::Session;
 7436
 7437        let client = project.read(cx).client();
 7438        let user_store = project.read(cx).user_store();
 7439        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 7440        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 7441        window.activate_window();
 7442        let app_state = Arc::new(AppState {
 7443            languages: project.read(cx).languages().clone(),
 7444            workspace_store,
 7445            client,
 7446            user_store,
 7447            fs: project.read(cx).fs().clone(),
 7448            build_window_options: |_, _| Default::default(),
 7449            node_runtime: NodeRuntime::unavailable(),
 7450            session,
 7451        });
 7452        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 7453        workspace
 7454            .active_pane
 7455            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 7456        workspace
 7457    }
 7458
 7459    pub fn register_action<A: Action>(
 7460        &mut self,
 7461        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 7462    ) -> &mut Self {
 7463        let callback = Arc::new(callback);
 7464
 7465        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 7466            let callback = callback.clone();
 7467            div.on_action(cx.listener(move |workspace, event, window, cx| {
 7468                (callback)(workspace, event, window, cx)
 7469            }))
 7470        }));
 7471        self
 7472    }
 7473    pub fn register_action_renderer(
 7474        &mut self,
 7475        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 7476    ) -> &mut Self {
 7477        self.workspace_actions.push(Box::new(callback));
 7478        self
 7479    }
 7480
 7481    fn add_workspace_actions_listeners(
 7482        &self,
 7483        mut div: Div,
 7484        window: &mut Window,
 7485        cx: &mut Context<Self>,
 7486    ) -> Div {
 7487        for action in self.workspace_actions.iter() {
 7488            div = (action)(div, self, window, cx)
 7489        }
 7490        div
 7491    }
 7492
 7493    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 7494        self.modal_layer.read(cx).has_active_modal()
 7495    }
 7496
 7497    pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
 7498        self.modal_layer
 7499            .read(cx)
 7500            .is_active_modal_command_palette(cx)
 7501    }
 7502
 7503    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7504        self.modal_layer.read(cx).active_modal()
 7505    }
 7506
 7507    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7508    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7509    /// If no modal is active, the new modal will be shown.
 7510    ///
 7511    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7512    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7513    /// will not be shown.
 7514    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7515    where
 7516        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7517    {
 7518        self.modal_layer.update(cx, |modal_layer, cx| {
 7519            modal_layer.toggle_modal(window, cx, build)
 7520        })
 7521    }
 7522
 7523    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7524        self.modal_layer
 7525            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7526    }
 7527
 7528    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7529        self.toast_layer
 7530            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7531    }
 7532
 7533    pub fn toggle_centered_layout(
 7534        &mut self,
 7535        _: &ToggleCenteredLayout,
 7536        _: &mut Window,
 7537        cx: &mut Context<Self>,
 7538    ) {
 7539        self.centered_layout = !self.centered_layout;
 7540        if let Some(database_id) = self.database_id() {
 7541            let db = WorkspaceDb::global(cx);
 7542            let centered_layout = self.centered_layout;
 7543            cx.background_spawn(async move {
 7544                db.set_centered_layout(database_id, centered_layout).await
 7545            })
 7546            .detach_and_log_err(cx);
 7547        }
 7548        cx.notify();
 7549    }
 7550
 7551    pub fn clear_bookmarks(&mut self, _: &ClearBookmarks, _: &mut Window, cx: &mut Context<Self>) {
 7552        self.project()
 7553            .read(cx)
 7554            .bookmark_store()
 7555            .update(cx, |bookmark_store, cx| {
 7556                bookmark_store.clear_bookmarks(cx);
 7557            });
 7558    }
 7559
 7560    fn adjust_padding(padding: Option<f32>) -> f32 {
 7561        padding
 7562            .unwrap_or(CenteredPaddingSettings::default().0)
 7563            .clamp(
 7564                CenteredPaddingSettings::MIN_PADDING,
 7565                CenteredPaddingSettings::MAX_PADDING,
 7566            )
 7567    }
 7568
 7569    fn render_dock(
 7570        &self,
 7571        position: DockPosition,
 7572        dock: &Entity<Dock>,
 7573        window: &mut Window,
 7574        cx: &mut App,
 7575    ) -> Option<Div> {
 7576        if self.zoomed_position == Some(position) {
 7577            return None;
 7578        }
 7579
 7580        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7581            let pane = panel.pane(cx)?;
 7582            let follower_states = &self.follower_states;
 7583            leader_border_for_pane(follower_states, &pane, window, cx)
 7584        });
 7585
 7586        let mut container = div()
 7587            .flex()
 7588            .overflow_hidden()
 7589            .flex_none()
 7590            .child(dock.clone())
 7591            .children(leader_border);
 7592
 7593        // Apply sizing only when the dock is open. When closed the dock is still
 7594        // included in the element tree so its focus handle remains mounted — without
 7595        // this, toggle_panel_focus cannot focus the panel when the dock is closed.
 7596        let dock = dock.read(cx);
 7597        if let Some(panel) = dock.visible_panel() {
 7598            let size_state = dock.stored_panel_size_state(panel.as_ref());
 7599            let min_size = panel.min_size(window, cx);
 7600            if position.axis() == Axis::Horizontal {
 7601                let use_flexible = panel.has_flexible_size(window, cx);
 7602                let flex_grow = if use_flexible {
 7603                    size_state
 7604                        .and_then(|state| state.flex)
 7605                        .or_else(|| self.default_dock_flex(position))
 7606                } else {
 7607                    None
 7608                };
 7609                if let Some(grow) = flex_grow {
 7610                    let grow = (grow / self.center_full_height_column_count()).max(0.001);
 7611                    let style = container.style();
 7612                    style.flex_grow = Some(grow);
 7613                    style.flex_shrink = Some(1.0);
 7614                    style.flex_basis = Some(relative(0.).into());
 7615                } else {
 7616                    let size = size_state
 7617                        .and_then(|state| state.size)
 7618                        .unwrap_or_else(|| panel.default_size(window, cx));
 7619                    container = container.w(size);
 7620                }
 7621                if let Some(min) = min_size {
 7622                    container = container.min_w(min);
 7623                }
 7624            } else {
 7625                let size = size_state
 7626                    .and_then(|state| state.size)
 7627                    .unwrap_or_else(|| panel.default_size(window, cx));
 7628                container = container.h(size);
 7629            }
 7630        }
 7631
 7632        Some(container)
 7633    }
 7634
 7635    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7636        window
 7637            .root::<MultiWorkspace>()
 7638            .flatten()
 7639            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7640    }
 7641
 7642    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7643        self.zoomed.as_ref()
 7644    }
 7645
 7646    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7647        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7648            return;
 7649        };
 7650        let windows = cx.windows();
 7651        let next_window =
 7652            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7653                || {
 7654                    windows
 7655                        .iter()
 7656                        .cycle()
 7657                        .skip_while(|window| window.window_id() != current_window_id)
 7658                        .nth(1)
 7659                },
 7660            );
 7661
 7662        if let Some(window) = next_window {
 7663            window
 7664                .update(cx, |_, window, _| window.activate_window())
 7665                .ok();
 7666        }
 7667    }
 7668
 7669    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7670        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7671            return;
 7672        };
 7673        let windows = cx.windows();
 7674        let prev_window =
 7675            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7676                || {
 7677                    windows
 7678                        .iter()
 7679                        .rev()
 7680                        .cycle()
 7681                        .skip_while(|window| window.window_id() != current_window_id)
 7682                        .nth(1)
 7683                },
 7684            );
 7685
 7686        if let Some(window) = prev_window {
 7687            window
 7688                .update(cx, |_, window, _| window.activate_window())
 7689                .ok();
 7690        }
 7691    }
 7692
 7693    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7694        if cx.stop_active_drag(window) {
 7695        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7696            dismiss_app_notification(&notification_id, cx);
 7697        } else {
 7698            cx.propagate();
 7699        }
 7700    }
 7701
 7702    fn resize_dock(
 7703        &mut self,
 7704        dock_pos: DockPosition,
 7705        new_size: Pixels,
 7706        window: &mut Window,
 7707        cx: &mut Context<Self>,
 7708    ) {
 7709        match dock_pos {
 7710            DockPosition::Left => self.resize_left_dock(new_size, window, cx),
 7711            DockPosition::Right => self.resize_right_dock(new_size, window, cx),
 7712            DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
 7713        }
 7714    }
 7715
 7716    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7717        let workspace_width = self.bounds.size.width;
 7718        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7719
 7720        self.right_dock.read_with(cx, |right_dock, cx| {
 7721            let right_dock_size = right_dock
 7722                .stored_active_panel_size(window, cx)
 7723                .unwrap_or(Pixels::ZERO);
 7724            if right_dock_size + size > workspace_width {
 7725                size = workspace_width - right_dock_size
 7726            }
 7727        });
 7728
 7729        let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
 7730        self.left_dock.update(cx, |left_dock, cx| {
 7731            if WorkspaceSettings::get_global(cx)
 7732                .resize_all_panels_in_dock
 7733                .contains(&DockPosition::Left)
 7734            {
 7735                left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7736            } else {
 7737                left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7738            }
 7739        });
 7740    }
 7741
 7742    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7743        let workspace_width = self.bounds.size.width;
 7744        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7745        self.left_dock.read_with(cx, |left_dock, cx| {
 7746            let left_dock_size = left_dock
 7747                .stored_active_panel_size(window, cx)
 7748                .unwrap_or(Pixels::ZERO);
 7749            if left_dock_size + size > workspace_width {
 7750                size = workspace_width - left_dock_size
 7751            }
 7752        });
 7753        let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
 7754        self.right_dock.update(cx, |right_dock, cx| {
 7755            if WorkspaceSettings::get_global(cx)
 7756                .resize_all_panels_in_dock
 7757                .contains(&DockPosition::Right)
 7758            {
 7759                right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
 7760            } else {
 7761                right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
 7762            }
 7763        });
 7764    }
 7765
 7766    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7767        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7768        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7769            if WorkspaceSettings::get_global(cx)
 7770                .resize_all_panels_in_dock
 7771                .contains(&DockPosition::Bottom)
 7772            {
 7773                bottom_dock.resize_all_panels(Some(size), None, window, cx);
 7774            } else {
 7775                bottom_dock.resize_active_panel(Some(size), None, window, cx);
 7776            }
 7777        });
 7778    }
 7779
 7780    fn toggle_edit_predictions_all_files(
 7781        &mut self,
 7782        _: &ToggleEditPrediction,
 7783        _window: &mut Window,
 7784        cx: &mut Context<Self>,
 7785    ) {
 7786        let fs = self.project().read(cx).fs().clone();
 7787        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7788        update_settings_file(fs, cx, move |file, _| {
 7789            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7790        });
 7791    }
 7792
 7793    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7794        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7795        let next_mode = match current_mode {
 7796            Some(theme_settings::ThemeAppearanceMode::Light) => {
 7797                theme_settings::ThemeAppearanceMode::Dark
 7798            }
 7799            Some(theme_settings::ThemeAppearanceMode::Dark) => {
 7800                theme_settings::ThemeAppearanceMode::Light
 7801            }
 7802            Some(theme_settings::ThemeAppearanceMode::System) | None => {
 7803                match cx.theme().appearance() {
 7804                    theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
 7805                    theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
 7806                }
 7807            }
 7808        };
 7809
 7810        let fs = self.project().read(cx).fs().clone();
 7811        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7812            theme_settings::set_mode(settings, next_mode);
 7813        });
 7814    }
 7815
 7816    pub fn show_worktree_trust_security_modal(
 7817        &mut self,
 7818        toggle: bool,
 7819        window: &mut Window,
 7820        cx: &mut Context<Self>,
 7821    ) {
 7822        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7823            if toggle {
 7824                security_modal.update(cx, |security_modal, cx| {
 7825                    security_modal.dismiss(cx);
 7826                })
 7827            } else {
 7828                security_modal.update(cx, |security_modal, cx| {
 7829                    security_modal.refresh_restricted_paths(cx);
 7830                });
 7831            }
 7832        } else {
 7833            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7834                .map(|trusted_worktrees| {
 7835                    trusted_worktrees
 7836                        .read(cx)
 7837                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7838                })
 7839                .unwrap_or(false);
 7840            if has_restricted_worktrees {
 7841                let project = self.project().read(cx);
 7842                let remote_host = project
 7843                    .remote_connection_options(cx)
 7844                    .map(RemoteHostLocation::from);
 7845                let worktree_store = project.worktree_store().downgrade();
 7846                self.toggle_modal(window, cx, |_, cx| {
 7847                    SecurityModal::new(worktree_store, remote_host, cx)
 7848                });
 7849            }
 7850        }
 7851    }
 7852}
 7853
 7854pub trait AnyActiveCall {
 7855    fn entity(&self) -> AnyEntity;
 7856    fn is_in_room(&self, _: &App) -> bool;
 7857    fn room_id(&self, _: &App) -> Option<u64>;
 7858    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7859    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7860    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7861    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7862    fn is_sharing_project(&self, _: &App) -> bool;
 7863    fn has_remote_participants(&self, _: &App) -> bool;
 7864    fn local_participant_is_guest(&self, _: &App) -> bool;
 7865    fn client(&self, _: &App) -> Arc<Client>;
 7866    fn share_on_join(&self, _: &App) -> bool;
 7867    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7868    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7869    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7870    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7871    fn join_project(
 7872        &self,
 7873        _: u64,
 7874        _: Arc<LanguageRegistry>,
 7875        _: Arc<dyn Fs>,
 7876        _: &mut App,
 7877    ) -> Task<Result<Entity<Project>>>;
 7878    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7879    fn subscribe(
 7880        &self,
 7881        _: &mut Window,
 7882        _: &mut Context<Workspace>,
 7883        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7884    ) -> Subscription;
 7885    fn create_shared_screen(
 7886        &self,
 7887        _: PeerId,
 7888        _: &Entity<Pane>,
 7889        _: &mut Window,
 7890        _: &mut App,
 7891    ) -> Option<Entity<SharedScreen>>;
 7892}
 7893
 7894#[derive(Clone)]
 7895pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7896impl Global for GlobalAnyActiveCall {}
 7897
 7898impl GlobalAnyActiveCall {
 7899    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7900        cx.try_global()
 7901    }
 7902
 7903    pub(crate) fn global(cx: &App) -> &Self {
 7904        cx.global()
 7905    }
 7906}
 7907
 7908/// Workspace-local view of a remote participant's location.
 7909#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7910pub enum ParticipantLocation {
 7911    SharedProject { project_id: u64 },
 7912    UnsharedProject,
 7913    External,
 7914}
 7915
 7916impl ParticipantLocation {
 7917    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7918        match location
 7919            .and_then(|l| l.variant)
 7920            .context("participant location was not provided")?
 7921        {
 7922            proto::participant_location::Variant::SharedProject(project) => {
 7923                Ok(Self::SharedProject {
 7924                    project_id: project.id,
 7925                })
 7926            }
 7927            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7928            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7929        }
 7930    }
 7931}
 7932/// Workspace-local view of a remote collaborator's state.
 7933/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7934#[derive(Clone)]
 7935pub struct RemoteCollaborator {
 7936    pub user: Arc<User>,
 7937    pub peer_id: PeerId,
 7938    pub location: ParticipantLocation,
 7939    pub participant_index: ParticipantIndex,
 7940}
 7941
 7942pub enum ActiveCallEvent {
 7943    ParticipantLocationChanged { participant_id: PeerId },
 7944    RemoteVideoTracksChanged { participant_id: PeerId },
 7945}
 7946
 7947fn leader_border_for_pane(
 7948    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7949    pane: &Entity<Pane>,
 7950    _: &Window,
 7951    cx: &App,
 7952) -> Option<Div> {
 7953    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7954        if state.pane() == pane {
 7955            Some((*leader_id, state))
 7956        } else {
 7957            None
 7958        }
 7959    })?;
 7960
 7961    let mut leader_color = match leader_id {
 7962        CollaboratorId::PeerId(leader_peer_id) => {
 7963            let leader = GlobalAnyActiveCall::try_global(cx)?
 7964                .0
 7965                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7966
 7967            cx.theme()
 7968                .players()
 7969                .color_for_participant(leader.participant_index.0)
 7970                .cursor
 7971        }
 7972        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7973    };
 7974    leader_color.fade_out(0.3);
 7975    Some(
 7976        div()
 7977            .absolute()
 7978            .size_full()
 7979            .left_0()
 7980            .top_0()
 7981            .border_2()
 7982            .border_color(leader_color),
 7983    )
 7984}
 7985
 7986fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7987    ZED_WINDOW_POSITION
 7988        .zip(*ZED_WINDOW_SIZE)
 7989        .map(|(position, size)| Bounds {
 7990            origin: position,
 7991            size,
 7992        })
 7993}
 7994
 7995fn open_items(
 7996    serialized_workspace: Option<SerializedWorkspace>,
 7997    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7998    window: &mut Window,
 7999    cx: &mut Context<Workspace>,
 8000) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 8001    let restored_items = serialized_workspace.map(|serialized_workspace| {
 8002        Workspace::load_workspace(
 8003            serialized_workspace,
 8004            project_paths_to_open
 8005                .iter()
 8006                .map(|(_, project_path)| project_path)
 8007                .cloned()
 8008                .collect(),
 8009            window,
 8010            cx,
 8011        )
 8012    });
 8013
 8014    cx.spawn_in(window, async move |workspace, cx| {
 8015        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 8016
 8017        if let Some(restored_items) = restored_items {
 8018            let restored_items = restored_items.await?;
 8019
 8020            let restored_project_paths = restored_items
 8021                .iter()
 8022                .filter_map(|item| {
 8023                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 8024                        .ok()
 8025                        .flatten()
 8026                })
 8027                .collect::<HashSet<_>>();
 8028
 8029            for restored_item in restored_items {
 8030                opened_items.push(restored_item.map(Ok));
 8031            }
 8032
 8033            project_paths_to_open
 8034                .iter_mut()
 8035                .for_each(|(_, project_path)| {
 8036                    if let Some(project_path_to_open) = project_path
 8037                        && restored_project_paths.contains(project_path_to_open)
 8038                    {
 8039                        *project_path = None;
 8040                    }
 8041                });
 8042        } else {
 8043            for _ in 0..project_paths_to_open.len() {
 8044                opened_items.push(None);
 8045            }
 8046        }
 8047        assert!(opened_items.len() == project_paths_to_open.len());
 8048
 8049        let tasks =
 8050            project_paths_to_open
 8051                .into_iter()
 8052                .enumerate()
 8053                .map(|(ix, (abs_path, project_path))| {
 8054                    let workspace = workspace.clone();
 8055                    cx.spawn(async move |cx| {
 8056                        let file_project_path = project_path?;
 8057                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 8058                            workspace.project().update(cx, |project, cx| {
 8059                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 8060                            })
 8061                        });
 8062
 8063                        // We only want to open file paths here. If one of the items
 8064                        // here is a directory, it was already opened further above
 8065                        // with a `find_or_create_worktree`.
 8066                        if let Ok(task) = abs_path_task
 8067                            && task.await.is_none_or(|p| p.is_file())
 8068                        {
 8069                            return Some((
 8070                                ix,
 8071                                workspace
 8072                                    .update_in(cx, |workspace, window, cx| {
 8073                                        workspace.open_path(
 8074                                            file_project_path,
 8075                                            None,
 8076                                            true,
 8077                                            window,
 8078                                            cx,
 8079                                        )
 8080                                    })
 8081                                    .log_err()?
 8082                                    .await,
 8083                            ));
 8084                        }
 8085                        None
 8086                    })
 8087                });
 8088
 8089        let tasks = tasks.collect::<Vec<_>>();
 8090
 8091        let tasks = futures::future::join_all(tasks);
 8092        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 8093            opened_items[ix] = Some(path_open_result);
 8094        }
 8095
 8096        Ok(opened_items)
 8097    })
 8098}
 8099
 8100#[derive(Clone)]
 8101enum ActivateInDirectionTarget {
 8102    Pane(Entity<Pane>),
 8103    Dock(Entity<Dock>),
 8104    Sidebar(FocusHandle),
 8105}
 8106
 8107fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 8108    window
 8109        .update(cx, |multi_workspace, _, cx| {
 8110            let workspace = multi_workspace.workspace().clone();
 8111            workspace.update(cx, |workspace, cx| {
 8112                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 8113                    struct DatabaseFailedNotification;
 8114
 8115                    workspace.show_notification(
 8116                        NotificationId::unique::<DatabaseFailedNotification>(),
 8117                        cx,
 8118                        |cx| {
 8119                            cx.new(|cx| {
 8120                                MessageNotification::new("Failed to load the database file.", cx)
 8121                                    .primary_message("File an Issue")
 8122                                    .primary_icon(IconName::Plus)
 8123                                    .primary_on_click(|window, cx| {
 8124                                        window.dispatch_action(Box::new(FileBugReport), cx)
 8125                                    })
 8126                            })
 8127                        },
 8128                    );
 8129                }
 8130            });
 8131        })
 8132        .log_err();
 8133}
 8134
 8135fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 8136    if val == 0 {
 8137        ThemeSettings::get_global(cx).ui_font_size(cx)
 8138    } else {
 8139        px(val as f32)
 8140    }
 8141}
 8142
 8143fn adjust_active_dock_size_by_px(
 8144    px: Pixels,
 8145    workspace: &mut Workspace,
 8146    window: &mut Window,
 8147    cx: &mut Context<Workspace>,
 8148) {
 8149    let Some(active_dock) = workspace
 8150        .all_docks()
 8151        .into_iter()
 8152        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 8153    else {
 8154        return;
 8155    };
 8156    let dock = active_dock.read(cx);
 8157    let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
 8158        return;
 8159    };
 8160    workspace.resize_dock(dock.position(), panel_size + px, window, cx);
 8161}
 8162
 8163fn adjust_open_docks_size_by_px(
 8164    px: Pixels,
 8165    workspace: &mut Workspace,
 8166    window: &mut Window,
 8167    cx: &mut Context<Workspace>,
 8168) {
 8169    let docks = workspace
 8170        .all_docks()
 8171        .into_iter()
 8172        .filter_map(|dock_entity| {
 8173            let dock = dock_entity.read(cx);
 8174            if dock.is_open() {
 8175                let dock_pos = dock.position();
 8176                let panel_size = workspace.dock_size(&dock, window, cx)?;
 8177                Some((dock_pos, panel_size + px))
 8178            } else {
 8179                None
 8180            }
 8181        })
 8182        .collect::<Vec<_>>();
 8183
 8184    for (position, new_size) in docks {
 8185        workspace.resize_dock(position, new_size, window, cx);
 8186    }
 8187}
 8188
 8189impl Focusable for Workspace {
 8190    fn focus_handle(&self, cx: &App) -> FocusHandle {
 8191        self.active_pane.focus_handle(cx)
 8192    }
 8193}
 8194
 8195#[derive(Clone)]
 8196struct DraggedDock(DockPosition);
 8197
 8198impl Render for DraggedDock {
 8199    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 8200        gpui::Empty
 8201    }
 8202}
 8203
 8204impl Render for Workspace {
 8205    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 8206        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 8207        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 8208            log::info!("Rendered first frame");
 8209        }
 8210
 8211        let centered_layout = self.centered_layout
 8212            && self.center.panes().len() == 1
 8213            && self.active_item(cx).is_some();
 8214        let render_padding = |size| {
 8215            (size > 0.0).then(|| {
 8216                div()
 8217                    .h_full()
 8218                    .w(relative(size))
 8219                    .bg(cx.theme().colors().editor_background)
 8220                    .border_color(cx.theme().colors().pane_group_border)
 8221            })
 8222        };
 8223        let paddings = if centered_layout {
 8224            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 8225            (
 8226                render_padding(Self::adjust_padding(
 8227                    settings.left_padding.map(|padding| padding.0),
 8228                )),
 8229                render_padding(Self::adjust_padding(
 8230                    settings.right_padding.map(|padding| padding.0),
 8231                )),
 8232            )
 8233        } else {
 8234            (None, None)
 8235        };
 8236        let ui_font = theme_settings::setup_ui_font(window, cx);
 8237
 8238        let theme = cx.theme().clone();
 8239        let colors = theme.colors();
 8240        let notification_entities = self
 8241            .notifications
 8242            .iter()
 8243            .map(|(_, notification)| notification.entity_id())
 8244            .collect::<Vec<_>>();
 8245        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 8246
 8247        let pane_render_context = PaneRenderContext {
 8248            follower_states: &self.follower_states,
 8249            active_call: self.active_call(),
 8250            active_pane: &self.active_pane,
 8251            app_state: &self.app_state,
 8252            project: &self.project,
 8253            workspace: &self.weak_self,
 8254        };
 8255
 8256        div()
 8257            .relative()
 8258            .size_full()
 8259            .flex()
 8260            .flex_col()
 8261            .font(ui_font)
 8262            .gap_0()
 8263            .justify_start()
 8264            .items_start()
 8265            .text_color(colors.text)
 8266            .overflow_hidden()
 8267            .children(self.titlebar_item.clone())
 8268            .on_modifiers_changed(move |_, _, cx| {
 8269                for &id in &notification_entities {
 8270                    cx.notify(id);
 8271                }
 8272            })
 8273            .child(
 8274                div()
 8275                    .size_full()
 8276                    .relative()
 8277                    .flex_1()
 8278                    .flex()
 8279                    .flex_col()
 8280                    .child(
 8281                        div()
 8282                            .id("workspace")
 8283                            .bg(colors.background)
 8284                            .relative()
 8285                            .flex_1()
 8286                            .w_full()
 8287                            .flex()
 8288                            .flex_col()
 8289                            .overflow_hidden()
 8290                            .border_t_1()
 8291                            .border_b_1()
 8292                            .border_color(colors.border)
 8293                            .child({
 8294                                let this = cx.entity();
 8295                                canvas(
 8296                                    move |bounds, window, cx| {
 8297                                        this.update(cx, |this, cx| {
 8298                                            let bounds_changed = this.bounds != bounds;
 8299                                            this.bounds = bounds;
 8300
 8301                                            if bounds_changed {
 8302                                                this.left_dock.update(cx, |dock, cx| {
 8303                                                    dock.clamp_panel_size(
 8304                                                        bounds.size.width,
 8305                                                        window,
 8306                                                        cx,
 8307                                                    )
 8308                                                });
 8309
 8310                                                this.right_dock.update(cx, |dock, cx| {
 8311                                                    dock.clamp_panel_size(
 8312                                                        bounds.size.width,
 8313                                                        window,
 8314                                                        cx,
 8315                                                    )
 8316                                                });
 8317
 8318                                                this.bottom_dock.update(cx, |dock, cx| {
 8319                                                    dock.clamp_panel_size(
 8320                                                        bounds.size.height,
 8321                                                        window,
 8322                                                        cx,
 8323                                                    )
 8324                                                });
 8325                                            }
 8326                                        })
 8327                                    },
 8328                                    |_, _, _, _| {},
 8329                                )
 8330                                .absolute()
 8331                                .size_full()
 8332                            })
 8333                            .when(self.zoomed.is_none(), |this| {
 8334                                this.on_drag_move(cx.listener(
 8335                                    move |workspace, e: &DragMoveEvent<DraggedDock>, window, cx| {
 8336                                        if workspace.previous_dock_drag_coordinates
 8337                                            != Some(e.event.position)
 8338                                        {
 8339                                            workspace.previous_dock_drag_coordinates =
 8340                                                Some(e.event.position);
 8341
 8342                                            match e.drag(cx).0 {
 8343                                                DockPosition::Left => {
 8344                                                    workspace.resize_left_dock(
 8345                                                        e.event.position.x
 8346                                                            - workspace.bounds.left(),
 8347                                                        window,
 8348                                                        cx,
 8349                                                    );
 8350                                                }
 8351                                                DockPosition::Right => {
 8352                                                    workspace.resize_right_dock(
 8353                                                        workspace.bounds.right()
 8354                                                            - e.event.position.x,
 8355                                                        window,
 8356                                                        cx,
 8357                                                    );
 8358                                                }
 8359                                                DockPosition::Bottom => {
 8360                                                    workspace.resize_bottom_dock(
 8361                                                        workspace.bounds.bottom()
 8362                                                            - e.event.position.y,
 8363                                                        window,
 8364                                                        cx,
 8365                                                    );
 8366                                                }
 8367                                            };
 8368                                            workspace.serialize_workspace(window, cx);
 8369                                        }
 8370                                    },
 8371                                ))
 8372                            })
 8373                            .child({
 8374                                match bottom_dock_layout {
 8375                                    BottomDockLayout::Full => div()
 8376                                        .flex()
 8377                                        .flex_col()
 8378                                        .h_full()
 8379                                        .child(
 8380                                            div()
 8381                                                .flex()
 8382                                                .flex_row()
 8383                                                .flex_1()
 8384                                                .overflow_hidden()
 8385                                                .children(self.render_dock(
 8386                                                    DockPosition::Left,
 8387                                                    &self.left_dock,
 8388                                                    window,
 8389                                                    cx,
 8390                                                ))
 8391                                                .child(
 8392                                                    div()
 8393                                                        .flex()
 8394                                                        .flex_col()
 8395                                                        .flex_1()
 8396                                                        .overflow_hidden()
 8397                                                        .child(
 8398                                                            h_flex()
 8399                                                                .flex_1()
 8400                                                                .when_some(paddings.0, |this, p| {
 8401                                                                    this.child(p.border_r_1())
 8402                                                                })
 8403                                                                .child(self.center.render(
 8404                                                                    self.zoomed.as_ref(),
 8405                                                                    &pane_render_context,
 8406                                                                    window,
 8407                                                                    cx,
 8408                                                                ))
 8409                                                                .when_some(
 8410                                                                    paddings.1,
 8411                                                                    |this, p| {
 8412                                                                        this.child(p.border_l_1())
 8413                                                                    },
 8414                                                                ),
 8415                                                        ),
 8416                                                )
 8417                                                .children(self.render_dock(
 8418                                                    DockPosition::Right,
 8419                                                    &self.right_dock,
 8420                                                    window,
 8421                                                    cx,
 8422                                                )),
 8423                                        )
 8424                                        .child(div().w_full().children(self.render_dock(
 8425                                            DockPosition::Bottom,
 8426                                            &self.bottom_dock,
 8427                                            window,
 8428                                            cx,
 8429                                        ))),
 8430
 8431                                    BottomDockLayout::LeftAligned => div()
 8432                                        .flex()
 8433                                        .flex_row()
 8434                                        .h_full()
 8435                                        .child(
 8436                                            div()
 8437                                                .flex()
 8438                                                .flex_col()
 8439                                                .flex_1()
 8440                                                .h_full()
 8441                                                .child(
 8442                                                    div()
 8443                                                        .flex()
 8444                                                        .flex_row()
 8445                                                        .flex_1()
 8446                                                        .children(self.render_dock(
 8447                                                            DockPosition::Left,
 8448                                                            &self.left_dock,
 8449                                                            window,
 8450                                                            cx,
 8451                                                        ))
 8452                                                        .child(
 8453                                                            div()
 8454                                                                .flex()
 8455                                                                .flex_col()
 8456                                                                .flex_1()
 8457                                                                .overflow_hidden()
 8458                                                                .child(
 8459                                                                    h_flex()
 8460                                                                        .flex_1()
 8461                                                                        .when_some(
 8462                                                                            paddings.0,
 8463                                                                            |this, p| {
 8464                                                                                this.child(
 8465                                                                                    p.border_r_1(),
 8466                                                                                )
 8467                                                                            },
 8468                                                                        )
 8469                                                                        .child(self.center.render(
 8470                                                                            self.zoomed.as_ref(),
 8471                                                                            &pane_render_context,
 8472                                                                            window,
 8473                                                                            cx,
 8474                                                                        ))
 8475                                                                        .when_some(
 8476                                                                            paddings.1,
 8477                                                                            |this, p| {
 8478                                                                                this.child(
 8479                                                                                    p.border_l_1(),
 8480                                                                                )
 8481                                                                            },
 8482                                                                        ),
 8483                                                                ),
 8484                                                        ),
 8485                                                )
 8486                                                .child(div().w_full().children(self.render_dock(
 8487                                                    DockPosition::Bottom,
 8488                                                    &self.bottom_dock,
 8489                                                    window,
 8490                                                    cx,
 8491                                                ))),
 8492                                        )
 8493                                        .children(self.render_dock(
 8494                                            DockPosition::Right,
 8495                                            &self.right_dock,
 8496                                            window,
 8497                                            cx,
 8498                                        )),
 8499                                    BottomDockLayout::RightAligned => div()
 8500                                        .flex()
 8501                                        .flex_row()
 8502                                        .h_full()
 8503                                        .children(self.render_dock(
 8504                                            DockPosition::Left,
 8505                                            &self.left_dock,
 8506                                            window,
 8507                                            cx,
 8508                                        ))
 8509                                        .child(
 8510                                            div()
 8511                                                .flex()
 8512                                                .flex_col()
 8513                                                .flex_1()
 8514                                                .h_full()
 8515                                                .child(
 8516                                                    div()
 8517                                                        .flex()
 8518                                                        .flex_row()
 8519                                                        .flex_1()
 8520                                                        .child(
 8521                                                            div()
 8522                                                                .flex()
 8523                                                                .flex_col()
 8524                                                                .flex_1()
 8525                                                                .overflow_hidden()
 8526                                                                .child(
 8527                                                                    h_flex()
 8528                                                                        .flex_1()
 8529                                                                        .when_some(
 8530                                                                            paddings.0,
 8531                                                                            |this, p| {
 8532                                                                                this.child(
 8533                                                                                    p.border_r_1(),
 8534                                                                                )
 8535                                                                            },
 8536                                                                        )
 8537                                                                        .child(self.center.render(
 8538                                                                            self.zoomed.as_ref(),
 8539                                                                            &pane_render_context,
 8540                                                                            window,
 8541                                                                            cx,
 8542                                                                        ))
 8543                                                                        .when_some(
 8544                                                                            paddings.1,
 8545                                                                            |this, p| {
 8546                                                                                this.child(
 8547                                                                                    p.border_l_1(),
 8548                                                                                )
 8549                                                                            },
 8550                                                                        ),
 8551                                                                ),
 8552                                                        )
 8553                                                        .children(self.render_dock(
 8554                                                            DockPosition::Right,
 8555                                                            &self.right_dock,
 8556                                                            window,
 8557                                                            cx,
 8558                                                        )),
 8559                                                )
 8560                                                .child(div().w_full().children(self.render_dock(
 8561                                                    DockPosition::Bottom,
 8562                                                    &self.bottom_dock,
 8563                                                    window,
 8564                                                    cx,
 8565                                                ))),
 8566                                        ),
 8567                                    BottomDockLayout::Contained => div()
 8568                                        .flex()
 8569                                        .flex_row()
 8570                                        .h_full()
 8571                                        .children(self.render_dock(
 8572                                            DockPosition::Left,
 8573                                            &self.left_dock,
 8574                                            window,
 8575                                            cx,
 8576                                        ))
 8577                                        .child(
 8578                                            div()
 8579                                                .flex()
 8580                                                .flex_col()
 8581                                                .flex_1()
 8582                                                .overflow_hidden()
 8583                                                .child(
 8584                                                    h_flex()
 8585                                                        .flex_1()
 8586                                                        .when_some(paddings.0, |this, p| {
 8587                                                            this.child(p.border_r_1())
 8588                                                        })
 8589                                                        .child(self.center.render(
 8590                                                            self.zoomed.as_ref(),
 8591                                                            &pane_render_context,
 8592                                                            window,
 8593                                                            cx,
 8594                                                        ))
 8595                                                        .when_some(paddings.1, |this, p| {
 8596                                                            this.child(p.border_l_1())
 8597                                                        }),
 8598                                                )
 8599                                                .children(self.render_dock(
 8600                                                    DockPosition::Bottom,
 8601                                                    &self.bottom_dock,
 8602                                                    window,
 8603                                                    cx,
 8604                                                )),
 8605                                        )
 8606                                        .children(self.render_dock(
 8607                                            DockPosition::Right,
 8608                                            &self.right_dock,
 8609                                            window,
 8610                                            cx,
 8611                                        )),
 8612                                }
 8613                            })
 8614                            .children(self.zoomed.as_ref().and_then(|view| {
 8615                                let zoomed_view = view.upgrade()?;
 8616                                let div = div()
 8617                                    .occlude()
 8618                                    .absolute()
 8619                                    .overflow_hidden()
 8620                                    .border_color(colors.border)
 8621                                    .bg(colors.background)
 8622                                    .child(zoomed_view)
 8623                                    .inset_0()
 8624                                    .shadow_lg();
 8625
 8626                                if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8627                                    return Some(div);
 8628                                }
 8629
 8630                                Some(match self.zoomed_position {
 8631                                    Some(DockPosition::Left) => div.right_2().border_r_1(),
 8632                                    Some(DockPosition::Right) => div.left_2().border_l_1(),
 8633                                    Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8634                                    None => div.top_2().bottom_2().left_2().right_2().border_1(),
 8635                                })
 8636                            }))
 8637                            .children(self.render_notifications(window, cx)),
 8638                    )
 8639                    .when(self.status_bar_visible(cx), |parent| {
 8640                        parent.child(self.status_bar.clone())
 8641                    })
 8642                    .child(self.toast_layer.clone()),
 8643            )
 8644    }
 8645}
 8646
 8647impl WorkspaceStore {
 8648    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8649        Self {
 8650            workspaces: Default::default(),
 8651            _subscriptions: vec![
 8652                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8653                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8654            ],
 8655            client,
 8656        }
 8657    }
 8658
 8659    pub fn update_followers(
 8660        &self,
 8661        project_id: Option<u64>,
 8662        update: proto::update_followers::Variant,
 8663        cx: &App,
 8664    ) -> Option<()> {
 8665        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8666        let room_id = active_call.0.room_id(cx)?;
 8667        self.client
 8668            .send(proto::UpdateFollowers {
 8669                room_id,
 8670                project_id,
 8671                variant: Some(update),
 8672            })
 8673            .log_err()
 8674    }
 8675
 8676    pub async fn handle_follow(
 8677        this: Entity<Self>,
 8678        envelope: TypedEnvelope<proto::Follow>,
 8679        mut cx: AsyncApp,
 8680    ) -> Result<proto::FollowResponse> {
 8681        this.update(&mut cx, |this, cx| {
 8682            let follower = Follower {
 8683                project_id: envelope.payload.project_id,
 8684                peer_id: envelope.original_sender_id()?,
 8685            };
 8686
 8687            let mut response = proto::FollowResponse::default();
 8688
 8689            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8690                let Some(workspace) = weak_workspace.upgrade() else {
 8691                    return false;
 8692                };
 8693                window_handle
 8694                    .update(cx, |_, window, cx| {
 8695                        workspace.update(cx, |workspace, cx| {
 8696                            let handler_response =
 8697                                workspace.handle_follow(follower.project_id, window, cx);
 8698                            if let Some(active_view) = handler_response.active_view
 8699                                && workspace.project.read(cx).remote_id() == follower.project_id
 8700                            {
 8701                                response.active_view = Some(active_view)
 8702                            }
 8703                        });
 8704                    })
 8705                    .is_ok()
 8706            });
 8707
 8708            Ok(response)
 8709        })
 8710    }
 8711
 8712    async fn handle_update_followers(
 8713        this: Entity<Self>,
 8714        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8715        mut cx: AsyncApp,
 8716    ) -> Result<()> {
 8717        let leader_id = envelope.original_sender_id()?;
 8718        let update = envelope.payload;
 8719
 8720        this.update(&mut cx, |this, cx| {
 8721            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8722                let Some(workspace) = weak_workspace.upgrade() else {
 8723                    return false;
 8724                };
 8725                window_handle
 8726                    .update(cx, |_, window, cx| {
 8727                        workspace.update(cx, |workspace, cx| {
 8728                            let project_id = workspace.project.read(cx).remote_id();
 8729                            if update.project_id != project_id && update.project_id.is_some() {
 8730                                return;
 8731                            }
 8732                            workspace.handle_update_followers(
 8733                                leader_id,
 8734                                update.clone(),
 8735                                window,
 8736                                cx,
 8737                            );
 8738                        });
 8739                    })
 8740                    .is_ok()
 8741            });
 8742            Ok(())
 8743        })
 8744    }
 8745
 8746    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8747        self.workspaces.iter().map(|(_, weak)| weak)
 8748    }
 8749
 8750    pub fn workspaces_with_windows(
 8751        &self,
 8752    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8753        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8754    }
 8755}
 8756
 8757impl ViewId {
 8758    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8759        Ok(Self {
 8760            creator: message
 8761                .creator
 8762                .map(CollaboratorId::PeerId)
 8763                .context("creator is missing")?,
 8764            id: message.id,
 8765        })
 8766    }
 8767
 8768    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8769        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8770            Some(proto::ViewId {
 8771                creator: Some(peer_id),
 8772                id: self.id,
 8773            })
 8774        } else {
 8775            None
 8776        }
 8777    }
 8778}
 8779
 8780impl FollowerState {
 8781    fn pane(&self) -> &Entity<Pane> {
 8782        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8783    }
 8784}
 8785
 8786pub trait WorkspaceHandle {
 8787    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8788}
 8789
 8790impl WorkspaceHandle for Entity<Workspace> {
 8791    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8792        self.read(cx)
 8793            .worktrees(cx)
 8794            .flat_map(|worktree| {
 8795                let worktree_id = worktree.read(cx).id();
 8796                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8797                    worktree_id,
 8798                    path: f.path.clone(),
 8799                })
 8800            })
 8801            .collect::<Vec<_>>()
 8802    }
 8803}
 8804
 8805pub async fn last_opened_workspace_location(
 8806    db: &WorkspaceDb,
 8807    fs: &dyn fs::Fs,
 8808) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8809    db.last_workspace(fs)
 8810        .await
 8811        .log_err()
 8812        .flatten()
 8813        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8814}
 8815
 8816pub async fn last_session_workspace_locations(
 8817    db: &WorkspaceDb,
 8818    last_session_id: &str,
 8819    last_session_window_stack: Option<Vec<WindowId>>,
 8820    fs: &dyn fs::Fs,
 8821) -> Option<Vec<SessionWorkspace>> {
 8822    db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8823        .await
 8824        .log_err()
 8825}
 8826
 8827pub async fn restore_multiworkspace(
 8828    multi_workspace: SerializedMultiWorkspace,
 8829    app_state: Arc<AppState>,
 8830    cx: &mut AsyncApp,
 8831) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8832    let SerializedMultiWorkspace {
 8833        active_workspace,
 8834        state,
 8835    } = multi_workspace;
 8836
 8837    let workspace_result = if active_workspace.paths.is_empty() {
 8838        cx.update(|cx| {
 8839            open_workspace_by_id(active_workspace.workspace_id, app_state.clone(), None, cx)
 8840        })
 8841        .await
 8842    } else {
 8843        cx.update(|cx| {
 8844            Workspace::new_local(
 8845                active_workspace.paths.paths().to_vec(),
 8846                app_state.clone(),
 8847                None,
 8848                None,
 8849                None,
 8850                OpenMode::Activate,
 8851                cx,
 8852            )
 8853        })
 8854        .await
 8855        .map(|result| result.window)
 8856    };
 8857
 8858    let window_handle = match workspace_result {
 8859        Ok(handle) => handle,
 8860        Err(err) => {
 8861            log::error!("Failed to restore active workspace: {err:#}");
 8862
 8863            let mut fallback_handle = None;
 8864            for key in &state.project_groups {
 8865                let key: ProjectGroupKey = key.clone().into();
 8866                let paths = key.path_list().paths().to_vec();
 8867                match cx
 8868                    .update(|cx| {
 8869                        Workspace::new_local(
 8870                            paths,
 8871                            app_state.clone(),
 8872                            None,
 8873                            None,
 8874                            None,
 8875                            OpenMode::Activate,
 8876                            cx,
 8877                        )
 8878                    })
 8879                    .await
 8880                {
 8881                    Ok(OpenResult { window, .. }) => {
 8882                        fallback_handle = Some(window);
 8883                        break;
 8884                    }
 8885                    Err(fallback_err) => {
 8886                        log::error!("Fallback project group also failed: {fallback_err:#}");
 8887                    }
 8888                }
 8889            }
 8890
 8891            fallback_handle.ok_or(err)?
 8892        }
 8893    };
 8894
 8895    apply_restored_multiworkspace_state(window_handle, &state, app_state.fs.clone(), cx).await;
 8896
 8897    window_handle
 8898        .update(cx, |_, window, _cx| {
 8899            window.activate_window();
 8900        })
 8901        .ok();
 8902
 8903    Ok(window_handle)
 8904}
 8905
 8906pub async fn apply_restored_multiworkspace_state(
 8907    window_handle: WindowHandle<MultiWorkspace>,
 8908    state: &MultiWorkspaceState,
 8909    fs: Arc<dyn fs::Fs>,
 8910    cx: &mut AsyncApp,
 8911) {
 8912    let MultiWorkspaceState {
 8913        sidebar_open,
 8914        project_groups,
 8915        sidebar_state,
 8916        ..
 8917    } = state;
 8918
 8919    if !project_groups.is_empty() {
 8920        // Resolve linked worktree paths to their main repo paths so
 8921        // stale keys from previous sessions get normalized and deduped.
 8922        let mut resolved_groups: Vec<SerializedProjectGroupState> = Vec::new();
 8923        for serialized in project_groups.iter().cloned() {
 8924            let SerializedProjectGroupState { key, expanded } = serialized.into_restored_state();
 8925            if key.path_list().paths().is_empty() {
 8926                continue;
 8927            }
 8928            let mut resolved_paths = Vec::new();
 8929            for path in key.path_list().paths() {
 8930                if key.host().is_none()
 8931                    && let Some(common_dir) =
 8932                        project::discover_root_repo_common_dir(path, fs.as_ref()).await
 8933                {
 8934                    let main_path = common_dir.parent().unwrap_or(&common_dir);
 8935                    resolved_paths.push(main_path.to_path_buf());
 8936                } else {
 8937                    resolved_paths.push(path.to_path_buf());
 8938                }
 8939            }
 8940            let resolved = ProjectGroupKey::new(key.host(), PathList::new(&resolved_paths));
 8941            if !resolved_groups.iter().any(|g| g.key == resolved) {
 8942                resolved_groups.push(SerializedProjectGroupState {
 8943                    key: resolved,
 8944                    expanded,
 8945                });
 8946            }
 8947        }
 8948
 8949        window_handle
 8950            .update(cx, |multi_workspace, _window, cx| {
 8951                multi_workspace.restore_project_groups(resolved_groups, cx);
 8952            })
 8953            .ok();
 8954    }
 8955
 8956    if *sidebar_open {
 8957        window_handle
 8958            .update(cx, |multi_workspace, _, cx| {
 8959                multi_workspace.restore_open_sidebar(cx);
 8960            })
 8961            .ok();
 8962    }
 8963
 8964    if let Some(sidebar_state) = sidebar_state {
 8965        window_handle
 8966            .update(cx, |multi_workspace, window, cx| {
 8967                if let Some(sidebar) = multi_workspace.sidebar() {
 8968                    sidebar.restore_serialized_state(sidebar_state, window, cx);
 8969                }
 8970                multi_workspace.serialize(cx);
 8971            })
 8972            .ok();
 8973    }
 8974}
 8975
 8976actions!(
 8977    collab,
 8978    [
 8979        /// Opens the channel notes for the current call.
 8980        ///
 8981        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8982        /// channel in the collab panel.
 8983        ///
 8984        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8985        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8986        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8987        OpenChannelNotes,
 8988        /// Mutes your microphone.
 8989        Mute,
 8990        /// Deafens yourself (mute both microphone and speakers).
 8991        Deafen,
 8992        /// Leaves the current call.
 8993        LeaveCall,
 8994        /// Shares the current project with collaborators.
 8995        ShareProject,
 8996        /// Shares your screen with collaborators.
 8997        ScreenShare,
 8998        /// Copies the current room name and session id for debugging purposes.
 8999        CopyRoomId,
 9000    ]
 9001);
 9002
 9003/// Opens the channel notes for a specific channel by its ID.
 9004#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 9005#[action(namespace = collab)]
 9006#[serde(deny_unknown_fields)]
 9007pub struct OpenChannelNotesById {
 9008    pub channel_id: u64,
 9009}
 9010
 9011actions!(
 9012    zed,
 9013    [
 9014        /// Opens the Zed log file.
 9015        OpenLog,
 9016        /// Reveals the Zed log file in the system file manager.
 9017        RevealLogInFileManager
 9018    ]
 9019);
 9020
 9021async fn join_channel_internal(
 9022    channel_id: ChannelId,
 9023    app_state: &Arc<AppState>,
 9024    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9025    requesting_workspace: Option<WeakEntity<Workspace>>,
 9026    active_call: &dyn AnyActiveCall,
 9027    cx: &mut AsyncApp,
 9028) -> Result<bool> {
 9029    let (should_prompt, already_in_channel) = cx.update(|cx| {
 9030        if !active_call.is_in_room(cx) {
 9031            return (false, false);
 9032        }
 9033
 9034        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 9035        let should_prompt = active_call.is_sharing_project(cx)
 9036            && active_call.has_remote_participants(cx)
 9037            && !already_in_channel;
 9038        (should_prompt, already_in_channel)
 9039    });
 9040
 9041    if already_in_channel {
 9042        let task = cx.update(|cx| {
 9043            if let Some((project, host)) = active_call.most_active_project(cx) {
 9044                Some(join_in_room_project(project, host, app_state.clone(), cx))
 9045            } else {
 9046                None
 9047            }
 9048        });
 9049        if let Some(task) = task {
 9050            task.await?;
 9051        }
 9052        return anyhow::Ok(true);
 9053    }
 9054
 9055    if should_prompt {
 9056        if let Some(multi_workspace) = requesting_window {
 9057            let answer = multi_workspace
 9058                .update(cx, |_, window, cx| {
 9059                    window.prompt(
 9060                        PromptLevel::Warning,
 9061                        "Do you want to switch channels?",
 9062                        Some("Leaving this call will unshare your current project."),
 9063                        &["Yes, Join Channel", "Cancel"],
 9064                        cx,
 9065                    )
 9066                })?
 9067                .await;
 9068
 9069            if answer == Ok(1) {
 9070                return Ok(false);
 9071            }
 9072        } else {
 9073            return Ok(false);
 9074        }
 9075    }
 9076
 9077    let client = cx.update(|cx| active_call.client(cx));
 9078
 9079    let mut client_status = client.status();
 9080
 9081    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 9082    'outer: loop {
 9083        let Some(status) = client_status.recv().await else {
 9084            anyhow::bail!("error connecting");
 9085        };
 9086
 9087        match status {
 9088            Status::Connecting
 9089            | Status::Authenticating
 9090            | Status::Authenticated
 9091            | Status::Reconnecting
 9092            | Status::Reauthenticating
 9093            | Status::Reauthenticated => continue,
 9094            Status::Connected { .. } => break 'outer,
 9095            Status::SignedOut | Status::AuthenticationError => {
 9096                return Err(ErrorCode::SignedOut.into());
 9097            }
 9098            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 9099            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 9100                return Err(ErrorCode::Disconnected.into());
 9101            }
 9102        }
 9103    }
 9104
 9105    let joined = cx
 9106        .update(|cx| active_call.join_channel(channel_id, cx))
 9107        .await?;
 9108
 9109    if !joined {
 9110        return anyhow::Ok(true);
 9111    }
 9112
 9113    cx.update(|cx| active_call.room_update_completed(cx)).await;
 9114
 9115    let task = cx.update(|cx| {
 9116        if let Some((project, host)) = active_call.most_active_project(cx) {
 9117            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 9118        }
 9119
 9120        // If you are the first to join a channel, see if you should share your project.
 9121        if !active_call.has_remote_participants(cx)
 9122            && !active_call.local_participant_is_guest(cx)
 9123            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 9124        {
 9125            let project = workspace.update(cx, |workspace, cx| {
 9126                let project = workspace.project.read(cx);
 9127
 9128                if !active_call.share_on_join(cx) {
 9129                    return None;
 9130                }
 9131
 9132                if (project.is_local() || project.is_via_remote_server())
 9133                    && project.visible_worktrees(cx).any(|tree| {
 9134                        tree.read(cx)
 9135                            .root_entry()
 9136                            .is_some_and(|entry| entry.is_dir())
 9137                    })
 9138                {
 9139                    Some(workspace.project.clone())
 9140                } else {
 9141                    None
 9142                }
 9143            });
 9144            if let Some(project) = project {
 9145                let share_task = active_call.share_project(project, cx);
 9146                return Some(cx.spawn(async move |_cx| -> Result<()> {
 9147                    share_task.await?;
 9148                    Ok(())
 9149                }));
 9150            }
 9151        }
 9152
 9153        None
 9154    });
 9155    if let Some(task) = task {
 9156        task.await?;
 9157        return anyhow::Ok(true);
 9158    }
 9159    anyhow::Ok(false)
 9160}
 9161
 9162pub fn join_channel(
 9163    channel_id: ChannelId,
 9164    app_state: Arc<AppState>,
 9165    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9166    requesting_workspace: Option<WeakEntity<Workspace>>,
 9167    cx: &mut App,
 9168) -> Task<Result<()>> {
 9169    let active_call = GlobalAnyActiveCall::global(cx).clone();
 9170    cx.spawn(async move |cx| {
 9171        let result = join_channel_internal(
 9172            channel_id,
 9173            &app_state,
 9174            requesting_window,
 9175            requesting_workspace,
 9176            &*active_call.0,
 9177            cx,
 9178        )
 9179        .await;
 9180
 9181        // join channel succeeded, and opened a window
 9182        if matches!(result, Ok(true)) {
 9183            return anyhow::Ok(());
 9184        }
 9185
 9186        // find an existing workspace to focus and show call controls
 9187        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 9188        if active_window.is_none() {
 9189            // no open workspaces, make one to show the error in (blergh)
 9190            let OpenResult {
 9191                window: window_handle,
 9192                ..
 9193            } = cx
 9194                .update(|cx| {
 9195                    Workspace::new_local(
 9196                        vec![],
 9197                        app_state.clone(),
 9198                        requesting_window,
 9199                        None,
 9200                        None,
 9201                        OpenMode::Activate,
 9202                        cx,
 9203                    )
 9204                })
 9205                .await?;
 9206
 9207            window_handle
 9208                .update(cx, |_, window, _cx| {
 9209                    window.activate_window();
 9210                })
 9211                .ok();
 9212
 9213            if result.is_ok() {
 9214                cx.update(|cx| {
 9215                    cx.dispatch_action(&OpenChannelNotes);
 9216                });
 9217            }
 9218
 9219            active_window = Some(window_handle);
 9220        }
 9221
 9222        if let Err(err) = result {
 9223            log::error!("failed to join channel: {}", err);
 9224            if let Some(active_window) = active_window {
 9225                active_window
 9226                    .update(cx, |_, window, cx| {
 9227                        let detail: SharedString = match err.error_code() {
 9228                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 9229                            ErrorCode::UpgradeRequired => concat!(
 9230                                "Your are running an unsupported version of Zed. ",
 9231                                "Please update to continue."
 9232                            )
 9233                            .into(),
 9234                            ErrorCode::NoSuchChannel => concat!(
 9235                                "No matching channel was found. ",
 9236                                "Please check the link and try again."
 9237                            )
 9238                            .into(),
 9239                            ErrorCode::Forbidden => concat!(
 9240                                "This channel is private, and you do not have access. ",
 9241                                "Please ask someone to add you and try again."
 9242                            )
 9243                            .into(),
 9244                            ErrorCode::Disconnected => {
 9245                                "Please check your internet connection and try again.".into()
 9246                            }
 9247                            _ => format!("{}\n\nPlease try again.", err).into(),
 9248                        };
 9249                        window.prompt(
 9250                            PromptLevel::Critical,
 9251                            "Failed to join channel",
 9252                            Some(&detail),
 9253                            &["Ok"],
 9254                            cx,
 9255                        )
 9256                    })?
 9257                    .await
 9258                    .ok();
 9259            }
 9260        }
 9261
 9262        // return ok, we showed the error to the user.
 9263        anyhow::Ok(())
 9264    })
 9265}
 9266
 9267pub async fn get_any_active_multi_workspace(
 9268    app_state: Arc<AppState>,
 9269    mut cx: AsyncApp,
 9270) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 9271    // find an existing workspace to focus and show call controls
 9272    let active_window = activate_any_workspace_window(&mut cx);
 9273    if active_window.is_none() {
 9274        cx.update(|cx| {
 9275            Workspace::new_local(
 9276                vec![],
 9277                app_state.clone(),
 9278                None,
 9279                None,
 9280                None,
 9281                OpenMode::Activate,
 9282                cx,
 9283            )
 9284        })
 9285        .await?;
 9286    }
 9287    activate_any_workspace_window(&mut cx).context("could not open zed")
 9288}
 9289
 9290fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 9291    cx.update(|cx| {
 9292        if let Some(workspace_window) = cx
 9293            .active_window()
 9294            .and_then(|window| window.downcast::<MultiWorkspace>())
 9295        {
 9296            return Some(workspace_window);
 9297        }
 9298
 9299        for window in cx.windows() {
 9300            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 9301                workspace_window
 9302                    .update(cx, |_, window, _| window.activate_window())
 9303                    .ok();
 9304                return Some(workspace_window);
 9305            }
 9306        }
 9307        None
 9308    })
 9309}
 9310
 9311pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 9312    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 9313}
 9314
 9315pub fn workspace_windows_for_location(
 9316    serialized_location: &SerializedWorkspaceLocation,
 9317    cx: &App,
 9318) -> Vec<WindowHandle<MultiWorkspace>> {
 9319    cx.windows()
 9320        .into_iter()
 9321        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9322        .filter(|multi_workspace| {
 9323            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 9324                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 9325                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 9326                }
 9327                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 9328                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 9329                    a.distro_name == b.distro_name
 9330                }
 9331                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 9332                    a.container_id == b.container_id
 9333                }
 9334                #[cfg(any(test, feature = "test-support"))]
 9335                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 9336                    a.id == b.id
 9337                }
 9338                _ => false,
 9339            };
 9340
 9341            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 9342                multi_workspace.workspaces().any(|workspace| {
 9343                    match workspace.read(cx).workspace_location(cx) {
 9344                        WorkspaceLocation::Location(location, _) => {
 9345                            match (&location, serialized_location) {
 9346                                (
 9347                                    SerializedWorkspaceLocation::Local,
 9348                                    SerializedWorkspaceLocation::Local,
 9349                                ) => true,
 9350                                (
 9351                                    SerializedWorkspaceLocation::Remote(a),
 9352                                    SerializedWorkspaceLocation::Remote(b),
 9353                                ) => same_host(a, b),
 9354                                _ => false,
 9355                            }
 9356                        }
 9357                        _ => false,
 9358                    }
 9359                })
 9360            })
 9361        })
 9362        .collect()
 9363}
 9364
 9365pub async fn find_existing_workspace(
 9366    abs_paths: &[PathBuf],
 9367    open_options: &OpenOptions,
 9368    location: &SerializedWorkspaceLocation,
 9369    cx: &mut AsyncApp,
 9370) -> (
 9371    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 9372    OpenVisible,
 9373) {
 9374    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 9375    let mut open_visible = OpenVisible::All;
 9376    let mut best_match = None;
 9377
 9378    if open_options.workspace_matching != WorkspaceMatching::None {
 9379        cx.update(|cx| {
 9380            for window in workspace_windows_for_location(location, cx) {
 9381                if let Ok(multi_workspace) = window.read(cx) {
 9382                    for workspace in multi_workspace.workspaces() {
 9383                        let project = workspace.read(cx).project.read(cx);
 9384                        let m = project.visibility_for_paths(
 9385                            abs_paths,
 9386                            open_options.workspace_matching != WorkspaceMatching::MatchSubdirectory,
 9387                            cx,
 9388                        );
 9389                        if m > best_match {
 9390                            existing = Some((window, workspace.clone()));
 9391                            best_match = m;
 9392                        } else if best_match.is_none()
 9393                            && open_options.workspace_matching
 9394                                == WorkspaceMatching::MatchSubdirectory
 9395                        {
 9396                            existing = Some((window, workspace.clone()))
 9397                        }
 9398                    }
 9399                }
 9400            }
 9401        });
 9402
 9403        let all_paths_are_files = existing
 9404            .as_ref()
 9405            .and_then(|(_, target_workspace)| {
 9406                cx.update(|cx| {
 9407                    let workspace = target_workspace.read(cx);
 9408                    let project = workspace.project.read(cx);
 9409                    let path_style = workspace.path_style(cx);
 9410                    Some(!abs_paths.iter().any(|path| {
 9411                        let path = util::paths::SanitizedPath::new(path);
 9412                        project.worktrees(cx).any(|worktree| {
 9413                            let worktree = worktree.read(cx);
 9414                            let abs_path = worktree.abs_path();
 9415                            path_style
 9416                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 9417                                .and_then(|rel| worktree.entry_for_path(&rel))
 9418                                .is_some_and(|e| e.is_dir())
 9419                        })
 9420                    }))
 9421                })
 9422            })
 9423            .unwrap_or(false);
 9424
 9425        if open_options.wait && existing.is_some() && all_paths_are_files {
 9426            cx.update(|cx| {
 9427                let windows = workspace_windows_for_location(location, cx);
 9428                let window = cx
 9429                    .active_window()
 9430                    .and_then(|window| window.downcast::<MultiWorkspace>())
 9431                    .filter(|window| windows.contains(window))
 9432                    .or_else(|| windows.into_iter().next());
 9433                if let Some(window) = window {
 9434                    if let Ok(multi_workspace) = window.read(cx) {
 9435                        let active_workspace = multi_workspace.workspace().clone();
 9436                        existing = Some((window, active_workspace));
 9437                        open_visible = OpenVisible::None;
 9438                    }
 9439                }
 9440            });
 9441        }
 9442    }
 9443    (existing, open_visible)
 9444}
 9445
 9446/// Controls whether to reuse an existing workspace whose worktrees contain the
 9447/// given paths, and how broadly to match.
 9448#[derive(Clone, Debug, Default, PartialEq, Eq)]
 9449pub enum WorkspaceMatching {
 9450    /// Always open a new workspace. No matching against existing worktrees.
 9451    None,
 9452    /// Match paths against existing worktree roots and files within them.
 9453    #[default]
 9454    MatchExact,
 9455    /// Match paths against existing worktrees including subdirectories, and
 9456    /// fall back to any existing window if no worktree matched.
 9457    ///
 9458    /// For example, `zed -a foo/bar` will activate the `bar` workspace if it
 9459    /// exists, otherwise it will open a new window with `foo/bar` as the root.
 9460    MatchSubdirectory,
 9461}
 9462
 9463#[derive(Clone)]
 9464pub struct OpenOptions {
 9465    pub visible: Option<OpenVisible>,
 9466    pub focus: Option<bool>,
 9467    pub workspace_matching: WorkspaceMatching,
 9468    /// Whether to add unmatched directories to the existing window's sidebar
 9469    /// rather than opening a new window. Defaults to true, matching the default
 9470    /// `cli_default_open_behavior` setting.
 9471    pub add_dirs_to_sidebar: bool,
 9472    pub wait: bool,
 9473    pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9474    pub open_mode: OpenMode,
 9475    pub env: Option<HashMap<String, String>>,
 9476    pub open_in_dev_container: bool,
 9477}
 9478
 9479impl Default for OpenOptions {
 9480    fn default() -> Self {
 9481        Self {
 9482            visible: None,
 9483            focus: None,
 9484            workspace_matching: WorkspaceMatching::default(),
 9485            add_dirs_to_sidebar: true,
 9486            wait: false,
 9487            requesting_window: None,
 9488            open_mode: OpenMode::default(),
 9489            env: None,
 9490            open_in_dev_container: false,
 9491        }
 9492    }
 9493}
 9494
 9495impl OpenOptions {
 9496    fn should_reuse_existing_window(&self) -> bool {
 9497        self.workspace_matching != WorkspaceMatching::None && self.open_mode != OpenMode::NewWindow
 9498    }
 9499}
 9500
 9501/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 9502/// or [`Workspace::open_workspace_for_paths`].
 9503pub struct OpenResult {
 9504    pub window: WindowHandle<MultiWorkspace>,
 9505    pub workspace: Entity<Workspace>,
 9506    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 9507}
 9508
 9509/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 9510pub fn open_workspace_by_id(
 9511    workspace_id: WorkspaceId,
 9512    app_state: Arc<AppState>,
 9513    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9514    cx: &mut App,
 9515) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 9516    let project_handle = Project::local(
 9517        app_state.client.clone(),
 9518        app_state.node_runtime.clone(),
 9519        app_state.user_store.clone(),
 9520        app_state.languages.clone(),
 9521        app_state.fs.clone(),
 9522        None,
 9523        project::LocalProjectFlags {
 9524            init_worktree_trust: true,
 9525            ..project::LocalProjectFlags::default()
 9526        },
 9527        cx,
 9528    );
 9529
 9530    let db = WorkspaceDb::global(cx);
 9531    let kvp = db::kvp::KeyValueStore::global(cx);
 9532    cx.spawn(async move |cx| {
 9533        let serialized_workspace = db
 9534            .workspace_for_id(workspace_id)
 9535            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 9536
 9537        let centered_layout = serialized_workspace.centered_layout;
 9538
 9539        let (window, workspace) = if let Some(window) = requesting_window {
 9540            let workspace = window.update(cx, |multi_workspace, window, cx| {
 9541                let workspace = cx.new(|cx| {
 9542                    let mut workspace = Workspace::new(
 9543                        Some(workspace_id),
 9544                        project_handle.clone(),
 9545                        app_state.clone(),
 9546                        window,
 9547                        cx,
 9548                    );
 9549                    workspace.centered_layout = centered_layout;
 9550                    workspace
 9551                });
 9552                multi_workspace.add(workspace.clone(), &*window, cx);
 9553                workspace
 9554            })?;
 9555            (window, workspace)
 9556        } else {
 9557            let window_bounds_override = window_bounds_env_override();
 9558
 9559            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 9560                (Some(WindowBounds::Windowed(bounds)), None)
 9561            } else if let Some(display) = serialized_workspace.display
 9562                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 9563            {
 9564                (Some(bounds.0), Some(display))
 9565            } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
 9566                (Some(bounds), Some(display))
 9567            } else {
 9568                (None, None)
 9569            };
 9570
 9571            let options = cx.update(|cx| {
 9572                let mut options = (app_state.build_window_options)(display, cx);
 9573                options.window_bounds = window_bounds;
 9574                options
 9575            });
 9576
 9577            let window = cx.open_window(options, {
 9578                let app_state = app_state.clone();
 9579                let project_handle = project_handle.clone();
 9580                move |window, cx| {
 9581                    let workspace = cx.new(|cx| {
 9582                        let mut workspace = Workspace::new(
 9583                            Some(workspace_id),
 9584                            project_handle,
 9585                            app_state,
 9586                            window,
 9587                            cx,
 9588                        );
 9589                        workspace.centered_layout = centered_layout;
 9590                        workspace
 9591                    });
 9592                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9593                }
 9594            })?;
 9595
 9596            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 9597                multi_workspace.workspace().clone()
 9598            })?;
 9599
 9600            (window, workspace)
 9601        };
 9602
 9603        notify_if_database_failed(window, cx);
 9604
 9605        // Restore items from the serialized workspace
 9606        window
 9607            .update(cx, |_, window, cx| {
 9608                workspace.update(cx, |_workspace, cx| {
 9609                    open_items(Some(serialized_workspace), vec![], window, cx)
 9610                })
 9611            })?
 9612            .await?;
 9613
 9614        window.update(cx, |_, window, cx| {
 9615            workspace.update(cx, |workspace, cx| {
 9616                workspace.serialize_workspace(window, cx);
 9617            });
 9618        })?;
 9619
 9620        Ok(window)
 9621    })
 9622}
 9623
 9624#[allow(clippy::type_complexity)]
 9625pub fn open_paths(
 9626    abs_paths: &[PathBuf],
 9627    app_state: Arc<AppState>,
 9628    mut open_options: OpenOptions,
 9629    cx: &mut App,
 9630) -> Task<anyhow::Result<OpenResult>> {
 9631    let abs_paths = abs_paths.to_vec();
 9632    #[cfg(target_os = "windows")]
 9633    let wsl_path = abs_paths
 9634        .iter()
 9635        .find_map(|p| util::paths::WslPath::from_path(p));
 9636
 9637    cx.spawn(async move |cx| {
 9638        let (mut existing, mut open_visible) = find_existing_workspace(
 9639            &abs_paths,
 9640            &open_options,
 9641            &SerializedWorkspaceLocation::Local,
 9642            cx,
 9643        )
 9644        .await;
 9645
 9646        // Fallback: if no workspace contains the paths and all paths are files,
 9647        // prefer an existing local workspace window (active window first).
 9648        if open_options.should_reuse_existing_window() && existing.is_none() {
 9649            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 9650            let all_metadatas = futures::future::join_all(all_paths)
 9651                .await
 9652                .into_iter()
 9653                .filter_map(|result| result.ok().flatten());
 9654
 9655            if all_metadatas.into_iter().all(|file| !file.is_dir) {
 9656                cx.update(|cx| {
 9657                    let windows = workspace_windows_for_location(
 9658                        &SerializedWorkspaceLocation::Local,
 9659                        cx,
 9660                    );
 9661                    let window = cx
 9662                        .active_window()
 9663                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9664                        .filter(|window| windows.contains(window))
 9665                        .or_else(|| windows.into_iter().next());
 9666                    if let Some(window) = window {
 9667                        if let Ok(multi_workspace) = window.read(cx) {
 9668                            let active_workspace = multi_workspace.workspace().clone();
 9669                            existing = Some((window, active_workspace));
 9670                            open_visible = OpenVisible::None;
 9671                        }
 9672                    }
 9673                });
 9674            }
 9675        }
 9676
 9677        // Fallback for directories: when no flag is specified and no existing
 9678        // workspace matched, check the user's setting to decide whether to add
 9679        // the directory as a new workspace in the active window's MultiWorkspace
 9680        // or open a new window.
 9681        // Skip when requesting_window is already set: the caller (e.g.
 9682        // open_workspace_for_paths reusing an empty window) already chose the
 9683        // target window, so we must not open the sidebar as a side-effect.
 9684        if open_options.should_reuse_existing_window()
 9685            && existing.is_none()
 9686            && open_options.requesting_window.is_none()
 9687        {
 9688            let use_existing_window = open_options.add_dirs_to_sidebar;
 9689
 9690            if use_existing_window {
 9691                let target_window = cx.update(|cx| {
 9692                    let windows = workspace_windows_for_location(
 9693                        &SerializedWorkspaceLocation::Local,
 9694                        cx,
 9695                    );
 9696                    let window = cx
 9697                        .active_window()
 9698                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9699                        .filter(|window| windows.contains(window))
 9700                        .or_else(|| windows.into_iter().next());
 9701                    window.filter(|window| {
 9702                        window
 9703                            .read(cx)
 9704                            .is_ok_and(|mw| mw.multi_workspace_enabled(cx))
 9705                    })
 9706                });
 9707
 9708                if let Some(window) = target_window {
 9709                    open_options.requesting_window = Some(window);
 9710                    window
 9711                        .update(cx, |multi_workspace, _, cx| {
 9712                            multi_workspace.open_sidebar(cx);
 9713                        })
 9714                        .log_err();
 9715                }
 9716            }
 9717        }
 9718
 9719        let open_in_dev_container = open_options.open_in_dev_container;
 9720
 9721        let result = if let Some((existing, target_workspace)) = existing {
 9722            let open_task = existing
 9723                .update(cx, |multi_workspace, window, cx| {
 9724                    window.activate_window();
 9725                    multi_workspace.activate(target_workspace.clone(), None, window, cx);
 9726                    target_workspace.update(cx, |workspace, cx| {
 9727                        if open_in_dev_container {
 9728                            workspace.set_open_in_dev_container(true);
 9729                        }
 9730                        workspace.open_paths(
 9731                            abs_paths,
 9732                            OpenOptions {
 9733                                visible: Some(open_visible),
 9734                                ..Default::default()
 9735                            },
 9736                            None,
 9737                            window,
 9738                            cx,
 9739                        )
 9740                    })
 9741                })?
 9742                .await;
 9743
 9744            _ = existing.update(cx, |multi_workspace, _, cx| {
 9745                let workspace = multi_workspace.workspace().clone();
 9746                workspace.update(cx, |workspace, cx| {
 9747                    for item in open_task.iter().flatten() {
 9748                        if let Err(e) = item {
 9749                            workspace.show_error(&e, cx);
 9750                        }
 9751                    }
 9752                });
 9753            });
 9754
 9755            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9756        } else {
 9757            let init = if open_in_dev_container {
 9758                Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>| {
 9759                    workspace.set_open_in_dev_container(true);
 9760                }) as Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>)
 9761            } else {
 9762                None
 9763            };
 9764            let result = cx
 9765                .update(move |cx| {
 9766                    Workspace::new_local(
 9767                        abs_paths,
 9768                        app_state.clone(),
 9769                        open_options.requesting_window,
 9770                        open_options.env,
 9771                        init,
 9772                        open_options.open_mode,
 9773                        cx,
 9774                    )
 9775                })
 9776                .await;
 9777
 9778            if let Ok(ref result) = result {
 9779                result.window
 9780                    .update(cx, |_, window, _cx| {
 9781                        window.activate_window();
 9782                    })
 9783                    .log_err();
 9784            }
 9785
 9786            result
 9787        };
 9788
 9789        #[cfg(target_os = "windows")]
 9790        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9791            && let Ok(ref result) = result
 9792        {
 9793            result.window
 9794                .update(cx, move |multi_workspace, _window, cx| {
 9795                    struct OpenInWsl;
 9796                    let workspace = multi_workspace.workspace().clone();
 9797                    workspace.update(cx, |workspace, cx| {
 9798                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9799                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9800                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9801                            cx.new(move |cx| {
 9802                                MessageNotification::new(msg, cx)
 9803                                    .primary_message("Open in WSL")
 9804                                    .primary_icon(IconName::FolderOpen)
 9805                                    .primary_on_click(move |window, cx| {
 9806                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9807                                                distro: remote::WslConnectionOptions {
 9808                                                        distro_name: distro.clone(),
 9809                                                    user: None,
 9810                                                },
 9811                                                paths: vec![path.clone().into()],
 9812                                            }), cx)
 9813                                    })
 9814                            })
 9815                        });
 9816                    });
 9817                })
 9818                .unwrap();
 9819        };
 9820        result
 9821    })
 9822}
 9823
 9824pub fn open_new(
 9825    open_options: OpenOptions,
 9826    app_state: Arc<AppState>,
 9827    cx: &mut App,
 9828    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9829) -> Task<anyhow::Result<()>> {
 9830    let addition = open_options.open_mode;
 9831    let task = Workspace::new_local(
 9832        Vec::new(),
 9833        app_state,
 9834        open_options.requesting_window,
 9835        open_options.env,
 9836        Some(Box::new(init)),
 9837        addition,
 9838        cx,
 9839    );
 9840    cx.spawn(async move |cx| {
 9841        let OpenResult { window, .. } = task.await?;
 9842        window
 9843            .update(cx, |_, window, _cx| {
 9844                window.activate_window();
 9845            })
 9846            .ok();
 9847        Ok(())
 9848    })
 9849}
 9850
 9851pub fn create_and_open_local_file(
 9852    path: &'static Path,
 9853    window: &mut Window,
 9854    cx: &mut Context<Workspace>,
 9855    default_content: impl 'static + Send + FnOnce() -> Rope,
 9856) -> Task<Result<Box<dyn ItemHandle>>> {
 9857    cx.spawn_in(window, async move |workspace, cx| {
 9858        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9859        if !fs.is_file(path).await {
 9860            fs.create_file(path, Default::default()).await?;
 9861            fs.save(path, &default_content(), Default::default())
 9862                .await?;
 9863        }
 9864
 9865        workspace
 9866            .update_in(cx, |workspace, window, cx| {
 9867                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9868                    let path = workspace
 9869                        .project
 9870                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9871                    cx.spawn_in(window, async move |workspace, cx| {
 9872                        let path = path.await?;
 9873
 9874                        let path = fs.canonicalize(&path).await.unwrap_or(path);
 9875
 9876                        let mut items = workspace
 9877                            .update_in(cx, |workspace, window, cx| {
 9878                                workspace.open_paths(
 9879                                    vec![path.to_path_buf()],
 9880                                    OpenOptions {
 9881                                        visible: Some(OpenVisible::None),
 9882                                        ..Default::default()
 9883                                    },
 9884                                    None,
 9885                                    window,
 9886                                    cx,
 9887                                )
 9888                            })?
 9889                            .await;
 9890                        let item = items.pop().flatten();
 9891                        item.with_context(|| format!("path {path:?} is not a file"))?
 9892                    })
 9893                })
 9894            })?
 9895            .await?
 9896            .await
 9897    })
 9898}
 9899
 9900pub fn open_remote_project_with_new_connection(
 9901    window: WindowHandle<MultiWorkspace>,
 9902    remote_connection: Arc<dyn RemoteConnection>,
 9903    cancel_rx: oneshot::Receiver<()>,
 9904    delegate: Arc<dyn RemoteClientDelegate>,
 9905    app_state: Arc<AppState>,
 9906    paths: Vec<PathBuf>,
 9907    cx: &mut App,
 9908) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9909    cx.spawn(async move |cx| {
 9910        let (workspace_id, serialized_workspace) =
 9911            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9912                .await?;
 9913
 9914        let session = match cx
 9915            .update(|cx| {
 9916                remote::RemoteClient::new(
 9917                    ConnectionIdentifier::Workspace(workspace_id.0),
 9918                    remote_connection,
 9919                    cancel_rx,
 9920                    delegate,
 9921                    cx,
 9922                )
 9923            })
 9924            .await?
 9925        {
 9926            Some(result) => result,
 9927            None => return Ok(Vec::new()),
 9928        };
 9929
 9930        let project = cx.update(|cx| {
 9931            project::Project::remote(
 9932                session,
 9933                app_state.client.clone(),
 9934                app_state.node_runtime.clone(),
 9935                app_state.user_store.clone(),
 9936                app_state.languages.clone(),
 9937                app_state.fs.clone(),
 9938                true,
 9939                cx,
 9940            )
 9941        });
 9942
 9943        open_remote_project_inner(
 9944            project,
 9945            paths,
 9946            workspace_id,
 9947            serialized_workspace,
 9948            app_state,
 9949            window,
 9950            None,
 9951            None,
 9952            cx,
 9953        )
 9954        .await
 9955    })
 9956}
 9957
 9958pub fn open_remote_project_with_existing_connection(
 9959    connection_options: RemoteConnectionOptions,
 9960    project: Entity<Project>,
 9961    paths: Vec<PathBuf>,
 9962    app_state: Arc<AppState>,
 9963    window: WindowHandle<MultiWorkspace>,
 9964    provisional_project_group_key: Option<ProjectGroupKey>,
 9965    source_workspace: Option<WeakEntity<Workspace>>,
 9966    cx: &mut AsyncApp,
 9967) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9968    cx.spawn(async move |cx| {
 9969        let (workspace_id, serialized_workspace) =
 9970            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9971
 9972        open_remote_project_inner(
 9973            project,
 9974            paths,
 9975            workspace_id,
 9976            serialized_workspace,
 9977            app_state,
 9978            window,
 9979            provisional_project_group_key,
 9980            source_workspace,
 9981            cx,
 9982        )
 9983        .await
 9984    })
 9985}
 9986
 9987async fn open_remote_project_inner(
 9988    project: Entity<Project>,
 9989    paths: Vec<PathBuf>,
 9990    workspace_id: WorkspaceId,
 9991    serialized_workspace: Option<SerializedWorkspace>,
 9992    app_state: Arc<AppState>,
 9993    window: WindowHandle<MultiWorkspace>,
 9994    provisional_project_group_key: Option<ProjectGroupKey>,
 9995    source_workspace: Option<WeakEntity<Workspace>>,
 9996    cx: &mut AsyncApp,
 9997) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9998    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9999    let toolchains = db.toolchains(workspace_id).await?;
10000    for (toolchain, worktree_path, path) in toolchains {
10001        project
10002            .update(cx, |this, cx| {
10003                let Some(worktree_id) =
10004                    this.find_worktree(&worktree_path, cx)
10005                        .and_then(|(worktree, rel_path)| {
10006                            if rel_path.is_empty() {
10007                                Some(worktree.read(cx).id())
10008                            } else {
10009                                None
10010                            }
10011                        })
10012                else {
10013                    return Task::ready(None);
10014                };
10015
10016                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
10017            })
10018            .await;
10019    }
10020    let mut project_paths_to_open = vec![];
10021    let mut project_path_errors = vec![];
10022
10023    for path in paths {
10024        let result = cx
10025            .update(|cx| {
10026                Workspace::project_path_for_path(project.clone(), path.as_path(), true, cx)
10027            })
10028            .await;
10029        match result {
10030            Ok((_, project_path)) => {
10031                project_paths_to_open.push((path, Some(project_path)));
10032            }
10033            Err(error) => {
10034                project_path_errors.push(error);
10035            }
10036        };
10037    }
10038
10039    if project_paths_to_open.is_empty() {
10040        return Err(project_path_errors.pop().context("no paths given")?);
10041    }
10042
10043    let workspace = window.update(cx, |multi_workspace, window, cx| {
10044        telemetry::event!("SSH Project Opened");
10045
10046        let new_workspace = cx.new(|cx| {
10047            let mut workspace =
10048                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
10049            workspace.update_history(cx);
10050
10051            if let Some(ref serialized) = serialized_workspace {
10052                workspace.centered_layout = serialized.centered_layout;
10053            }
10054
10055            workspace
10056        });
10057
10058        if let Some(project_group_key) = provisional_project_group_key.clone() {
10059            multi_workspace.activate_provisional_workspace(
10060                new_workspace.clone(),
10061                project_group_key,
10062                window,
10063                cx,
10064            );
10065        } else {
10066            multi_workspace.activate(new_workspace.clone(), source_workspace, window, cx);
10067        }
10068        new_workspace
10069    })?;
10070
10071    let items = window
10072        .update(cx, |_, window, cx| {
10073            window.activate_window();
10074            workspace.update(cx, |_workspace, cx| {
10075                open_items(serialized_workspace, project_paths_to_open, window, cx)
10076            })
10077        })?
10078        .await?;
10079
10080    workspace.update(cx, |workspace, cx| {
10081        for error in project_path_errors {
10082            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
10083                if let Some(path) = error.error_tag("path") {
10084                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
10085                }
10086            } else {
10087                workspace.show_error(&error, cx)
10088            }
10089        }
10090    });
10091
10092    Ok(items.into_iter().map(|item| item?.ok()).collect())
10093}
10094
10095fn deserialize_remote_project(
10096    connection_options: RemoteConnectionOptions,
10097    paths: Vec<PathBuf>,
10098    cx: &AsyncApp,
10099) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
10100    let db = cx.update(|cx| WorkspaceDb::global(cx));
10101    cx.background_spawn(async move {
10102        let remote_connection_id = db
10103            .get_or_create_remote_connection(connection_options)
10104            .await?;
10105
10106        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10107
10108        let workspace_id = if let Some(workspace_id) =
10109            serialized_workspace.as_ref().map(|workspace| workspace.id)
10110        {
10111            workspace_id
10112        } else {
10113            db.next_id().await?
10114        };
10115
10116        Ok((workspace_id, serialized_workspace))
10117    })
10118}
10119
10120pub fn join_in_room_project(
10121    project_id: u64,
10122    follow_user_id: u64,
10123    app_state: Arc<AppState>,
10124    cx: &mut App,
10125) -> Task<Result<()>> {
10126    let windows = cx.windows();
10127    cx.spawn(async move |cx| {
10128        let existing_window_and_workspace: Option<(
10129            WindowHandle<MultiWorkspace>,
10130            Entity<Workspace>,
10131        )> = windows.into_iter().find_map(|window_handle| {
10132            window_handle
10133                .downcast::<MultiWorkspace>()
10134                .and_then(|window_handle| {
10135                    window_handle
10136                        .update(cx, |multi_workspace, _window, cx| {
10137                            multi_workspace
10138                                .workspaces()
10139                                .find(|workspace| {
10140                                    workspace.read(cx).project().read(cx).remote_id()
10141                                        == Some(project_id)
10142                                })
10143                                .map(|workspace| (window_handle, workspace.clone()))
10144                        })
10145                        .unwrap_or(None)
10146                })
10147        });
10148
10149        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
10150            existing_window_and_workspace
10151        {
10152            existing_window
10153                .update(cx, |multi_workspace, window, cx| {
10154                    multi_workspace.activate(target_workspace, None, window, cx);
10155                })
10156                .ok();
10157            existing_window
10158        } else {
10159            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
10160            let project = cx
10161                .update(|cx| {
10162                    active_call.0.join_project(
10163                        project_id,
10164                        app_state.languages.clone(),
10165                        app_state.fs.clone(),
10166                        cx,
10167                    )
10168                })
10169                .await?;
10170
10171            let window_bounds_override = window_bounds_env_override();
10172            cx.update(|cx| {
10173                let mut options = (app_state.build_window_options)(None, cx);
10174                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
10175                cx.open_window(options, |window, cx| {
10176                    let workspace = cx.new(|cx| {
10177                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
10178                    });
10179                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
10180                })
10181            })?
10182        };
10183
10184        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
10185            cx.activate(true);
10186            window.activate_window();
10187
10188            // We set the active workspace above, so this is the correct workspace.
10189            let workspace = multi_workspace.workspace().clone();
10190            workspace.update(cx, |workspace, cx| {
10191                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
10192                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
10193                    .or_else(|| {
10194                        // If we couldn't follow the given user, follow the host instead.
10195                        let collaborator = workspace
10196                            .project()
10197                            .read(cx)
10198                            .collaborators()
10199                            .values()
10200                            .find(|collaborator| collaborator.is_host)?;
10201                        Some(collaborator.peer_id)
10202                    });
10203
10204                if let Some(follow_peer_id) = follow_peer_id {
10205                    workspace.follow(follow_peer_id, window, cx);
10206                }
10207            });
10208        })?;
10209
10210        anyhow::Ok(())
10211    })
10212}
10213
10214pub fn reload(cx: &mut App) {
10215    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
10216    let mut workspace_windows = cx
10217        .windows()
10218        .into_iter()
10219        .filter_map(|window| window.downcast::<MultiWorkspace>())
10220        .collect::<Vec<_>>();
10221
10222    // If multiple windows have unsaved changes, and need a save prompt,
10223    // prompt in the active window before switching to a different window.
10224    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
10225
10226    let mut prompt = None;
10227    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
10228        prompt = window
10229            .update(cx, |_, window, cx| {
10230                window.prompt(
10231                    PromptLevel::Info,
10232                    "Are you sure you want to restart?",
10233                    None,
10234                    &["Restart", "Cancel"],
10235                    cx,
10236                )
10237            })
10238            .ok();
10239    }
10240
10241    cx.spawn(async move |cx| {
10242        if let Some(prompt) = prompt {
10243            let answer = prompt.await?;
10244            if answer != 0 {
10245                return anyhow::Ok(());
10246            }
10247        }
10248
10249        // If the user cancels any save prompt, then keep the app open.
10250        for window in workspace_windows {
10251            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
10252                let workspace = multi_workspace.workspace().clone();
10253                workspace.update(cx, |workspace, cx| {
10254                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
10255                })
10256            }) && !should_close.await?
10257            {
10258                return anyhow::Ok(());
10259            }
10260        }
10261        cx.update(|cx| cx.restart());
10262        anyhow::Ok(())
10263    })
10264    .detach_and_log_err(cx);
10265}
10266
10267fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
10268    let mut parts = value.split(',');
10269    let x: usize = parts.next()?.parse().ok()?;
10270    let y: usize = parts.next()?.parse().ok()?;
10271    Some(point(px(x as f32), px(y as f32)))
10272}
10273
10274fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
10275    let mut parts = value.split(',');
10276    let width: usize = parts.next()?.parse().ok()?;
10277    let height: usize = parts.next()?.parse().ok()?;
10278    Some(size(px(width as f32), px(height as f32)))
10279}
10280
10281/// Add client-side decorations (rounded corners, shadows, resize handling) when
10282/// appropriate.
10283///
10284/// The `border_radius_tiling` parameter allows overriding which corners get
10285/// rounded, independently of the actual window tiling state. This is used
10286/// specifically for the workspace switcher sidebar: when the sidebar is open,
10287/// we want square corners on the left (so the sidebar appears flush with the
10288/// window edge) but we still need the shadow padding for proper visual
10289/// appearance. Unlike actual window tiling, this only affects border radius -
10290/// not padding or shadows.
10291pub fn client_side_decorations(
10292    element: impl IntoElement,
10293    window: &mut Window,
10294    cx: &mut App,
10295    border_radius_tiling: Tiling,
10296) -> Stateful<Div> {
10297    const BORDER_SIZE: Pixels = px(1.0);
10298    let decorations = window.window_decorations();
10299    let tiling = match decorations {
10300        Decorations::Server => Tiling::default(),
10301        Decorations::Client { tiling } => tiling,
10302    };
10303
10304    match decorations {
10305        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
10306        Decorations::Server => window.set_client_inset(px(0.0)),
10307    }
10308
10309    struct GlobalResizeEdge(ResizeEdge);
10310    impl Global for GlobalResizeEdge {}
10311
10312    div()
10313        .id("window-backdrop")
10314        .bg(transparent_black())
10315        .map(|div| match decorations {
10316            Decorations::Server => div,
10317            Decorations::Client { .. } => div
10318                .when(
10319                    !(tiling.top
10320                        || tiling.right
10321                        || border_radius_tiling.top
10322                        || border_radius_tiling.right),
10323                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10324                )
10325                .when(
10326                    !(tiling.top
10327                        || tiling.left
10328                        || border_radius_tiling.top
10329                        || border_radius_tiling.left),
10330                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10331                )
10332                .when(
10333                    !(tiling.bottom
10334                        || tiling.right
10335                        || border_radius_tiling.bottom
10336                        || border_radius_tiling.right),
10337                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10338                )
10339                .when(
10340                    !(tiling.bottom
10341                        || tiling.left
10342                        || border_radius_tiling.bottom
10343                        || border_radius_tiling.left),
10344                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10345                )
10346                .when(!tiling.top, |div| {
10347                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
10348                })
10349                .when(!tiling.bottom, |div| {
10350                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
10351                })
10352                .when(!tiling.left, |div| {
10353                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10354                })
10355                .when(!tiling.right, |div| {
10356                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10357                })
10358                .on_mouse_move(move |e, window, cx| {
10359                    let size = window.window_bounds().get_bounds().size;
10360                    let pos = e.position;
10361
10362                    let new_edge =
10363                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10364
10365                    let edge = cx.try_global::<GlobalResizeEdge>();
10366                    if new_edge != edge.map(|edge| edge.0) {
10367                        window
10368                            .window_handle()
10369                            .update(cx, |workspace, _, cx| {
10370                                cx.notify(workspace.entity_id());
10371                            })
10372                            .ok();
10373                    }
10374                })
10375                .on_mouse_down(MouseButton::Left, move |e, window, _| {
10376                    let size = window.window_bounds().get_bounds().size;
10377                    let pos = e.position;
10378
10379                    let edge = match resize_edge(
10380                        pos,
10381                        theme::CLIENT_SIDE_DECORATION_SHADOW,
10382                        size,
10383                        tiling,
10384                    ) {
10385                        Some(value) => value,
10386                        None => return,
10387                    };
10388
10389                    window.start_window_resize(edge);
10390                }),
10391        })
10392        .size_full()
10393        .child(
10394            div()
10395                .cursor(CursorStyle::Arrow)
10396                .map(|div| match decorations {
10397                    Decorations::Server => div,
10398                    Decorations::Client { .. } => div
10399                        .border_color(cx.theme().colors().border)
10400                        .when(
10401                            !(tiling.top
10402                                || tiling.right
10403                                || border_radius_tiling.top
10404                                || border_radius_tiling.right),
10405                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10406                        )
10407                        .when(
10408                            !(tiling.top
10409                                || tiling.left
10410                                || border_radius_tiling.top
10411                                || border_radius_tiling.left),
10412                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10413                        )
10414                        .when(
10415                            !(tiling.bottom
10416                                || tiling.right
10417                                || border_radius_tiling.bottom
10418                                || border_radius_tiling.right),
10419                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10420                        )
10421                        .when(
10422                            !(tiling.bottom
10423                                || tiling.left
10424                                || border_radius_tiling.bottom
10425                                || border_radius_tiling.left),
10426                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10427                        )
10428                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10429                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10430                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10431                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10432                        .when(!tiling.is_tiled(), |div| {
10433                            div.shadow(vec![gpui::BoxShadow {
10434                                color: Hsla {
10435                                    h: 0.,
10436                                    s: 0.,
10437                                    l: 0.,
10438                                    a: 0.4,
10439                                },
10440                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10441                                spread_radius: px(0.),
10442                                offset: point(px(0.0), px(0.0)),
10443                            }])
10444                        }),
10445                })
10446                .on_mouse_move(|_e, _, cx| {
10447                    cx.stop_propagation();
10448                })
10449                .size_full()
10450                .child(element),
10451        )
10452        .map(|div| match decorations {
10453            Decorations::Server => div,
10454            Decorations::Client { tiling, .. } => div.child(
10455                canvas(
10456                    |_bounds, window, _| {
10457                        window.insert_hitbox(
10458                            Bounds::new(
10459                                point(px(0.0), px(0.0)),
10460                                window.window_bounds().get_bounds().size,
10461                            ),
10462                            HitboxBehavior::Normal,
10463                        )
10464                    },
10465                    move |_bounds, hitbox, window, cx| {
10466                        let mouse = window.mouse_position();
10467                        let size = window.window_bounds().get_bounds().size;
10468                        let Some(edge) =
10469                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10470                        else {
10471                            return;
10472                        };
10473                        cx.set_global(GlobalResizeEdge(edge));
10474                        window.set_cursor_style(
10475                            match edge {
10476                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10477                                ResizeEdge::Left | ResizeEdge::Right => {
10478                                    CursorStyle::ResizeLeftRight
10479                                }
10480                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10481                                    CursorStyle::ResizeUpLeftDownRight
10482                                }
10483                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10484                                    CursorStyle::ResizeUpRightDownLeft
10485                                }
10486                            },
10487                            &hitbox,
10488                        );
10489                    },
10490                )
10491                .size_full()
10492                .absolute(),
10493            ),
10494        })
10495}
10496
10497fn resize_edge(
10498    pos: Point<Pixels>,
10499    shadow_size: Pixels,
10500    window_size: Size<Pixels>,
10501    tiling: Tiling,
10502) -> Option<ResizeEdge> {
10503    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10504    if bounds.contains(&pos) {
10505        return None;
10506    }
10507
10508    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10509    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10510    if !tiling.top && top_left_bounds.contains(&pos) {
10511        return Some(ResizeEdge::TopLeft);
10512    }
10513
10514    let top_right_bounds = Bounds::new(
10515        Point::new(window_size.width - corner_size.width, px(0.)),
10516        corner_size,
10517    );
10518    if !tiling.top && top_right_bounds.contains(&pos) {
10519        return Some(ResizeEdge::TopRight);
10520    }
10521
10522    let bottom_left_bounds = Bounds::new(
10523        Point::new(px(0.), window_size.height - corner_size.height),
10524        corner_size,
10525    );
10526    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10527        return Some(ResizeEdge::BottomLeft);
10528    }
10529
10530    let bottom_right_bounds = Bounds::new(
10531        Point::new(
10532            window_size.width - corner_size.width,
10533            window_size.height - corner_size.height,
10534        ),
10535        corner_size,
10536    );
10537    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10538        return Some(ResizeEdge::BottomRight);
10539    }
10540
10541    if !tiling.top && pos.y < shadow_size {
10542        Some(ResizeEdge::Top)
10543    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10544        Some(ResizeEdge::Bottom)
10545    } else if !tiling.left && pos.x < shadow_size {
10546        Some(ResizeEdge::Left)
10547    } else if !tiling.right && pos.x > window_size.width - shadow_size {
10548        Some(ResizeEdge::Right)
10549    } else {
10550        None
10551    }
10552}
10553
10554fn join_pane_into_active(
10555    active_pane: &Entity<Pane>,
10556    pane: &Entity<Pane>,
10557    window: &mut Window,
10558    cx: &mut App,
10559) {
10560    if pane == active_pane {
10561    } else if pane.read(cx).items_len() == 0 {
10562        pane.update(cx, |_, cx| {
10563            cx.emit(pane::Event::Remove {
10564                focus_on_pane: None,
10565            });
10566        })
10567    } else {
10568        move_all_items(pane, active_pane, window, cx);
10569    }
10570}
10571
10572fn move_all_items(
10573    from_pane: &Entity<Pane>,
10574    to_pane: &Entity<Pane>,
10575    window: &mut Window,
10576    cx: &mut App,
10577) {
10578    let destination_is_different = from_pane != to_pane;
10579    let mut moved_items = 0;
10580    for (item_ix, item_handle) in from_pane
10581        .read(cx)
10582        .items()
10583        .enumerate()
10584        .map(|(ix, item)| (ix, item.clone()))
10585        .collect::<Vec<_>>()
10586    {
10587        let ix = item_ix - moved_items;
10588        if destination_is_different {
10589            // Close item from previous pane
10590            from_pane.update(cx, |source, cx| {
10591                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10592            });
10593            moved_items += 1;
10594        }
10595
10596        // This automatically removes duplicate items in the pane
10597        to_pane.update(cx, |destination, cx| {
10598            destination.add_item(item_handle, true, true, None, window, cx);
10599            window.focus(&destination.focus_handle(cx), cx)
10600        });
10601    }
10602}
10603
10604pub fn move_item(
10605    source: &Entity<Pane>,
10606    destination: &Entity<Pane>,
10607    item_id_to_move: EntityId,
10608    destination_index: usize,
10609    activate: bool,
10610    window: &mut Window,
10611    cx: &mut App,
10612) {
10613    let Some((item_ix, item_handle)) = source
10614        .read(cx)
10615        .items()
10616        .enumerate()
10617        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10618        .map(|(ix, item)| (ix, item.clone()))
10619    else {
10620        // Tab was closed during drag
10621        return;
10622    };
10623
10624    if source != destination {
10625        // Close item from previous pane
10626        source.update(cx, |source, cx| {
10627            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10628        });
10629    }
10630
10631    // This automatically removes duplicate items in the pane
10632    destination.update(cx, |destination, cx| {
10633        destination.add_item_inner(
10634            item_handle,
10635            activate,
10636            activate,
10637            activate,
10638            Some(destination_index),
10639            window,
10640            cx,
10641        );
10642        if activate {
10643            window.focus(&destination.focus_handle(cx), cx)
10644        }
10645    });
10646}
10647
10648pub fn move_active_item(
10649    source: &Entity<Pane>,
10650    destination: &Entity<Pane>,
10651    focus_destination: bool,
10652    close_if_empty: bool,
10653    window: &mut Window,
10654    cx: &mut App,
10655) {
10656    if source == destination {
10657        return;
10658    }
10659    let Some(active_item) = source.read(cx).active_item() else {
10660        return;
10661    };
10662    source.update(cx, |source_pane, cx| {
10663        let item_id = active_item.item_id();
10664        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10665        destination.update(cx, |target_pane, cx| {
10666            target_pane.add_item(
10667                active_item,
10668                focus_destination,
10669                focus_destination,
10670                Some(target_pane.items_len()),
10671                window,
10672                cx,
10673            );
10674        });
10675    });
10676}
10677
10678pub fn clone_active_item(
10679    workspace_id: Option<WorkspaceId>,
10680    source: &Entity<Pane>,
10681    destination: &Entity<Pane>,
10682    focus_destination: bool,
10683    window: &mut Window,
10684    cx: &mut App,
10685) {
10686    if source == destination {
10687        return;
10688    }
10689    let Some(active_item) = source.read(cx).active_item() else {
10690        return;
10691    };
10692    if !active_item.can_split(cx) {
10693        return;
10694    }
10695    let destination = destination.downgrade();
10696    let task = active_item.clone_on_split(workspace_id, window, cx);
10697    window
10698        .spawn(cx, async move |cx| {
10699            let Some(clone) = task.await else {
10700                return;
10701            };
10702            destination
10703                .update_in(cx, |target_pane, window, cx| {
10704                    target_pane.add_item(
10705                        clone,
10706                        focus_destination,
10707                        focus_destination,
10708                        Some(target_pane.items_len()),
10709                        window,
10710                        cx,
10711                    );
10712                })
10713                .log_err();
10714        })
10715        .detach();
10716}
10717
10718#[derive(Debug)]
10719pub struct WorkspacePosition {
10720    pub window_bounds: Option<WindowBounds>,
10721    pub display: Option<Uuid>,
10722    pub centered_layout: bool,
10723}
10724
10725pub fn remote_workspace_position_from_db(
10726    connection_options: RemoteConnectionOptions,
10727    paths_to_open: &[PathBuf],
10728    cx: &App,
10729) -> Task<Result<WorkspacePosition>> {
10730    let paths = paths_to_open.to_vec();
10731    let db = WorkspaceDb::global(cx);
10732    let kvp = db::kvp::KeyValueStore::global(cx);
10733
10734    cx.background_spawn(async move {
10735        let remote_connection_id = db
10736            .get_or_create_remote_connection(connection_options)
10737            .await
10738            .context("fetching serialized ssh project")?;
10739        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10740
10741        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10742            (Some(WindowBounds::Windowed(bounds)), None)
10743        } else {
10744            let restorable_bounds = serialized_workspace
10745                .as_ref()
10746                .and_then(|workspace| {
10747                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10748                })
10749                .or_else(|| persistence::read_default_window_bounds(&kvp));
10750
10751            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10752                (Some(serialized_bounds), Some(serialized_display))
10753            } else {
10754                (None, None)
10755            }
10756        };
10757
10758        let centered_layout = serialized_workspace
10759            .as_ref()
10760            .map(|w| w.centered_layout)
10761            .unwrap_or(false);
10762
10763        Ok(WorkspacePosition {
10764            window_bounds,
10765            display,
10766            centered_layout,
10767        })
10768    })
10769}
10770
10771pub fn with_active_or_new_workspace(
10772    cx: &mut App,
10773    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10774) {
10775    match cx
10776        .active_window()
10777        .and_then(|w| w.downcast::<MultiWorkspace>())
10778    {
10779        Some(multi_workspace) => {
10780            cx.defer(move |cx| {
10781                multi_workspace
10782                    .update(cx, |multi_workspace, window, cx| {
10783                        let workspace = multi_workspace.workspace().clone();
10784                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10785                    })
10786                    .log_err();
10787            });
10788        }
10789        None => {
10790            let app_state = AppState::global(cx);
10791            open_new(
10792                OpenOptions::default(),
10793                app_state,
10794                cx,
10795                move |workspace, window, cx| f(workspace, window, cx),
10796            )
10797            .detach_and_log_err(cx);
10798        }
10799    }
10800}
10801
10802/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10803/// key. This migration path only runs once per panel per workspace.
10804fn load_legacy_panel_size(
10805    panel_key: &str,
10806    dock_position: DockPosition,
10807    workspace: &Workspace,
10808    cx: &mut App,
10809) -> Option<Pixels> {
10810    #[derive(Deserialize)]
10811    struct LegacyPanelState {
10812        #[serde(default)]
10813        width: Option<Pixels>,
10814        #[serde(default)]
10815        height: Option<Pixels>,
10816    }
10817
10818    let workspace_id = workspace
10819        .database_id()
10820        .map(|id| i64::from(id).to_string())
10821        .or_else(|| workspace.session_id())?;
10822
10823    let legacy_key = match panel_key {
10824        "ProjectPanel" => {
10825            format!("{}-{:?}", "ProjectPanel", workspace_id)
10826        }
10827        "OutlinePanel" => {
10828            format!("{}-{:?}", "OutlinePanel", workspace_id)
10829        }
10830        "GitPanel" => {
10831            format!("{}-{:?}", "GitPanel", workspace_id)
10832        }
10833        "TerminalPanel" => {
10834            format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10835        }
10836        _ => return None,
10837    };
10838
10839    let kvp = db::kvp::KeyValueStore::global(cx);
10840    let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10841    let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10842    let size = match dock_position {
10843        DockPosition::Bottom => state.height,
10844        DockPosition::Left | DockPosition::Right => state.width,
10845    }?;
10846
10847    cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10848        .detach_and_log_err(cx);
10849
10850    Some(size)
10851}
10852
10853#[cfg(test)]
10854mod tests {
10855    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10856
10857    use super::*;
10858    use crate::{
10859        dock::{PanelEvent, test::TestPanel},
10860        item::{
10861            ItemBufferKind, ItemEvent,
10862            test::{TestItem, TestProjectItem},
10863        },
10864    };
10865    use fs::FakeFs;
10866    use gpui::{
10867        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10868        UpdateGlobal, VisualTestContext, px,
10869    };
10870    use project::{Project, ProjectEntryId};
10871    use serde_json::json;
10872    use settings::SettingsStore;
10873    use util::path;
10874    use util::rel_path::rel_path;
10875
10876    #[gpui::test]
10877    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10878        init_test(cx);
10879
10880        let fs = FakeFs::new(cx.executor());
10881        let project = Project::test(fs, [], cx).await;
10882        let (workspace, cx) =
10883            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10884
10885        // Adding an item with no ambiguity renders the tab without detail.
10886        let item1 = cx.new(|cx| {
10887            let mut item = TestItem::new(cx);
10888            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10889            item
10890        });
10891        workspace.update_in(cx, |workspace, window, cx| {
10892            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10893        });
10894        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10895
10896        // Adding an item that creates ambiguity increases the level of detail on
10897        // both tabs.
10898        let item2 = cx.new_window_entity(|_window, cx| {
10899            let mut item = TestItem::new(cx);
10900            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10901            item
10902        });
10903        workspace.update_in(cx, |workspace, window, cx| {
10904            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10905        });
10906        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10907        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10908
10909        // Adding an item that creates ambiguity increases the level of detail only
10910        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10911        // we stop at the highest detail available.
10912        let item3 = cx.new(|cx| {
10913            let mut item = TestItem::new(cx);
10914            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10915            item
10916        });
10917        workspace.update_in(cx, |workspace, window, cx| {
10918            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10919        });
10920        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10921        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10922        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10923    }
10924
10925    #[gpui::test]
10926    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10927        init_test(cx);
10928
10929        let fs = FakeFs::new(cx.executor());
10930        fs.insert_tree(
10931            "/root1",
10932            json!({
10933                "one.txt": "",
10934                "two.txt": "",
10935            }),
10936        )
10937        .await;
10938        fs.insert_tree(
10939            "/root2",
10940            json!({
10941                "three.txt": "",
10942            }),
10943        )
10944        .await;
10945
10946        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10947        let (workspace, cx) =
10948            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10949        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10950        let worktree_id = project.update(cx, |project, cx| {
10951            project.worktrees(cx).next().unwrap().read(cx).id()
10952        });
10953
10954        let item1 = cx.new(|cx| {
10955            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10956        });
10957        let item2 = cx.new(|cx| {
10958            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10959        });
10960
10961        // Add an item to an empty pane
10962        workspace.update_in(cx, |workspace, window, cx| {
10963            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10964        });
10965        project.update(cx, |project, cx| {
10966            assert_eq!(
10967                project.active_entry(),
10968                project
10969                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10970                    .map(|e| e.id)
10971            );
10972        });
10973        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10974
10975        // Add a second item to a non-empty pane
10976        workspace.update_in(cx, |workspace, window, cx| {
10977            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10978        });
10979        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10980        project.update(cx, |project, cx| {
10981            assert_eq!(
10982                project.active_entry(),
10983                project
10984                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10985                    .map(|e| e.id)
10986            );
10987        });
10988
10989        // Close the active item
10990        pane.update_in(cx, |pane, window, cx| {
10991            pane.close_active_item(&Default::default(), window, cx)
10992        })
10993        .await
10994        .unwrap();
10995        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10996        project.update(cx, |project, cx| {
10997            assert_eq!(
10998                project.active_entry(),
10999                project
11000                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
11001                    .map(|e| e.id)
11002            );
11003        });
11004
11005        // Add a project folder
11006        project
11007            .update(cx, |project, cx| {
11008                project.find_or_create_worktree("root2", true, cx)
11009            })
11010            .await
11011            .unwrap();
11012        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
11013
11014        // Remove a project folder
11015        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
11016        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
11017    }
11018
11019    #[gpui::test]
11020    async fn test_close_window(cx: &mut TestAppContext) {
11021        init_test(cx);
11022
11023        let fs = FakeFs::new(cx.executor());
11024        fs.insert_tree("/root", json!({ "one": "" })).await;
11025
11026        let project = Project::test(fs, ["root".as_ref()], cx).await;
11027        let (workspace, cx) =
11028            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11029
11030        // When there are no dirty items, there's nothing to do.
11031        let item1 = cx.new(TestItem::new);
11032        workspace.update_in(cx, |w, window, cx| {
11033            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
11034        });
11035        let task = workspace.update_in(cx, |w, window, cx| {
11036            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
11037        });
11038        assert!(task.await.unwrap());
11039
11040        // When there are dirty untitled items, prompt to save each one. If the user
11041        // cancels any prompt, then abort.
11042        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
11043        let item3 = cx.new(|cx| {
11044            TestItem::new(cx)
11045                .with_dirty(true)
11046                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11047        });
11048        workspace.update_in(cx, |w, window, cx| {
11049            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
11050            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
11051        });
11052        let task = workspace.update_in(cx, |w, window, cx| {
11053            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
11054        });
11055        cx.executor().run_until_parked();
11056        cx.simulate_prompt_answer("Cancel"); // cancel save all
11057        cx.executor().run_until_parked();
11058        assert!(!cx.has_pending_prompt());
11059        assert!(!task.await.unwrap());
11060    }
11061
11062    #[gpui::test]
11063    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
11064        init_test(cx);
11065
11066        let fs = FakeFs::new(cx.executor());
11067        fs.insert_tree("/root", json!({ "one": "" })).await;
11068
11069        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
11070        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
11071        let multi_workspace_handle =
11072            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
11073        cx.run_until_parked();
11074
11075        multi_workspace_handle
11076            .update(cx, |mw, _window, cx| {
11077                mw.open_sidebar(cx);
11078            })
11079            .unwrap();
11080
11081        let workspace_a = multi_workspace_handle
11082            .read_with(cx, |mw, _| mw.workspace().clone())
11083            .unwrap();
11084
11085        let workspace_b = multi_workspace_handle
11086            .update(cx, |mw, window, cx| {
11087                mw.test_add_workspace(project_b, window, cx)
11088            })
11089            .unwrap();
11090
11091        // Activate workspace A
11092        multi_workspace_handle
11093            .update(cx, |mw, window, cx| {
11094                mw.activate(workspace_a.clone(), None, window, cx);
11095            })
11096            .unwrap();
11097
11098        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
11099
11100        // Workspace A has a clean item
11101        let item_a = cx.new(TestItem::new);
11102        workspace_a.update_in(cx, |w, window, cx| {
11103            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
11104        });
11105
11106        // Workspace B has a dirty item
11107        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
11108        workspace_b.update_in(cx, |w, window, cx| {
11109            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
11110        });
11111
11112        // Verify workspace A is active
11113        multi_workspace_handle
11114            .read_with(cx, |mw, _| {
11115                assert_eq!(mw.workspace(), &workspace_a);
11116            })
11117            .unwrap();
11118
11119        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
11120        multi_workspace_handle
11121            .update(cx, |mw, window, cx| {
11122                mw.close_window(&CloseWindow, window, cx);
11123            })
11124            .unwrap();
11125        cx.run_until_parked();
11126
11127        // Workspace B should now be active since it has dirty items that need attention
11128        multi_workspace_handle
11129            .read_with(cx, |mw, _| {
11130                assert_eq!(
11131                    mw.workspace(),
11132                    &workspace_b,
11133                    "workspace B should be activated when it prompts"
11134                );
11135            })
11136            .unwrap();
11137
11138        // User cancels the save prompt from workspace B
11139        cx.simulate_prompt_answer("Cancel");
11140        cx.run_until_parked();
11141
11142        // Window should still exist because workspace B's close was cancelled
11143        assert!(
11144            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
11145            "window should still exist after cancelling one workspace's close"
11146        );
11147    }
11148
11149    #[gpui::test]
11150    async fn test_remove_workspace_prompts_for_unsaved_changes(cx: &mut TestAppContext) {
11151        init_test(cx);
11152
11153        let fs = FakeFs::new(cx.executor());
11154        fs.insert_tree("/root", json!({ "one": "" })).await;
11155
11156        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
11157        let project_b = Project::test(fs.clone(), ["root".as_ref()], cx).await;
11158        let multi_workspace_handle =
11159            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
11160        cx.run_until_parked();
11161
11162        multi_workspace_handle
11163            .update(cx, |mw, _window, cx| mw.open_sidebar(cx))
11164            .unwrap();
11165
11166        let workspace_a = multi_workspace_handle
11167            .read_with(cx, |mw, _| mw.workspace().clone())
11168            .unwrap();
11169
11170        let workspace_b = multi_workspace_handle
11171            .update(cx, |mw, window, cx| {
11172                mw.test_add_workspace(project_b, window, cx)
11173            })
11174            .unwrap();
11175
11176        // Activate workspace A.
11177        multi_workspace_handle
11178            .update(cx, |mw, window, cx| {
11179                mw.activate(workspace_a.clone(), None, window, cx);
11180            })
11181            .unwrap();
11182
11183        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
11184
11185        // Workspace B has a dirty item.
11186        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
11187        workspace_b.update_in(cx, |w, window, cx| {
11188            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
11189        });
11190
11191        // Try to remove workspace B. It should prompt because of the dirty item.
11192        let remove_task = multi_workspace_handle
11193            .update(cx, |mw, window, cx| {
11194                mw.remove([workspace_b.clone()], |_, _, _| unreachable!(), window, cx)
11195            })
11196            .unwrap();
11197        cx.run_until_parked();
11198
11199        // The prompt should have activated workspace B.
11200        multi_workspace_handle
11201            .read_with(cx, |mw, _| {
11202                assert_eq!(
11203                    mw.workspace(),
11204                    &workspace_b,
11205                    "workspace B should be active while prompting"
11206                );
11207            })
11208            .unwrap();
11209
11210        // Cancel the prompt — user stays on workspace B.
11211        cx.simulate_prompt_answer("Cancel");
11212        cx.run_until_parked();
11213        let removed = remove_task.await.unwrap();
11214        assert!(!removed, "removal should have been cancelled");
11215
11216        multi_workspace_handle
11217            .read_with(cx, |mw, _cx| {
11218                assert_eq!(
11219                    mw.workspace(),
11220                    &workspace_b,
11221                    "user should stay on workspace B after cancelling"
11222                );
11223                assert_eq!(mw.workspaces().count(), 2, "both workspaces should remain");
11224            })
11225            .unwrap();
11226
11227        // Try again. This time accept the prompt.
11228        let remove_task = multi_workspace_handle
11229            .update(cx, |mw, window, cx| {
11230                // First switch back to A.
11231                mw.activate(workspace_a.clone(), None, window, cx);
11232                mw.remove([workspace_b.clone()], |_, _, _| unreachable!(), window, cx)
11233            })
11234            .unwrap();
11235        cx.run_until_parked();
11236
11237        // Accept the save prompt.
11238        cx.simulate_prompt_answer("Don't Save");
11239        cx.run_until_parked();
11240        let removed = remove_task.await.unwrap();
11241        assert!(removed, "removal should have succeeded");
11242
11243        // Should be back on workspace A, and B should be gone.
11244        multi_workspace_handle
11245            .read_with(cx, |mw, _cx| {
11246                assert_eq!(
11247                    mw.workspace(),
11248                    &workspace_a,
11249                    "should be back on workspace A after removing B"
11250                );
11251                assert_eq!(mw.workspaces().count(), 1, "only workspace A should remain");
11252            })
11253            .unwrap();
11254    }
11255
11256    #[gpui::test]
11257    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
11258        init_test(cx);
11259
11260        // Register TestItem as a serializable item
11261        cx.update(|cx| {
11262            register_serializable_item::<TestItem>(cx);
11263        });
11264
11265        let fs = FakeFs::new(cx.executor());
11266        fs.insert_tree("/root", json!({ "one": "" })).await;
11267
11268        let project = Project::test(fs, ["root".as_ref()], cx).await;
11269        let (workspace, cx) =
11270            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11271
11272        // When there are dirty untitled items, but they can serialize, then there is no prompt.
11273        let item1 = cx.new(|cx| {
11274            TestItem::new(cx)
11275                .with_dirty(true)
11276                .with_serialize(|| Some(Task::ready(Ok(()))))
11277        });
11278        let item2 = cx.new(|cx| {
11279            TestItem::new(cx)
11280                .with_dirty(true)
11281                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11282                .with_serialize(|| Some(Task::ready(Ok(()))))
11283        });
11284        workspace.update_in(cx, |w, window, cx| {
11285            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
11286            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
11287        });
11288        let task = workspace.update_in(cx, |w, window, cx| {
11289            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
11290        });
11291        assert!(task.await.unwrap());
11292    }
11293
11294    #[gpui::test]
11295    async fn test_close_pane_items(cx: &mut TestAppContext) {
11296        init_test(cx);
11297
11298        let fs = FakeFs::new(cx.executor());
11299
11300        let project = Project::test(fs, None, cx).await;
11301        let (workspace, cx) =
11302            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11303
11304        let item1 = cx.new(|cx| {
11305            TestItem::new(cx)
11306                .with_dirty(true)
11307                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11308        });
11309        let item2 = cx.new(|cx| {
11310            TestItem::new(cx)
11311                .with_dirty(true)
11312                .with_conflict(true)
11313                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11314        });
11315        let item3 = cx.new(|cx| {
11316            TestItem::new(cx)
11317                .with_dirty(true)
11318                .with_conflict(true)
11319                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
11320        });
11321        let item4 = cx.new(|cx| {
11322            TestItem::new(cx).with_dirty(true).with_project_items(&[{
11323                let project_item = TestProjectItem::new_untitled(cx);
11324                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11325                project_item
11326            }])
11327        });
11328        let pane = workspace.update_in(cx, |workspace, window, cx| {
11329            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
11330            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
11331            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
11332            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
11333            workspace.active_pane().clone()
11334        });
11335
11336        let close_items = pane.update_in(cx, |pane, window, cx| {
11337            pane.activate_item(1, true, true, window, cx);
11338            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
11339            let item1_id = item1.item_id();
11340            let item3_id = item3.item_id();
11341            let item4_id = item4.item_id();
11342            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
11343                [item1_id, item3_id, item4_id].contains(&id)
11344            })
11345        });
11346        cx.executor().run_until_parked();
11347
11348        assert!(cx.has_pending_prompt());
11349        cx.simulate_prompt_answer("Save all");
11350
11351        cx.executor().run_until_parked();
11352
11353        // Item 1 is saved. There's a prompt to save item 3.
11354        pane.update(cx, |pane, cx| {
11355            assert_eq!(item1.read(cx).save_count, 1);
11356            assert_eq!(item1.read(cx).save_as_count, 0);
11357            assert_eq!(item1.read(cx).reload_count, 0);
11358            assert_eq!(pane.items_len(), 3);
11359            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
11360        });
11361        assert!(cx.has_pending_prompt());
11362
11363        // Cancel saving item 3.
11364        cx.simulate_prompt_answer("Discard");
11365        cx.executor().run_until_parked();
11366
11367        // Item 3 is reloaded. There's a prompt to save item 4.
11368        pane.update(cx, |pane, cx| {
11369            assert_eq!(item3.read(cx).save_count, 0);
11370            assert_eq!(item3.read(cx).save_as_count, 0);
11371            assert_eq!(item3.read(cx).reload_count, 1);
11372            assert_eq!(pane.items_len(), 2);
11373            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
11374        });
11375
11376        // There's a prompt for a path for item 4.
11377        cx.simulate_new_path_selection(|_| Some(Default::default()));
11378        close_items.await.unwrap();
11379
11380        // The requested items are closed.
11381        pane.update(cx, |pane, cx| {
11382            assert_eq!(item4.read(cx).save_count, 0);
11383            assert_eq!(item4.read(cx).save_as_count, 1);
11384            assert_eq!(item4.read(cx).reload_count, 0);
11385            assert_eq!(pane.items_len(), 1);
11386            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
11387        });
11388    }
11389
11390    #[gpui::test]
11391    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
11392        init_test(cx);
11393
11394        let fs = FakeFs::new(cx.executor());
11395        let project = Project::test(fs, [], cx).await;
11396        let (workspace, cx) =
11397            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11398
11399        // Create several workspace items with single project entries, and two
11400        // workspace items with multiple project entries.
11401        let single_entry_items = (0..=4)
11402            .map(|project_entry_id| {
11403                cx.new(|cx| {
11404                    TestItem::new(cx)
11405                        .with_dirty(true)
11406                        .with_project_items(&[dirty_project_item(
11407                            project_entry_id,
11408                            &format!("{project_entry_id}.txt"),
11409                            cx,
11410                        )])
11411                })
11412            })
11413            .collect::<Vec<_>>();
11414        let item_2_3 = cx.new(|cx| {
11415            TestItem::new(cx)
11416                .with_dirty(true)
11417                .with_buffer_kind(ItemBufferKind::Multibuffer)
11418                .with_project_items(&[
11419                    single_entry_items[2].read(cx).project_items[0].clone(),
11420                    single_entry_items[3].read(cx).project_items[0].clone(),
11421                ])
11422        });
11423        let item_3_4 = cx.new(|cx| {
11424            TestItem::new(cx)
11425                .with_dirty(true)
11426                .with_buffer_kind(ItemBufferKind::Multibuffer)
11427                .with_project_items(&[
11428                    single_entry_items[3].read(cx).project_items[0].clone(),
11429                    single_entry_items[4].read(cx).project_items[0].clone(),
11430                ])
11431        });
11432
11433        // Create two panes that contain the following project entries:
11434        //   left pane:
11435        //     multi-entry items:   (2, 3)
11436        //     single-entry items:  0, 2, 3, 4
11437        //   right pane:
11438        //     single-entry items:  4, 1
11439        //     multi-entry items:   (3, 4)
11440        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
11441            let left_pane = workspace.active_pane().clone();
11442            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
11443            workspace.add_item_to_active_pane(
11444                single_entry_items[0].boxed_clone(),
11445                None,
11446                true,
11447                window,
11448                cx,
11449            );
11450            workspace.add_item_to_active_pane(
11451                single_entry_items[2].boxed_clone(),
11452                None,
11453                true,
11454                window,
11455                cx,
11456            );
11457            workspace.add_item_to_active_pane(
11458                single_entry_items[3].boxed_clone(),
11459                None,
11460                true,
11461                window,
11462                cx,
11463            );
11464            workspace.add_item_to_active_pane(
11465                single_entry_items[4].boxed_clone(),
11466                None,
11467                true,
11468                window,
11469                cx,
11470            );
11471
11472            let right_pane =
11473                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11474
11475            let boxed_clone = single_entry_items[1].boxed_clone();
11476            let right_pane = window.spawn(cx, async move |cx| {
11477                right_pane.await.inspect(|right_pane| {
11478                    right_pane
11479                        .update_in(cx, |pane, window, cx| {
11480                            pane.add_item(boxed_clone, true, true, None, window, cx);
11481                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11482                        })
11483                        .unwrap();
11484                })
11485            });
11486
11487            (left_pane, right_pane)
11488        });
11489        let right_pane = right_pane.await.unwrap();
11490        cx.focus(&right_pane);
11491
11492        let close = right_pane.update_in(cx, |pane, window, cx| {
11493            pane.close_all_items(&CloseAllItems::default(), window, cx)
11494                .unwrap()
11495        });
11496        cx.executor().run_until_parked();
11497
11498        let msg = cx.pending_prompt().unwrap().0;
11499        assert!(msg.contains("1.txt"));
11500        assert!(!msg.contains("2.txt"));
11501        assert!(!msg.contains("3.txt"));
11502        assert!(!msg.contains("4.txt"));
11503
11504        // With best-effort close, cancelling item 1 keeps it open but items 4
11505        // and (3,4) still close since their entries exist in left pane.
11506        cx.simulate_prompt_answer("Cancel");
11507        close.await;
11508
11509        right_pane.read_with(cx, |pane, _| {
11510            assert_eq!(pane.items_len(), 1);
11511        });
11512
11513        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11514        left_pane
11515            .update_in(cx, |left_pane, window, cx| {
11516                left_pane.close_item_by_id(
11517                    single_entry_items[3].entity_id(),
11518                    SaveIntent::Skip,
11519                    window,
11520                    cx,
11521                )
11522            })
11523            .await
11524            .unwrap();
11525
11526        let close = left_pane.update_in(cx, |pane, window, cx| {
11527            pane.close_all_items(&CloseAllItems::default(), window, cx)
11528                .unwrap()
11529        });
11530        cx.executor().run_until_parked();
11531
11532        let details = cx.pending_prompt().unwrap().1;
11533        assert!(details.contains("0.txt"));
11534        assert!(details.contains("3.txt"));
11535        assert!(details.contains("4.txt"));
11536        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11537        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11538        // assert!(!details.contains("2.txt"));
11539
11540        cx.simulate_prompt_answer("Save all");
11541        cx.executor().run_until_parked();
11542        close.await;
11543
11544        left_pane.read_with(cx, |pane, _| {
11545            assert_eq!(pane.items_len(), 0);
11546        });
11547    }
11548
11549    #[gpui::test]
11550    async fn test_autosave(cx: &mut gpui::TestAppContext) {
11551        init_test(cx);
11552
11553        let fs = FakeFs::new(cx.executor());
11554        let project = Project::test(fs, [], cx).await;
11555        let (workspace, cx) =
11556            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11557        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11558
11559        let item = cx.new(|cx| {
11560            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11561        });
11562        let item_id = item.entity_id();
11563        workspace.update_in(cx, |workspace, window, cx| {
11564            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11565        });
11566
11567        // Autosave on window change.
11568        item.update(cx, |item, cx| {
11569            SettingsStore::update_global(cx, |settings, cx| {
11570                settings.update_user_settings(cx, |settings| {
11571                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11572                })
11573            });
11574            item.is_dirty = true;
11575        });
11576
11577        // Deactivating the window saves the file.
11578        cx.deactivate_window();
11579        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11580
11581        // Re-activating the window doesn't save the file.
11582        cx.update(|window, _| window.activate_window());
11583        cx.executor().run_until_parked();
11584        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11585
11586        // Autosave on focus change.
11587        item.update_in(cx, |item, window, cx| {
11588            cx.focus_self(window);
11589            SettingsStore::update_global(cx, |settings, cx| {
11590                settings.update_user_settings(cx, |settings| {
11591                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11592                })
11593            });
11594            item.is_dirty = true;
11595        });
11596        // Blurring the item saves the file.
11597        item.update_in(cx, |_, window, _| window.blur());
11598        cx.executor().run_until_parked();
11599        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11600
11601        // Deactivating the window still saves the file.
11602        item.update_in(cx, |item, window, cx| {
11603            cx.focus_self(window);
11604            item.is_dirty = true;
11605        });
11606        cx.deactivate_window();
11607        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11608
11609        // Autosave after delay.
11610        item.update(cx, |item, cx| {
11611            SettingsStore::update_global(cx, |settings, cx| {
11612                settings.update_user_settings(cx, |settings| {
11613                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11614                        milliseconds: 500.into(),
11615                    });
11616                })
11617            });
11618            item.is_dirty = true;
11619            cx.emit(ItemEvent::Edit);
11620        });
11621
11622        // Delay hasn't fully expired, so the file is still dirty and unsaved.
11623        cx.executor().advance_clock(Duration::from_millis(250));
11624        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11625
11626        // After delay expires, the file is saved.
11627        cx.executor().advance_clock(Duration::from_millis(250));
11628        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11629
11630        // Autosave after delay, should save earlier than delay if tab is closed
11631        item.update(cx, |item, cx| {
11632            item.is_dirty = true;
11633            cx.emit(ItemEvent::Edit);
11634        });
11635        cx.executor().advance_clock(Duration::from_millis(250));
11636        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11637
11638        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11639        pane.update_in(cx, |pane, window, cx| {
11640            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11641        })
11642        .await
11643        .unwrap();
11644        assert!(!cx.has_pending_prompt());
11645        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11646
11647        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11648        workspace.update_in(cx, |workspace, window, cx| {
11649            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11650        });
11651        item.update_in(cx, |item, _window, cx| {
11652            item.is_dirty = true;
11653            for project_item in &mut item.project_items {
11654                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11655            }
11656        });
11657        cx.run_until_parked();
11658        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11659
11660        // Autosave on focus change, ensuring closing the tab counts as such.
11661        item.update(cx, |item, cx| {
11662            SettingsStore::update_global(cx, |settings, cx| {
11663                settings.update_user_settings(cx, |settings| {
11664                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11665                })
11666            });
11667            item.is_dirty = true;
11668            for project_item in &mut item.project_items {
11669                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11670            }
11671        });
11672
11673        pane.update_in(cx, |pane, window, cx| {
11674            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11675        })
11676        .await
11677        .unwrap();
11678        assert!(!cx.has_pending_prompt());
11679        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11680
11681        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11682        workspace.update_in(cx, |workspace, window, cx| {
11683            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11684        });
11685        item.update_in(cx, |item, window, cx| {
11686            item.project_items[0].update(cx, |item, _| {
11687                item.entry_id = None;
11688            });
11689            item.is_dirty = true;
11690            window.blur();
11691        });
11692        cx.run_until_parked();
11693        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11694
11695        // Ensure autosave is prevented for deleted files also when closing the buffer.
11696        let _close_items = pane.update_in(cx, |pane, window, cx| {
11697            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11698        });
11699        cx.run_until_parked();
11700        assert!(cx.has_pending_prompt());
11701        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11702    }
11703
11704    #[gpui::test]
11705    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11706        init_test(cx);
11707
11708        let fs = FakeFs::new(cx.executor());
11709        let project = Project::test(fs, [], cx).await;
11710        let (workspace, cx) =
11711            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11712
11713        // Create a multibuffer-like item with two child focus handles,
11714        // simulating individual buffer editors within a multibuffer.
11715        let item = cx.new(|cx| {
11716            TestItem::new(cx)
11717                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11718                .with_child_focus_handles(2, cx)
11719        });
11720        workspace.update_in(cx, |workspace, window, cx| {
11721            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11722        });
11723
11724        // Set autosave to OnFocusChange and focus the first child handle,
11725        // simulating the user's cursor being inside one of the multibuffer's excerpts.
11726        item.update_in(cx, |item, window, cx| {
11727            SettingsStore::update_global(cx, |settings, cx| {
11728                settings.update_user_settings(cx, |settings| {
11729                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11730                })
11731            });
11732            item.is_dirty = true;
11733            window.focus(&item.child_focus_handles[0], cx);
11734        });
11735        cx.executor().run_until_parked();
11736        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11737
11738        // Moving focus from one child to another within the same item should
11739        // NOT trigger autosave — focus is still within the item's focus hierarchy.
11740        item.update_in(cx, |item, window, cx| {
11741            window.focus(&item.child_focus_handles[1], cx);
11742        });
11743        cx.executor().run_until_parked();
11744        item.read_with(cx, |item, _| {
11745            assert_eq!(
11746                item.save_count, 0,
11747                "Switching focus between children within the same item should not autosave"
11748            );
11749        });
11750
11751        // Blurring the item saves the file. This is the core regression scenario:
11752        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11753        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11754        // the leaf is always a child focus handle, so `on_blur` never detected
11755        // focus leaving the item.
11756        item.update_in(cx, |_, window, _| window.blur());
11757        cx.executor().run_until_parked();
11758        item.read_with(cx, |item, _| {
11759            assert_eq!(
11760                item.save_count, 1,
11761                "Blurring should trigger autosave when focus was on a child of the item"
11762            );
11763        });
11764
11765        // Deactivating the window should also trigger autosave when a child of
11766        // the multibuffer item currently owns focus.
11767        item.update_in(cx, |item, window, cx| {
11768            item.is_dirty = true;
11769            window.focus(&item.child_focus_handles[0], cx);
11770        });
11771        cx.executor().run_until_parked();
11772        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11773
11774        cx.deactivate_window();
11775        item.read_with(cx, |item, _| {
11776            assert_eq!(
11777                item.save_count, 2,
11778                "Deactivating window should trigger autosave when focus was on a child"
11779            );
11780        });
11781    }
11782
11783    #[gpui::test]
11784    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11785        init_test(cx);
11786
11787        let fs = FakeFs::new(cx.executor());
11788
11789        let project = Project::test(fs, [], cx).await;
11790        let (workspace, cx) =
11791            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11792
11793        let item = cx.new(|cx| {
11794            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11795        });
11796        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11797        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11798        let toolbar_notify_count = Rc::new(RefCell::new(0));
11799
11800        workspace.update_in(cx, |workspace, window, cx| {
11801            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11802            let toolbar_notification_count = toolbar_notify_count.clone();
11803            cx.observe_in(&toolbar, window, move |_, _, _, _| {
11804                *toolbar_notification_count.borrow_mut() += 1
11805            })
11806            .detach();
11807        });
11808
11809        pane.read_with(cx, |pane, _| {
11810            assert!(!pane.can_navigate_backward());
11811            assert!(!pane.can_navigate_forward());
11812        });
11813
11814        item.update_in(cx, |item, _, cx| {
11815            item.set_state("one".to_string(), cx);
11816        });
11817
11818        // Toolbar must be notified to re-render the navigation buttons
11819        assert_eq!(*toolbar_notify_count.borrow(), 1);
11820
11821        pane.read_with(cx, |pane, _| {
11822            assert!(pane.can_navigate_backward());
11823            assert!(!pane.can_navigate_forward());
11824        });
11825
11826        workspace
11827            .update_in(cx, |workspace, window, cx| {
11828                workspace.go_back(pane.downgrade(), window, cx)
11829            })
11830            .await
11831            .unwrap();
11832
11833        assert_eq!(*toolbar_notify_count.borrow(), 2);
11834        pane.read_with(cx, |pane, _| {
11835            assert!(!pane.can_navigate_backward());
11836            assert!(pane.can_navigate_forward());
11837        });
11838    }
11839
11840    /// Tests that the navigation history deduplicates entries for the same item.
11841    ///
11842    /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11843    /// the navigation history deduplicates by keeping only the most recent visit to each item,
11844    /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11845    /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11846    /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11847    ///
11848    /// This behavior prevents the navigation history from growing unnecessarily large and provides
11849    /// a better user experience by eliminating redundant navigation steps when jumping between files.
11850    #[gpui::test]
11851    async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11852        init_test(cx);
11853
11854        let fs = FakeFs::new(cx.executor());
11855        let project = Project::test(fs, [], cx).await;
11856        let (workspace, cx) =
11857            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11858
11859        let item_a = cx.new(|cx| {
11860            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11861        });
11862        let item_b = cx.new(|cx| {
11863            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11864        });
11865        let item_c = cx.new(|cx| {
11866            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11867        });
11868
11869        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11870
11871        workspace.update_in(cx, |workspace, window, cx| {
11872            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11873            workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11874            workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11875        });
11876
11877        workspace.update_in(cx, |workspace, window, cx| {
11878            workspace.activate_item(&item_a, false, false, window, cx);
11879        });
11880        cx.run_until_parked();
11881
11882        workspace.update_in(cx, |workspace, window, cx| {
11883            workspace.activate_item(&item_b, false, false, window, cx);
11884        });
11885        cx.run_until_parked();
11886
11887        workspace.update_in(cx, |workspace, window, cx| {
11888            workspace.activate_item(&item_a, false, false, window, cx);
11889        });
11890        cx.run_until_parked();
11891
11892        workspace.update_in(cx, |workspace, window, cx| {
11893            workspace.activate_item(&item_b, false, false, window, cx);
11894        });
11895        cx.run_until_parked();
11896
11897        workspace.update_in(cx, |workspace, window, cx| {
11898            workspace.activate_item(&item_a, false, false, window, cx);
11899        });
11900        cx.run_until_parked();
11901
11902        workspace.update_in(cx, |workspace, window, cx| {
11903            workspace.activate_item(&item_b, false, false, window, cx);
11904        });
11905        cx.run_until_parked();
11906
11907        workspace.update_in(cx, |workspace, window, cx| {
11908            workspace.activate_item(&item_c, false, false, window, cx);
11909        });
11910        cx.run_until_parked();
11911
11912        let backward_count = pane.read_with(cx, |pane, cx| {
11913            let mut count = 0;
11914            pane.nav_history().for_each_entry(cx, &mut |_, _| {
11915                count += 1;
11916            });
11917            count
11918        });
11919        assert!(
11920            backward_count <= 4,
11921            "Should have at most 4 entries, got {}",
11922            backward_count
11923        );
11924
11925        workspace
11926            .update_in(cx, |workspace, window, cx| {
11927                workspace.go_back(pane.downgrade(), window, cx)
11928            })
11929            .await
11930            .unwrap();
11931
11932        let active_item = workspace.read_with(cx, |workspace, cx| {
11933            workspace.active_item(cx).unwrap().item_id()
11934        });
11935        assert_eq!(
11936            active_item,
11937            item_b.entity_id(),
11938            "After first go_back, should be at item B"
11939        );
11940
11941        workspace
11942            .update_in(cx, |workspace, window, cx| {
11943                workspace.go_back(pane.downgrade(), window, cx)
11944            })
11945            .await
11946            .unwrap();
11947
11948        let active_item = workspace.read_with(cx, |workspace, cx| {
11949            workspace.active_item(cx).unwrap().item_id()
11950        });
11951        assert_eq!(
11952            active_item,
11953            item_a.entity_id(),
11954            "After second go_back, should be at item A"
11955        );
11956
11957        pane.read_with(cx, |pane, _| {
11958            assert!(pane.can_navigate_forward(), "Should be able to go forward");
11959        });
11960    }
11961
11962    #[gpui::test]
11963    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11964        init_test(cx);
11965        let fs = FakeFs::new(cx.executor());
11966        let project = Project::test(fs, [], cx).await;
11967        let (multi_workspace, cx) =
11968            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11969        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11970
11971        workspace.update_in(cx, |workspace, window, cx| {
11972            let first_item = cx.new(|cx| {
11973                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11974            });
11975            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11976            workspace.split_pane(
11977                workspace.active_pane().clone(),
11978                SplitDirection::Right,
11979                window,
11980                cx,
11981            );
11982            workspace.split_pane(
11983                workspace.active_pane().clone(),
11984                SplitDirection::Right,
11985                window,
11986                cx,
11987            );
11988        });
11989
11990        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11991            let panes = workspace.center.panes();
11992            assert!(panes.len() >= 2);
11993            (
11994                panes.first().expect("at least one pane").entity_id(),
11995                panes.last().expect("at least one pane").entity_id(),
11996            )
11997        });
11998
11999        workspace.update_in(cx, |workspace, window, cx| {
12000            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
12001        });
12002        workspace.update(cx, |workspace, _| {
12003            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
12004            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
12005        });
12006
12007        cx.dispatch_action(ActivateLastPane);
12008
12009        workspace.update(cx, |workspace, _| {
12010            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
12011        });
12012    }
12013
12014    #[gpui::test]
12015    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
12016        init_test(cx);
12017        let fs = FakeFs::new(cx.executor());
12018
12019        let project = Project::test(fs, [], cx).await;
12020        let (workspace, cx) =
12021            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12022
12023        let panel = workspace.update_in(cx, |workspace, window, cx| {
12024            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12025            workspace.add_panel(panel.clone(), window, cx);
12026
12027            workspace
12028                .right_dock()
12029                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12030
12031            panel
12032        });
12033
12034        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12035        pane.update_in(cx, |pane, window, cx| {
12036            let item = cx.new(TestItem::new);
12037            pane.add_item(Box::new(item), true, true, None, window, cx);
12038        });
12039
12040        // Transfer focus from center to panel
12041        workspace.update_in(cx, |workspace, window, cx| {
12042            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12043        });
12044
12045        workspace.update_in(cx, |workspace, window, cx| {
12046            assert!(workspace.right_dock().read(cx).is_open());
12047            assert!(!panel.is_zoomed(window, cx));
12048            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12049        });
12050
12051        // Transfer focus from panel to center
12052        workspace.update_in(cx, |workspace, window, cx| {
12053            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12054        });
12055
12056        workspace.update_in(cx, |workspace, window, cx| {
12057            assert!(workspace.right_dock().read(cx).is_open());
12058            assert!(!panel.is_zoomed(window, cx));
12059            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12060            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
12061        });
12062
12063        // Close the dock
12064        workspace.update_in(cx, |workspace, window, cx| {
12065            workspace.toggle_dock(DockPosition::Right, window, cx);
12066        });
12067
12068        workspace.update_in(cx, |workspace, window, cx| {
12069            assert!(!workspace.right_dock().read(cx).is_open());
12070            assert!(!panel.is_zoomed(window, cx));
12071            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12072            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
12073        });
12074
12075        // Open the dock
12076        workspace.update_in(cx, |workspace, window, cx| {
12077            workspace.toggle_dock(DockPosition::Right, window, cx);
12078        });
12079
12080        workspace.update_in(cx, |workspace, window, cx| {
12081            assert!(workspace.right_dock().read(cx).is_open());
12082            assert!(!panel.is_zoomed(window, cx));
12083            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12084        });
12085
12086        // Focus and zoom panel
12087        panel.update_in(cx, |panel, window, cx| {
12088            cx.focus_self(window);
12089            panel.set_zoomed(true, window, cx)
12090        });
12091
12092        workspace.update_in(cx, |workspace, window, cx| {
12093            assert!(workspace.right_dock().read(cx).is_open());
12094            assert!(panel.is_zoomed(window, cx));
12095            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12096        });
12097
12098        // Transfer focus to the center closes the dock
12099        workspace.update_in(cx, |workspace, window, cx| {
12100            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12101        });
12102
12103        workspace.update_in(cx, |workspace, window, cx| {
12104            assert!(!workspace.right_dock().read(cx).is_open());
12105            assert!(panel.is_zoomed(window, cx));
12106            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12107        });
12108
12109        // Transferring focus back to the panel keeps it zoomed
12110        workspace.update_in(cx, |workspace, window, cx| {
12111            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12112        });
12113
12114        workspace.update_in(cx, |workspace, window, cx| {
12115            assert!(workspace.right_dock().read(cx).is_open());
12116            assert!(panel.is_zoomed(window, cx));
12117            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12118        });
12119
12120        // Close the dock while it is zoomed
12121        workspace.update_in(cx, |workspace, window, cx| {
12122            workspace.toggle_dock(DockPosition::Right, window, cx)
12123        });
12124
12125        workspace.update_in(cx, |workspace, window, cx| {
12126            assert!(!workspace.right_dock().read(cx).is_open());
12127            assert!(panel.is_zoomed(window, cx));
12128            assert!(workspace.zoomed.is_none());
12129            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12130        });
12131
12132        // Opening the dock, when it's zoomed, retains focus
12133        workspace.update_in(cx, |workspace, window, cx| {
12134            workspace.toggle_dock(DockPosition::Right, window, cx)
12135        });
12136
12137        workspace.update_in(cx, |workspace, window, cx| {
12138            assert!(workspace.right_dock().read(cx).is_open());
12139            assert!(panel.is_zoomed(window, cx));
12140            assert!(workspace.zoomed.is_some());
12141            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12142        });
12143
12144        // Unzoom and close the panel, zoom the active pane.
12145        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
12146        workspace.update_in(cx, |workspace, window, cx| {
12147            workspace.toggle_dock(DockPosition::Right, window, cx)
12148        });
12149        pane.update_in(cx, |pane, window, cx| {
12150            pane.toggle_zoom(&Default::default(), window, cx)
12151        });
12152
12153        // Opening a dock unzooms the pane.
12154        workspace.update_in(cx, |workspace, window, cx| {
12155            workspace.toggle_dock(DockPosition::Right, window, cx)
12156        });
12157        workspace.update_in(cx, |workspace, window, cx| {
12158            let pane = pane.read(cx);
12159            assert!(!pane.is_zoomed());
12160            assert!(!pane.focus_handle(cx).is_focused(window));
12161            assert!(workspace.right_dock().read(cx).is_open());
12162            assert!(workspace.zoomed.is_none());
12163        });
12164    }
12165
12166    #[gpui::test]
12167    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
12168        init_test(cx);
12169        let fs = FakeFs::new(cx.executor());
12170
12171        let project = Project::test(fs, [], cx).await;
12172        let (workspace, cx) =
12173            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12174
12175        let panel = workspace.update_in(cx, |workspace, window, cx| {
12176            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12177            workspace.add_panel(panel.clone(), window, cx);
12178            panel
12179        });
12180
12181        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12182        pane.update_in(cx, |pane, window, cx| {
12183            let item = cx.new(TestItem::new);
12184            pane.add_item(Box::new(item), true, true, None, window, cx);
12185        });
12186
12187        // Enable close_panel_on_toggle
12188        cx.update_global(|store: &mut SettingsStore, cx| {
12189            store.update_user_settings(cx, |settings| {
12190                settings.workspace.close_panel_on_toggle = Some(true);
12191            });
12192        });
12193
12194        // Panel starts closed. Toggling should open and focus it.
12195        workspace.update_in(cx, |workspace, window, cx| {
12196            assert!(!workspace.right_dock().read(cx).is_open());
12197            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12198        });
12199
12200        workspace.update_in(cx, |workspace, window, cx| {
12201            assert!(
12202                workspace.right_dock().read(cx).is_open(),
12203                "Dock should be open after toggling from center"
12204            );
12205            assert!(
12206                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12207                "Panel should be focused after toggling from center"
12208            );
12209        });
12210
12211        // Panel is open and focused. Toggling should close the panel and
12212        // return focus to the center.
12213        workspace.update_in(cx, |workspace, window, cx| {
12214            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12215        });
12216
12217        workspace.update_in(cx, |workspace, window, cx| {
12218            assert!(
12219                !workspace.right_dock().read(cx).is_open(),
12220                "Dock should be closed after toggling from focused panel"
12221            );
12222            assert!(
12223                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12224                "Panel should not be focused after toggling from focused panel"
12225            );
12226        });
12227
12228        // Open the dock and focus something else so the panel is open but not
12229        // focused. Toggling should focus the panel (not close it).
12230        workspace.update_in(cx, |workspace, window, cx| {
12231            workspace
12232                .right_dock()
12233                .update(cx, |dock, cx| dock.set_open(true, window, cx));
12234            window.focus(&pane.read(cx).focus_handle(cx), cx);
12235        });
12236
12237        workspace.update_in(cx, |workspace, window, cx| {
12238            assert!(workspace.right_dock().read(cx).is_open());
12239            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12240            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12241        });
12242
12243        workspace.update_in(cx, |workspace, window, cx| {
12244            assert!(
12245                workspace.right_dock().read(cx).is_open(),
12246                "Dock should remain open when toggling focuses an open-but-unfocused panel"
12247            );
12248            assert!(
12249                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12250                "Panel should be focused after toggling an open-but-unfocused panel"
12251            );
12252        });
12253
12254        // Now disable the setting and verify the original behavior: toggling
12255        // from a focused panel moves focus to center but leaves the dock open.
12256        cx.update_global(|store: &mut SettingsStore, cx| {
12257            store.update_user_settings(cx, |settings| {
12258                settings.workspace.close_panel_on_toggle = Some(false);
12259            });
12260        });
12261
12262        workspace.update_in(cx, |workspace, window, cx| {
12263            workspace.toggle_panel_focus::<TestPanel>(window, cx);
12264        });
12265
12266        workspace.update_in(cx, |workspace, window, cx| {
12267            assert!(
12268                workspace.right_dock().read(cx).is_open(),
12269                "Dock should remain open when setting is disabled"
12270            );
12271            assert!(
12272                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12273                "Panel should not be focused after toggling with setting disabled"
12274            );
12275        });
12276    }
12277
12278    #[gpui::test]
12279    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
12280        init_test(cx);
12281        let fs = FakeFs::new(cx.executor());
12282
12283        let project = Project::test(fs, [], cx).await;
12284        let (workspace, cx) =
12285            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12286
12287        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
12288            workspace.active_pane().clone()
12289        });
12290
12291        // Add an item to the pane so it can be zoomed
12292        workspace.update_in(cx, |workspace, window, cx| {
12293            let item = cx.new(TestItem::new);
12294            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
12295        });
12296
12297        // Initially not zoomed
12298        workspace.update_in(cx, |workspace, _window, cx| {
12299            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
12300            assert!(
12301                workspace.zoomed.is_none(),
12302                "Workspace should track no zoomed pane"
12303            );
12304            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
12305        });
12306
12307        // Zoom In
12308        pane.update_in(cx, |pane, window, cx| {
12309            pane.zoom_in(&crate::ZoomIn, window, cx);
12310        });
12311
12312        workspace.update_in(cx, |workspace, window, cx| {
12313            assert!(
12314                pane.read(cx).is_zoomed(),
12315                "Pane should be zoomed after ZoomIn"
12316            );
12317            assert!(
12318                workspace.zoomed.is_some(),
12319                "Workspace should track the zoomed pane"
12320            );
12321            assert!(
12322                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
12323                "ZoomIn should focus the pane"
12324            );
12325        });
12326
12327        // Zoom In again is a no-op
12328        pane.update_in(cx, |pane, window, cx| {
12329            pane.zoom_in(&crate::ZoomIn, window, cx);
12330        });
12331
12332        workspace.update_in(cx, |workspace, window, cx| {
12333            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
12334            assert!(
12335                workspace.zoomed.is_some(),
12336                "Workspace still tracks zoomed pane"
12337            );
12338            assert!(
12339                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
12340                "Pane remains focused after repeated ZoomIn"
12341            );
12342        });
12343
12344        // Zoom Out
12345        pane.update_in(cx, |pane, window, cx| {
12346            pane.zoom_out(&crate::ZoomOut, window, cx);
12347        });
12348
12349        workspace.update_in(cx, |workspace, _window, cx| {
12350            assert!(
12351                !pane.read(cx).is_zoomed(),
12352                "Pane should unzoom after ZoomOut"
12353            );
12354            assert!(
12355                workspace.zoomed.is_none(),
12356                "Workspace clears zoom tracking after ZoomOut"
12357            );
12358        });
12359
12360        // Zoom Out again is a no-op
12361        pane.update_in(cx, |pane, window, cx| {
12362            pane.zoom_out(&crate::ZoomOut, window, cx);
12363        });
12364
12365        workspace.update_in(cx, |workspace, _window, cx| {
12366            assert!(
12367                !pane.read(cx).is_zoomed(),
12368                "Second ZoomOut keeps pane unzoomed"
12369            );
12370            assert!(
12371                workspace.zoomed.is_none(),
12372                "Workspace remains without zoomed pane"
12373            );
12374        });
12375    }
12376
12377    #[gpui::test]
12378    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
12379        init_test(cx);
12380        let fs = FakeFs::new(cx.executor());
12381
12382        let project = Project::test(fs, [], cx).await;
12383        let (workspace, cx) =
12384            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12385        workspace.update_in(cx, |workspace, window, cx| {
12386            // Open two docks
12387            let left_dock = workspace.dock_at_position(DockPosition::Left);
12388            let right_dock = workspace.dock_at_position(DockPosition::Right);
12389
12390            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12391            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12392
12393            assert!(left_dock.read(cx).is_open());
12394            assert!(right_dock.read(cx).is_open());
12395        });
12396
12397        workspace.update_in(cx, |workspace, window, cx| {
12398            // Toggle all docks - should close both
12399            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12400
12401            let left_dock = workspace.dock_at_position(DockPosition::Left);
12402            let right_dock = workspace.dock_at_position(DockPosition::Right);
12403            assert!(!left_dock.read(cx).is_open());
12404            assert!(!right_dock.read(cx).is_open());
12405        });
12406
12407        workspace.update_in(cx, |workspace, window, cx| {
12408            // Toggle again - should reopen both
12409            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12410
12411            let left_dock = workspace.dock_at_position(DockPosition::Left);
12412            let right_dock = workspace.dock_at_position(DockPosition::Right);
12413            assert!(left_dock.read(cx).is_open());
12414            assert!(right_dock.read(cx).is_open());
12415        });
12416    }
12417
12418    #[gpui::test]
12419    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
12420        init_test(cx);
12421        let fs = FakeFs::new(cx.executor());
12422
12423        let project = Project::test(fs, [], cx).await;
12424        let (workspace, cx) =
12425            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12426        workspace.update_in(cx, |workspace, window, cx| {
12427            // Open two docks
12428            let left_dock = workspace.dock_at_position(DockPosition::Left);
12429            let right_dock = workspace.dock_at_position(DockPosition::Right);
12430
12431            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12432            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12433
12434            assert!(left_dock.read(cx).is_open());
12435            assert!(right_dock.read(cx).is_open());
12436        });
12437
12438        workspace.update_in(cx, |workspace, window, cx| {
12439            // Close them manually
12440            workspace.toggle_dock(DockPosition::Left, window, cx);
12441            workspace.toggle_dock(DockPosition::Right, window, cx);
12442
12443            let left_dock = workspace.dock_at_position(DockPosition::Left);
12444            let right_dock = workspace.dock_at_position(DockPosition::Right);
12445            assert!(!left_dock.read(cx).is_open());
12446            assert!(!right_dock.read(cx).is_open());
12447        });
12448
12449        workspace.update_in(cx, |workspace, window, cx| {
12450            // Toggle all docks - only last closed (right dock) should reopen
12451            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12452
12453            let left_dock = workspace.dock_at_position(DockPosition::Left);
12454            let right_dock = workspace.dock_at_position(DockPosition::Right);
12455            assert!(!left_dock.read(cx).is_open());
12456            assert!(right_dock.read(cx).is_open());
12457        });
12458    }
12459
12460    #[gpui::test]
12461    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
12462        init_test(cx);
12463        let fs = FakeFs::new(cx.executor());
12464        let project = Project::test(fs, [], cx).await;
12465        let (multi_workspace, cx) =
12466            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12467        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12468
12469        // Open two docks (left and right) with one panel each
12470        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12471            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12472            workspace.add_panel(left_panel.clone(), window, cx);
12473
12474            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12475            workspace.add_panel(right_panel.clone(), window, cx);
12476
12477            workspace.toggle_dock(DockPosition::Left, window, cx);
12478            workspace.toggle_dock(DockPosition::Right, window, cx);
12479
12480            // Verify initial state
12481            assert!(
12482                workspace.left_dock().read(cx).is_open(),
12483                "Left dock should be open"
12484            );
12485            assert_eq!(
12486                workspace
12487                    .left_dock()
12488                    .read(cx)
12489                    .visible_panel()
12490                    .unwrap()
12491                    .panel_id(),
12492                left_panel.panel_id(),
12493                "Left panel should be visible in left dock"
12494            );
12495            assert!(
12496                workspace.right_dock().read(cx).is_open(),
12497                "Right dock should be open"
12498            );
12499            assert_eq!(
12500                workspace
12501                    .right_dock()
12502                    .read(cx)
12503                    .visible_panel()
12504                    .unwrap()
12505                    .panel_id(),
12506                right_panel.panel_id(),
12507                "Right panel should be visible in right dock"
12508            );
12509            assert!(
12510                !workspace.bottom_dock().read(cx).is_open(),
12511                "Bottom dock should be closed"
12512            );
12513
12514            (left_panel, right_panel)
12515        });
12516
12517        // Focus the left panel and move it to the next position (bottom dock)
12518        workspace.update_in(cx, |workspace, window, cx| {
12519            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12520            assert!(
12521                left_panel.read(cx).focus_handle(cx).is_focused(window),
12522                "Left panel should be focused"
12523            );
12524        });
12525
12526        cx.dispatch_action(MoveFocusedPanelToNextPosition);
12527
12528        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12529        workspace.update(cx, |workspace, cx| {
12530            assert!(
12531                !workspace.left_dock().read(cx).is_open(),
12532                "Left dock should be closed"
12533            );
12534            assert!(
12535                workspace.bottom_dock().read(cx).is_open(),
12536                "Bottom dock should now be open"
12537            );
12538            assert_eq!(
12539                left_panel.read(cx).position,
12540                DockPosition::Bottom,
12541                "Left panel should now be in the bottom dock"
12542            );
12543            assert_eq!(
12544                workspace
12545                    .bottom_dock()
12546                    .read(cx)
12547                    .visible_panel()
12548                    .unwrap()
12549                    .panel_id(),
12550                left_panel.panel_id(),
12551                "Left panel should be the visible panel in the bottom dock"
12552            );
12553        });
12554
12555        // Toggle all docks off
12556        workspace.update_in(cx, |workspace, window, cx| {
12557            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12558            assert!(
12559                !workspace.left_dock().read(cx).is_open(),
12560                "Left dock should be closed"
12561            );
12562            assert!(
12563                !workspace.right_dock().read(cx).is_open(),
12564                "Right dock should be closed"
12565            );
12566            assert!(
12567                !workspace.bottom_dock().read(cx).is_open(),
12568                "Bottom dock should be closed"
12569            );
12570        });
12571
12572        // Toggle all docks back on and verify positions are restored
12573        workspace.update_in(cx, |workspace, window, cx| {
12574            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12575            assert!(
12576                !workspace.left_dock().read(cx).is_open(),
12577                "Left dock should remain closed"
12578            );
12579            assert!(
12580                workspace.right_dock().read(cx).is_open(),
12581                "Right dock should remain open"
12582            );
12583            assert!(
12584                workspace.bottom_dock().read(cx).is_open(),
12585                "Bottom dock should remain open"
12586            );
12587            assert_eq!(
12588                left_panel.read(cx).position,
12589                DockPosition::Bottom,
12590                "Left panel should remain in the bottom dock"
12591            );
12592            assert_eq!(
12593                right_panel.read(cx).position,
12594                DockPosition::Right,
12595                "Right panel should remain in the right dock"
12596            );
12597            assert_eq!(
12598                workspace
12599                    .bottom_dock()
12600                    .read(cx)
12601                    .visible_panel()
12602                    .unwrap()
12603                    .panel_id(),
12604                left_panel.panel_id(),
12605                "Left panel should be the visible panel in the right dock"
12606            );
12607        });
12608    }
12609
12610    #[gpui::test]
12611    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12612        init_test(cx);
12613
12614        let fs = FakeFs::new(cx.executor());
12615
12616        let project = Project::test(fs, None, cx).await;
12617        let (workspace, cx) =
12618            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12619
12620        // Let's arrange the panes like this:
12621        //
12622        // +-----------------------+
12623        // |         top           |
12624        // +------+--------+-------+
12625        // | left | center | right |
12626        // +------+--------+-------+
12627        // |        bottom         |
12628        // +-----------------------+
12629
12630        let top_item = cx.new(|cx| {
12631            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12632        });
12633        let bottom_item = cx.new(|cx| {
12634            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12635        });
12636        let left_item = cx.new(|cx| {
12637            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12638        });
12639        let right_item = cx.new(|cx| {
12640            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12641        });
12642        let center_item = cx.new(|cx| {
12643            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12644        });
12645
12646        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12647            let top_pane_id = workspace.active_pane().entity_id();
12648            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12649            workspace.split_pane(
12650                workspace.active_pane().clone(),
12651                SplitDirection::Down,
12652                window,
12653                cx,
12654            );
12655            top_pane_id
12656        });
12657        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12658            let bottom_pane_id = workspace.active_pane().entity_id();
12659            workspace.add_item_to_active_pane(
12660                Box::new(bottom_item.clone()),
12661                None,
12662                false,
12663                window,
12664                cx,
12665            );
12666            workspace.split_pane(
12667                workspace.active_pane().clone(),
12668                SplitDirection::Up,
12669                window,
12670                cx,
12671            );
12672            bottom_pane_id
12673        });
12674        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12675            let left_pane_id = workspace.active_pane().entity_id();
12676            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12677            workspace.split_pane(
12678                workspace.active_pane().clone(),
12679                SplitDirection::Right,
12680                window,
12681                cx,
12682            );
12683            left_pane_id
12684        });
12685        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12686            let right_pane_id = workspace.active_pane().entity_id();
12687            workspace.add_item_to_active_pane(
12688                Box::new(right_item.clone()),
12689                None,
12690                false,
12691                window,
12692                cx,
12693            );
12694            workspace.split_pane(
12695                workspace.active_pane().clone(),
12696                SplitDirection::Left,
12697                window,
12698                cx,
12699            );
12700            right_pane_id
12701        });
12702        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12703            let center_pane_id = workspace.active_pane().entity_id();
12704            workspace.add_item_to_active_pane(
12705                Box::new(center_item.clone()),
12706                None,
12707                false,
12708                window,
12709                cx,
12710            );
12711            center_pane_id
12712        });
12713        cx.executor().run_until_parked();
12714
12715        workspace.update_in(cx, |workspace, window, cx| {
12716            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12717
12718            // Join into next from center pane into right
12719            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12720        });
12721
12722        workspace.update_in(cx, |workspace, window, cx| {
12723            let active_pane = workspace.active_pane();
12724            assert_eq!(right_pane_id, active_pane.entity_id());
12725            assert_eq!(2, active_pane.read(cx).items_len());
12726            let item_ids_in_pane =
12727                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12728            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12729            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12730
12731            // Join into next from right pane into bottom
12732            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12733        });
12734
12735        workspace.update_in(cx, |workspace, window, cx| {
12736            let active_pane = workspace.active_pane();
12737            assert_eq!(bottom_pane_id, active_pane.entity_id());
12738            assert_eq!(3, active_pane.read(cx).items_len());
12739            let item_ids_in_pane =
12740                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12741            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12742            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12743            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12744
12745            // Join into next from bottom pane into left
12746            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12747        });
12748
12749        workspace.update_in(cx, |workspace, window, cx| {
12750            let active_pane = workspace.active_pane();
12751            assert_eq!(left_pane_id, active_pane.entity_id());
12752            assert_eq!(4, active_pane.read(cx).items_len());
12753            let item_ids_in_pane =
12754                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12755            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12756            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12757            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12758            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12759
12760            // Join into next from left pane into top
12761            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12762        });
12763
12764        workspace.update_in(cx, |workspace, window, cx| {
12765            let active_pane = workspace.active_pane();
12766            assert_eq!(top_pane_id, active_pane.entity_id());
12767            assert_eq!(5, active_pane.read(cx).items_len());
12768            let item_ids_in_pane =
12769                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12770            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12771            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12772            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12773            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12774            assert!(item_ids_in_pane.contains(&top_item.item_id()));
12775
12776            // Single pane left: no-op
12777            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12778        });
12779
12780        workspace.update(cx, |workspace, _cx| {
12781            let active_pane = workspace.active_pane();
12782            assert_eq!(top_pane_id, active_pane.entity_id());
12783        });
12784    }
12785
12786    fn add_an_item_to_active_pane(
12787        cx: &mut VisualTestContext,
12788        workspace: &Entity<Workspace>,
12789        item_id: u64,
12790    ) -> Entity<TestItem> {
12791        let item = cx.new(|cx| {
12792            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12793                item_id,
12794                "item{item_id}.txt",
12795                cx,
12796            )])
12797        });
12798        workspace.update_in(cx, |workspace, window, cx| {
12799            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12800        });
12801        item
12802    }
12803
12804    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12805        workspace.update_in(cx, |workspace, window, cx| {
12806            workspace.split_pane(
12807                workspace.active_pane().clone(),
12808                SplitDirection::Right,
12809                window,
12810                cx,
12811            )
12812        })
12813    }
12814
12815    #[gpui::test]
12816    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12817        init_test(cx);
12818        let fs = FakeFs::new(cx.executor());
12819        let project = Project::test(fs, None, cx).await;
12820        let (workspace, cx) =
12821            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12822
12823        add_an_item_to_active_pane(cx, &workspace, 1);
12824        split_pane(cx, &workspace);
12825        add_an_item_to_active_pane(cx, &workspace, 2);
12826        split_pane(cx, &workspace); // empty pane
12827        split_pane(cx, &workspace);
12828        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12829
12830        cx.executor().run_until_parked();
12831
12832        workspace.update(cx, |workspace, cx| {
12833            let num_panes = workspace.panes().len();
12834            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12835            let active_item = workspace
12836                .active_pane()
12837                .read(cx)
12838                .active_item()
12839                .expect("item is in focus");
12840
12841            assert_eq!(num_panes, 4);
12842            assert_eq!(num_items_in_current_pane, 1);
12843            assert_eq!(active_item.item_id(), last_item.item_id());
12844        });
12845
12846        workspace.update_in(cx, |workspace, window, cx| {
12847            workspace.join_all_panes(window, cx);
12848        });
12849
12850        workspace.update(cx, |workspace, cx| {
12851            let num_panes = workspace.panes().len();
12852            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12853            let active_item = workspace
12854                .active_pane()
12855                .read(cx)
12856                .active_item()
12857                .expect("item is in focus");
12858
12859            assert_eq!(num_panes, 1);
12860            assert_eq!(num_items_in_current_pane, 3);
12861            assert_eq!(active_item.item_id(), last_item.item_id());
12862        });
12863    }
12864
12865    #[gpui::test]
12866    async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12867        init_test(cx);
12868        let fs = FakeFs::new(cx.executor());
12869
12870        let project = Project::test(fs, [], cx).await;
12871        let (multi_workspace, cx) =
12872            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12873        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12874
12875        workspace.update(cx, |workspace, _cx| {
12876            workspace.set_random_database_id();
12877        });
12878
12879        workspace.update_in(cx, |workspace, window, cx| {
12880            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12881            workspace.add_panel(panel.clone(), window, cx);
12882            workspace.toggle_dock(DockPosition::Right, window, cx);
12883
12884            let right_dock = workspace.right_dock().clone();
12885            right_dock.update(cx, |dock, cx| {
12886                dock.set_panel_size_state(
12887                    &panel,
12888                    dock::PanelSizeState {
12889                        size: None,
12890                        flex: Some(1.0),
12891                    },
12892                    cx,
12893                );
12894            });
12895        });
12896
12897        workspace.update_in(cx, |workspace, window, cx| {
12898            let item = cx.new(|cx| {
12899                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12900            });
12901            workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12902            workspace.bounds.size.width = px(1920.);
12903
12904            let dock = workspace.right_dock().read(cx);
12905            let initial_width = workspace
12906                .dock_size(&dock, window, cx)
12907                .expect("flexible dock should have an initial width");
12908
12909            assert_eq!(initial_width, px(960.));
12910        });
12911
12912        workspace.update_in(cx, |workspace, window, cx| {
12913            workspace.split_pane(
12914                workspace.active_pane().clone(),
12915                SplitDirection::Right,
12916                window,
12917                cx,
12918            );
12919
12920            let center_column_count = workspace.center.full_height_column_count();
12921            assert_eq!(center_column_count, 2);
12922
12923            let dock = workspace.right_dock().read(cx);
12924            assert_eq!(workspace.dock_size(&dock, window, cx).unwrap(), px(640.));
12925
12926            workspace.bounds.size.width = px(2400.);
12927
12928            let dock = workspace.right_dock().read(cx);
12929            assert_eq!(workspace.dock_size(&dock, window, cx).unwrap(), px(800.));
12930        });
12931    }
12932
12933    #[gpui::test]
12934    async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12935        init_test(cx);
12936        let fs = FakeFs::new(cx.executor());
12937
12938        // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12939        {
12940            let project = Project::test(fs.clone(), [], cx).await;
12941            let (multi_workspace, cx) =
12942                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12943            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12944
12945            workspace.update(cx, |workspace, _cx| {
12946                workspace.set_random_database_id();
12947                workspace.bounds.size.width = px(800.);
12948            });
12949
12950            let panel = workspace.update_in(cx, |workspace, window, cx| {
12951                let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12952                workspace.add_panel(panel.clone(), window, cx);
12953                workspace.toggle_dock(DockPosition::Left, window, cx);
12954                panel
12955            });
12956
12957            workspace.update_in(cx, |workspace, window, cx| {
12958                workspace.resize_left_dock(px(350.), window, cx);
12959            });
12960
12961            cx.run_until_parked();
12962
12963            let persisted = workspace.read_with(cx, |workspace, cx| {
12964                workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12965            });
12966            assert_eq!(
12967                persisted.and_then(|s| s.size),
12968                Some(px(350.)),
12969                "fixed-width panel size should be persisted to KVP"
12970            );
12971
12972            // Remove the panel and re-add a fresh instance with the same key.
12973            // The new instance should have its size state restored from KVP.
12974            workspace.update_in(cx, |workspace, window, cx| {
12975                workspace.remove_panel(&panel, window, cx);
12976            });
12977
12978            workspace.update_in(cx, |workspace, window, cx| {
12979                let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12980                workspace.add_panel(new_panel, window, cx);
12981
12982                let left_dock = workspace.left_dock().read(cx);
12983                let size_state = left_dock
12984                    .panel::<TestPanel>()
12985                    .and_then(|p| left_dock.stored_panel_size_state(&p));
12986                assert_eq!(
12987                    size_state.and_then(|s| s.size),
12988                    Some(px(350.)),
12989                    "re-added fixed-width panel should restore persisted size from KVP"
12990                );
12991            });
12992        }
12993
12994        // Flexible panel: both pixel size and ratio are persisted and restored.
12995        {
12996            let project = Project::test(fs.clone(), [], cx).await;
12997            let (multi_workspace, cx) =
12998                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12999            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13000
13001            workspace.update(cx, |workspace, _cx| {
13002                workspace.set_random_database_id();
13003                workspace.bounds.size.width = px(800.);
13004            });
13005
13006            let panel = workspace.update_in(cx, |workspace, window, cx| {
13007                let item = cx.new(|cx| {
13008                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
13009                });
13010                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
13011
13012                let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
13013                workspace.add_panel(panel.clone(), window, cx);
13014                workspace.toggle_dock(DockPosition::Right, window, cx);
13015                panel
13016            });
13017
13018            workspace.update_in(cx, |workspace, window, cx| {
13019                workspace.resize_right_dock(px(300.), window, cx);
13020            });
13021
13022            cx.run_until_parked();
13023
13024            let persisted = workspace
13025                .read_with(cx, |workspace, cx| {
13026                    workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
13027                })
13028                .expect("flexible panel state should be persisted to KVP");
13029            assert_eq!(
13030                persisted.size, None,
13031                "flexible panel should not persist a redundant pixel size"
13032            );
13033            let original_ratio = persisted.flex.expect("panel's flex should be persisted");
13034
13035            // Remove the panel and re-add: both size and ratio should be restored.
13036            workspace.update_in(cx, |workspace, window, cx| {
13037                workspace.remove_panel(&panel, window, cx);
13038            });
13039
13040            workspace.update_in(cx, |workspace, window, cx| {
13041                let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
13042                workspace.add_panel(new_panel, window, cx);
13043
13044                let right_dock = workspace.right_dock().read(cx);
13045                let size_state = right_dock
13046                    .panel::<TestPanel>()
13047                    .and_then(|p| right_dock.stored_panel_size_state(&p))
13048                    .expect("re-added flexible panel should have restored size state from KVP");
13049                assert_eq!(
13050                    size_state.size, None,
13051                    "re-added flexible panel should not have a persisted pixel size"
13052                );
13053                assert_eq!(
13054                    size_state.flex,
13055                    Some(original_ratio),
13056                    "re-added flexible panel should restore persisted flex"
13057                );
13058            });
13059        }
13060    }
13061
13062    #[gpui::test]
13063    async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
13064        init_test(cx);
13065        let fs = FakeFs::new(cx.executor());
13066
13067        let project = Project::test(fs, [], cx).await;
13068        let (multi_workspace, cx) =
13069            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13070        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13071
13072        workspace.update(cx, |workspace, _cx| {
13073            workspace.bounds.size.width = px(900.);
13074        });
13075
13076        // Step 1: Add a tab to the center pane then open a flexible panel in the left
13077        // dock. With one full-width center pane the default ratio is 0.5, so the panel
13078        // and the center pane each take half the workspace width.
13079        workspace.update_in(cx, |workspace, window, cx| {
13080            let item = cx.new(|cx| {
13081                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
13082            });
13083            workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
13084
13085            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
13086            workspace.add_panel(panel, window, cx);
13087            workspace.toggle_dock(DockPosition::Left, window, cx);
13088
13089            let left_dock = workspace.left_dock().read(cx);
13090            let left_width = workspace
13091                .dock_size(&left_dock, window, cx)
13092                .expect("left dock should have an active panel");
13093
13094            assert_eq!(
13095                left_width,
13096                workspace.bounds.size.width / 2.,
13097                "flexible left panel should split evenly with the center pane"
13098            );
13099        });
13100
13101        // Step 2: Split the center pane left/right. The flexible panel is treated as one
13102        // average center column, so with two center columns it should take one third of
13103        // the workspace width.
13104        workspace.update_in(cx, |workspace, window, cx| {
13105            workspace.split_pane(
13106                workspace.active_pane().clone(),
13107                SplitDirection::Right,
13108                window,
13109                cx,
13110            );
13111
13112            let left_dock = workspace.left_dock().read(cx);
13113            let left_width = workspace
13114                .dock_size(&left_dock, window, cx)
13115                .expect("left dock should still have an active panel after horizontal split");
13116
13117            assert_eq!(
13118                left_width,
13119                workspace.bounds.size.width / 3.,
13120                "flexible left panel width should match the average center column width"
13121            );
13122        });
13123
13124        // Step 3: Split the active center pane vertically (top/bottom). Vertical splits do
13125        // not change the number of center columns, so the flexible panel width stays the same.
13126        workspace.update_in(cx, |workspace, window, cx| {
13127            workspace.split_pane(
13128                workspace.active_pane().clone(),
13129                SplitDirection::Down,
13130                window,
13131                cx,
13132            );
13133
13134            let left_dock = workspace.left_dock().read(cx);
13135            let left_width = workspace
13136                .dock_size(&left_dock, window, cx)
13137                .expect("left dock should still have an active panel after vertical split");
13138
13139            assert_eq!(
13140                left_width,
13141                workspace.bounds.size.width / 3.,
13142                "flexible left panel width should still match the average center column width"
13143            );
13144        });
13145
13146        // Step 4: Open a fixed-width panel in the right dock. The right dock's default
13147        // size reduces the available width, so the flexible left panel keeps matching one
13148        // average center column within the remaining space.
13149        workspace.update_in(cx, |workspace, window, cx| {
13150            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
13151            workspace.add_panel(panel, window, cx);
13152            workspace.toggle_dock(DockPosition::Right, window, cx);
13153
13154            let right_dock = workspace.right_dock().read(cx);
13155            let right_width = workspace
13156                .dock_size(&right_dock, window, cx)
13157                .expect("right dock should have an active panel");
13158
13159            let left_dock = workspace.left_dock().read(cx);
13160            let left_width = workspace
13161                .dock_size(&left_dock, window, cx)
13162                .expect("left dock should still have an active panel");
13163
13164            let available_width = workspace.bounds.size.width - right_width;
13165            assert_eq!(
13166                left_width,
13167                available_width / 3.,
13168                "flexible left panel should keep matching one average center column"
13169            );
13170        });
13171
13172        // Step 5: Toggle the right dock's panel to flexible. Now both docks use
13173        // column-equivalent flex sizing and the workspace width is divided among
13174        // left-flex, two center columns, and right-flex.
13175        workspace.update_in(cx, |workspace, window, cx| {
13176            let right_dock = workspace.right_dock().clone();
13177            let right_panel = right_dock
13178                .read(cx)
13179                .visible_panel()
13180                .expect("right dock should have a visible panel")
13181                .clone();
13182            workspace.toggle_dock_panel_flexible_size(
13183                &right_dock,
13184                right_panel.as_ref(),
13185                window,
13186                cx,
13187            );
13188
13189            let right_dock = right_dock.read(cx);
13190            let right_panel = right_dock
13191                .visible_panel()
13192                .expect("right dock should still have a visible panel");
13193            assert!(
13194                right_panel.has_flexible_size(window, cx),
13195                "right panel should now be flexible"
13196            );
13197
13198            let right_size_state = right_dock
13199                .stored_panel_size_state(right_panel.as_ref())
13200                .expect("right panel should have a stored size state after toggling");
13201            let right_flex = right_size_state
13202                .flex
13203                .expect("right panel should have a flex value after toggling");
13204
13205            let left_dock = workspace.left_dock().read(cx);
13206            let left_width = workspace
13207                .dock_size(&left_dock, window, cx)
13208                .expect("left dock should still have an active panel");
13209            let right_width = workspace
13210                .dock_size(&right_dock, window, cx)
13211                .expect("right dock should still have an active panel");
13212
13213            let left_flex = workspace
13214                .default_dock_flex(DockPosition::Left)
13215                .expect("left dock should have a default flex");
13216            let center_column_count = workspace.center.full_height_column_count() as f32;
13217
13218            let total_flex = left_flex + center_column_count + right_flex;
13219            let expected_left = left_flex / total_flex * workspace.bounds.size.width;
13220            let expected_right = right_flex / total_flex * workspace.bounds.size.width;
13221            assert_eq!(
13222                left_width, expected_left,
13223                "flexible left panel should share workspace width via flex ratios"
13224            );
13225            assert_eq!(
13226                right_width, expected_right,
13227                "flexible right panel should share workspace width via flex ratios"
13228            );
13229        });
13230    }
13231
13232    struct TestModal(FocusHandle);
13233
13234    impl TestModal {
13235        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
13236            Self(cx.focus_handle())
13237        }
13238    }
13239
13240    impl EventEmitter<DismissEvent> for TestModal {}
13241
13242    impl Focusable for TestModal {
13243        fn focus_handle(&self, _cx: &App) -> FocusHandle {
13244            self.0.clone()
13245        }
13246    }
13247
13248    impl ModalView for TestModal {}
13249
13250    impl Render for TestModal {
13251        fn render(
13252            &mut self,
13253            _window: &mut Window,
13254            _cx: &mut Context<TestModal>,
13255        ) -> impl IntoElement {
13256            div().track_focus(&self.0)
13257        }
13258    }
13259
13260    #[gpui::test]
13261    async fn test_panels(cx: &mut gpui::TestAppContext) {
13262        init_test(cx);
13263        let fs = FakeFs::new(cx.executor());
13264
13265        let project = Project::test(fs, [], cx).await;
13266        let (multi_workspace, cx) =
13267            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13268        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13269
13270        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
13271            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
13272            workspace.add_panel(panel_1.clone(), window, cx);
13273            workspace.toggle_dock(DockPosition::Left, window, cx);
13274            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
13275            workspace.add_panel(panel_2.clone(), window, cx);
13276            workspace.toggle_dock(DockPosition::Right, window, cx);
13277
13278            let left_dock = workspace.left_dock();
13279            assert_eq!(
13280                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13281                panel_1.panel_id()
13282            );
13283            assert_eq!(
13284                workspace.dock_size(&left_dock.read(cx), window, cx),
13285                Some(px(300.))
13286            );
13287
13288            workspace.resize_left_dock(px(1337.), window, cx);
13289            assert_eq!(
13290                workspace
13291                    .right_dock()
13292                    .read(cx)
13293                    .visible_panel()
13294                    .unwrap()
13295                    .panel_id(),
13296                panel_2.panel_id(),
13297            );
13298
13299            (panel_1, panel_2)
13300        });
13301
13302        // Move panel_1 to the right
13303        panel_1.update_in(cx, |panel_1, window, cx| {
13304            panel_1.set_position(DockPosition::Right, window, cx)
13305        });
13306
13307        workspace.update_in(cx, |workspace, window, cx| {
13308            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
13309            // Since it was the only panel on the left, the left dock should now be closed.
13310            assert!(!workspace.left_dock().read(cx).is_open());
13311            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
13312            let right_dock = workspace.right_dock();
13313            assert_eq!(
13314                right_dock.read(cx).visible_panel().unwrap().panel_id(),
13315                panel_1.panel_id()
13316            );
13317            assert_eq!(
13318                right_dock
13319                    .read(cx)
13320                    .active_panel_size()
13321                    .unwrap()
13322                    .size
13323                    .unwrap(),
13324                px(1337.)
13325            );
13326
13327            // Now we move panel_2 to the left
13328            panel_2.set_position(DockPosition::Left, window, cx);
13329        });
13330
13331        workspace.update(cx, |workspace, cx| {
13332            // Since panel_2 was not visible on the right, we don't open the left dock.
13333            assert!(!workspace.left_dock().read(cx).is_open());
13334            // And the right dock is unaffected in its displaying of panel_1
13335            assert!(workspace.right_dock().read(cx).is_open());
13336            assert_eq!(
13337                workspace
13338                    .right_dock()
13339                    .read(cx)
13340                    .visible_panel()
13341                    .unwrap()
13342                    .panel_id(),
13343                panel_1.panel_id(),
13344            );
13345        });
13346
13347        // Move panel_1 back to the left
13348        panel_1.update_in(cx, |panel_1, window, cx| {
13349            panel_1.set_position(DockPosition::Left, window, cx)
13350        });
13351
13352        workspace.update_in(cx, |workspace, window, cx| {
13353            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
13354            let left_dock = workspace.left_dock();
13355            assert!(left_dock.read(cx).is_open());
13356            assert_eq!(
13357                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13358                panel_1.panel_id()
13359            );
13360            assert_eq!(
13361                workspace.dock_size(&left_dock.read(cx), window, cx),
13362                Some(px(1337.))
13363            );
13364            // And the right dock should be closed as it no longer has any panels.
13365            assert!(!workspace.right_dock().read(cx).is_open());
13366
13367            // Now we move panel_1 to the bottom
13368            panel_1.set_position(DockPosition::Bottom, window, cx);
13369        });
13370
13371        workspace.update_in(cx, |workspace, window, cx| {
13372            // Since panel_1 was visible on the left, we close the left dock.
13373            assert!(!workspace.left_dock().read(cx).is_open());
13374            // The bottom dock is sized based on the panel's default size,
13375            // since the panel orientation changed from vertical to horizontal.
13376            let bottom_dock = workspace.bottom_dock();
13377            assert_eq!(
13378                workspace.dock_size(&bottom_dock.read(cx), window, cx),
13379                Some(px(300.))
13380            );
13381            // Close bottom dock and move panel_1 back to the left.
13382            bottom_dock.update(cx, |bottom_dock, cx| {
13383                bottom_dock.set_open(false, window, cx)
13384            });
13385            panel_1.set_position(DockPosition::Left, window, cx);
13386        });
13387
13388        // Emit activated event on panel 1
13389        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
13390
13391        // Now the left dock is open and panel_1 is active and focused.
13392        workspace.update_in(cx, |workspace, window, cx| {
13393            let left_dock = workspace.left_dock();
13394            assert!(left_dock.read(cx).is_open());
13395            assert_eq!(
13396                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13397                panel_1.panel_id(),
13398            );
13399            assert!(panel_1.focus_handle(cx).is_focused(window));
13400        });
13401
13402        // Emit closed event on panel 2, which is not active
13403        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13404
13405        // Wo don't close the left dock, because panel_2 wasn't the active panel
13406        workspace.update(cx, |workspace, cx| {
13407            let left_dock = workspace.left_dock();
13408            assert!(left_dock.read(cx).is_open());
13409            assert_eq!(
13410                left_dock.read(cx).visible_panel().unwrap().panel_id(),
13411                panel_1.panel_id(),
13412            );
13413        });
13414
13415        // Emitting a ZoomIn event shows the panel as zoomed.
13416        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
13417        workspace.read_with(cx, |workspace, _| {
13418            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13419            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
13420        });
13421
13422        // Move panel to another dock while it is zoomed
13423        panel_1.update_in(cx, |panel, window, cx| {
13424            panel.set_position(DockPosition::Right, window, cx)
13425        });
13426        workspace.read_with(cx, |workspace, _| {
13427            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13428
13429            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13430        });
13431
13432        // This is a helper for getting a:
13433        // - valid focus on an element,
13434        // - that isn't a part of the panes and panels system of the Workspace,
13435        // - and doesn't trigger the 'on_focus_lost' API.
13436        let focus_other_view = {
13437            let workspace = workspace.clone();
13438            move |cx: &mut VisualTestContext| {
13439                workspace.update_in(cx, |workspace, window, cx| {
13440                    if workspace.active_modal::<TestModal>(cx).is_some() {
13441                        workspace.toggle_modal(window, cx, TestModal::new);
13442                        workspace.toggle_modal(window, cx, TestModal::new);
13443                    } else {
13444                        workspace.toggle_modal(window, cx, TestModal::new);
13445                    }
13446                })
13447            }
13448        };
13449
13450        // If focus is transferred to another view that's not a panel or another pane, we still show
13451        // the panel as zoomed.
13452        focus_other_view(cx);
13453        workspace.read_with(cx, |workspace, _| {
13454            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13455            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13456        });
13457
13458        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13459        workspace.update_in(cx, |_workspace, window, cx| {
13460            cx.focus_self(window);
13461        });
13462        workspace.read_with(cx, |workspace, _| {
13463            assert_eq!(workspace.zoomed, None);
13464            assert_eq!(workspace.zoomed_position, None);
13465        });
13466
13467        // If focus is transferred again to another view that's not a panel or a pane, we won't
13468        // show the panel as zoomed because it wasn't zoomed before.
13469        focus_other_view(cx);
13470        workspace.read_with(cx, |workspace, _| {
13471            assert_eq!(workspace.zoomed, None);
13472            assert_eq!(workspace.zoomed_position, None);
13473        });
13474
13475        // When the panel is activated, it is zoomed again.
13476        cx.dispatch_action(ToggleRightDock);
13477        workspace.read_with(cx, |workspace, _| {
13478            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13479            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13480        });
13481
13482        // Emitting a ZoomOut event unzooms the panel.
13483        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13484        workspace.read_with(cx, |workspace, _| {
13485            assert_eq!(workspace.zoomed, None);
13486            assert_eq!(workspace.zoomed_position, None);
13487        });
13488
13489        // Emit closed event on panel 1, which is active
13490        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13491
13492        // Now the left dock is closed, because panel_1 was the active panel
13493        workspace.update(cx, |workspace, cx| {
13494            let right_dock = workspace.right_dock();
13495            assert!(!right_dock.read(cx).is_open());
13496        });
13497    }
13498
13499    #[gpui::test]
13500    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13501        init_test(cx);
13502
13503        let fs = FakeFs::new(cx.background_executor.clone());
13504        let project = Project::test(fs, [], cx).await;
13505        let (workspace, cx) =
13506            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13507        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13508
13509        let dirty_regular_buffer = cx.new(|cx| {
13510            TestItem::new(cx)
13511                .with_dirty(true)
13512                .with_label("1.txt")
13513                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13514        });
13515        let dirty_regular_buffer_2 = cx.new(|cx| {
13516            TestItem::new(cx)
13517                .with_dirty(true)
13518                .with_label("2.txt")
13519                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13520        });
13521        let dirty_multi_buffer_with_both = cx.new(|cx| {
13522            TestItem::new(cx)
13523                .with_dirty(true)
13524                .with_buffer_kind(ItemBufferKind::Multibuffer)
13525                .with_label("Fake Project Search")
13526                .with_project_items(&[
13527                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13528                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13529                ])
13530        });
13531        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13532        workspace.update_in(cx, |workspace, window, cx| {
13533            workspace.add_item(
13534                pane.clone(),
13535                Box::new(dirty_regular_buffer.clone()),
13536                None,
13537                false,
13538                false,
13539                window,
13540                cx,
13541            );
13542            workspace.add_item(
13543                pane.clone(),
13544                Box::new(dirty_regular_buffer_2.clone()),
13545                None,
13546                false,
13547                false,
13548                window,
13549                cx,
13550            );
13551            workspace.add_item(
13552                pane.clone(),
13553                Box::new(dirty_multi_buffer_with_both.clone()),
13554                None,
13555                false,
13556                false,
13557                window,
13558                cx,
13559            );
13560        });
13561
13562        pane.update_in(cx, |pane, window, cx| {
13563            pane.activate_item(2, true, true, window, cx);
13564            assert_eq!(
13565                pane.active_item().unwrap().item_id(),
13566                multi_buffer_with_both_files_id,
13567                "Should select the multi buffer in the pane"
13568            );
13569        });
13570        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13571            pane.close_other_items(
13572                &CloseOtherItems {
13573                    save_intent: Some(SaveIntent::Save),
13574                    close_pinned: true,
13575                },
13576                None,
13577                window,
13578                cx,
13579            )
13580        });
13581        cx.background_executor.run_until_parked();
13582        assert!(!cx.has_pending_prompt());
13583        close_all_but_multi_buffer_task
13584            .await
13585            .expect("Closing all buffers but the multi buffer failed");
13586        pane.update(cx, |pane, cx| {
13587            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13588            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13589            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13590            assert_eq!(pane.items_len(), 1);
13591            assert_eq!(
13592                pane.active_item().unwrap().item_id(),
13593                multi_buffer_with_both_files_id,
13594                "Should have only the multi buffer left in the pane"
13595            );
13596            assert!(
13597                dirty_multi_buffer_with_both.read(cx).is_dirty,
13598                "The multi buffer containing the unsaved buffer should still be dirty"
13599            );
13600        });
13601
13602        dirty_regular_buffer.update(cx, |buffer, cx| {
13603            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13604        });
13605
13606        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13607            pane.close_active_item(
13608                &CloseActiveItem {
13609                    save_intent: Some(SaveIntent::Close),
13610                    close_pinned: false,
13611                },
13612                window,
13613                cx,
13614            )
13615        });
13616        cx.background_executor.run_until_parked();
13617        assert!(
13618            cx.has_pending_prompt(),
13619            "Dirty multi buffer should prompt a save dialog"
13620        );
13621        cx.simulate_prompt_answer("Save");
13622        cx.background_executor.run_until_parked();
13623        close_multi_buffer_task
13624            .await
13625            .expect("Closing the multi buffer failed");
13626        pane.update(cx, |pane, cx| {
13627            assert_eq!(
13628                dirty_multi_buffer_with_both.read(cx).save_count,
13629                1,
13630                "Multi buffer item should get be saved"
13631            );
13632            // Test impl does not save inner items, so we do not assert them
13633            assert_eq!(
13634                pane.items_len(),
13635                0,
13636                "No more items should be left in the pane"
13637            );
13638            assert!(pane.active_item().is_none());
13639        });
13640    }
13641
13642    #[gpui::test]
13643    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13644        cx: &mut TestAppContext,
13645    ) {
13646        init_test(cx);
13647
13648        let fs = FakeFs::new(cx.background_executor.clone());
13649        let project = Project::test(fs, [], cx).await;
13650        let (workspace, cx) =
13651            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13652        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13653
13654        let dirty_regular_buffer = cx.new(|cx| {
13655            TestItem::new(cx)
13656                .with_dirty(true)
13657                .with_label("1.txt")
13658                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13659        });
13660        let dirty_regular_buffer_2 = cx.new(|cx| {
13661            TestItem::new(cx)
13662                .with_dirty(true)
13663                .with_label("2.txt")
13664                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13665        });
13666        let clear_regular_buffer = cx.new(|cx| {
13667            TestItem::new(cx)
13668                .with_label("3.txt")
13669                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13670        });
13671
13672        let dirty_multi_buffer_with_both = cx.new(|cx| {
13673            TestItem::new(cx)
13674                .with_dirty(true)
13675                .with_buffer_kind(ItemBufferKind::Multibuffer)
13676                .with_label("Fake Project Search")
13677                .with_project_items(&[
13678                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13679                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13680                    clear_regular_buffer.read(cx).project_items[0].clone(),
13681                ])
13682        });
13683        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13684        workspace.update_in(cx, |workspace, window, cx| {
13685            workspace.add_item(
13686                pane.clone(),
13687                Box::new(dirty_regular_buffer.clone()),
13688                None,
13689                false,
13690                false,
13691                window,
13692                cx,
13693            );
13694            workspace.add_item(
13695                pane.clone(),
13696                Box::new(dirty_multi_buffer_with_both.clone()),
13697                None,
13698                false,
13699                false,
13700                window,
13701                cx,
13702            );
13703        });
13704
13705        pane.update_in(cx, |pane, window, cx| {
13706            pane.activate_item(1, true, true, window, cx);
13707            assert_eq!(
13708                pane.active_item().unwrap().item_id(),
13709                multi_buffer_with_both_files_id,
13710                "Should select the multi buffer in the pane"
13711            );
13712        });
13713        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13714            pane.close_active_item(
13715                &CloseActiveItem {
13716                    save_intent: None,
13717                    close_pinned: false,
13718                },
13719                window,
13720                cx,
13721            )
13722        });
13723        cx.background_executor.run_until_parked();
13724        assert!(
13725            cx.has_pending_prompt(),
13726            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13727        );
13728    }
13729
13730    /// Tests that when `close_on_file_delete` is enabled, files are automatically
13731    /// closed when they are deleted from disk.
13732    #[gpui::test]
13733    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13734        init_test(cx);
13735
13736        // Enable the close_on_disk_deletion setting
13737        cx.update_global(|store: &mut SettingsStore, cx| {
13738            store.update_user_settings(cx, |settings| {
13739                settings.workspace.close_on_file_delete = Some(true);
13740            });
13741        });
13742
13743        let fs = FakeFs::new(cx.background_executor.clone());
13744        let project = Project::test(fs, [], cx).await;
13745        let (workspace, cx) =
13746            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13747        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13748
13749        // Create a test item that simulates a file
13750        let item = cx.new(|cx| {
13751            TestItem::new(cx)
13752                .with_label("test.txt")
13753                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13754        });
13755
13756        // Add item to workspace
13757        workspace.update_in(cx, |workspace, window, cx| {
13758            workspace.add_item(
13759                pane.clone(),
13760                Box::new(item.clone()),
13761                None,
13762                false,
13763                false,
13764                window,
13765                cx,
13766            );
13767        });
13768
13769        // Verify the item is in the pane
13770        pane.read_with(cx, |pane, _| {
13771            assert_eq!(pane.items().count(), 1);
13772        });
13773
13774        // Simulate file deletion by setting the item's deleted state
13775        item.update(cx, |item, _| {
13776            item.set_has_deleted_file(true);
13777        });
13778
13779        // Emit UpdateTab event to trigger the close behavior
13780        cx.run_until_parked();
13781        item.update(cx, |_, cx| {
13782            cx.emit(ItemEvent::UpdateTab);
13783        });
13784
13785        // Allow the close operation to complete
13786        cx.run_until_parked();
13787
13788        // Verify the item was automatically closed
13789        pane.read_with(cx, |pane, _| {
13790            assert_eq!(
13791                pane.items().count(),
13792                0,
13793                "Item should be automatically closed when file is deleted"
13794            );
13795        });
13796    }
13797
13798    /// Tests that when `close_on_file_delete` is disabled (default), files remain
13799    /// open with a strikethrough when they are deleted from disk.
13800    #[gpui::test]
13801    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13802        init_test(cx);
13803
13804        // Ensure close_on_disk_deletion is disabled (default)
13805        cx.update_global(|store: &mut SettingsStore, cx| {
13806            store.update_user_settings(cx, |settings| {
13807                settings.workspace.close_on_file_delete = Some(false);
13808            });
13809        });
13810
13811        let fs = FakeFs::new(cx.background_executor.clone());
13812        let project = Project::test(fs, [], cx).await;
13813        let (workspace, cx) =
13814            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13815        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13816
13817        // Create a test item that simulates a file
13818        let item = cx.new(|cx| {
13819            TestItem::new(cx)
13820                .with_label("test.txt")
13821                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13822        });
13823
13824        // Add item to workspace
13825        workspace.update_in(cx, |workspace, window, cx| {
13826            workspace.add_item(
13827                pane.clone(),
13828                Box::new(item.clone()),
13829                None,
13830                false,
13831                false,
13832                window,
13833                cx,
13834            );
13835        });
13836
13837        // Verify the item is in the pane
13838        pane.read_with(cx, |pane, _| {
13839            assert_eq!(pane.items().count(), 1);
13840        });
13841
13842        // Simulate file deletion
13843        item.update(cx, |item, _| {
13844            item.set_has_deleted_file(true);
13845        });
13846
13847        // Emit UpdateTab event
13848        cx.run_until_parked();
13849        item.update(cx, |_, cx| {
13850            cx.emit(ItemEvent::UpdateTab);
13851        });
13852
13853        // Allow any potential close operation to complete
13854        cx.run_until_parked();
13855
13856        // Verify the item remains open (with strikethrough)
13857        pane.read_with(cx, |pane, _| {
13858            assert_eq!(
13859                pane.items().count(),
13860                1,
13861                "Item should remain open when close_on_disk_deletion is disabled"
13862            );
13863        });
13864
13865        // Verify the item shows as deleted
13866        item.read_with(cx, |item, _| {
13867            assert!(
13868                item.has_deleted_file,
13869                "Item should be marked as having deleted file"
13870            );
13871        });
13872    }
13873
13874    /// Tests that dirty files are not automatically closed when deleted from disk,
13875    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13876    /// unsaved changes without being prompted.
13877    #[gpui::test]
13878    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13879        init_test(cx);
13880
13881        // Enable the close_on_file_delete setting
13882        cx.update_global(|store: &mut SettingsStore, cx| {
13883            store.update_user_settings(cx, |settings| {
13884                settings.workspace.close_on_file_delete = Some(true);
13885            });
13886        });
13887
13888        let fs = FakeFs::new(cx.background_executor.clone());
13889        let project = Project::test(fs, [], cx).await;
13890        let (workspace, cx) =
13891            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13892        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13893
13894        // Create a dirty test item
13895        let item = cx.new(|cx| {
13896            TestItem::new(cx)
13897                .with_dirty(true)
13898                .with_label("test.txt")
13899                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13900        });
13901
13902        // Add item to workspace
13903        workspace.update_in(cx, |workspace, window, cx| {
13904            workspace.add_item(
13905                pane.clone(),
13906                Box::new(item.clone()),
13907                None,
13908                false,
13909                false,
13910                window,
13911                cx,
13912            );
13913        });
13914
13915        // Simulate file deletion
13916        item.update(cx, |item, _| {
13917            item.set_has_deleted_file(true);
13918        });
13919
13920        // Emit UpdateTab event to trigger the close behavior
13921        cx.run_until_parked();
13922        item.update(cx, |_, cx| {
13923            cx.emit(ItemEvent::UpdateTab);
13924        });
13925
13926        // Allow any potential close operation to complete
13927        cx.run_until_parked();
13928
13929        // Verify the item remains open (dirty files are not auto-closed)
13930        pane.read_with(cx, |pane, _| {
13931            assert_eq!(
13932                pane.items().count(),
13933                1,
13934                "Dirty items should not be automatically closed even when file is deleted"
13935            );
13936        });
13937
13938        // Verify the item is marked as deleted and still dirty
13939        item.read_with(cx, |item, _| {
13940            assert!(
13941                item.has_deleted_file,
13942                "Item should be marked as having deleted file"
13943            );
13944            assert!(item.is_dirty, "Item should still be dirty");
13945        });
13946    }
13947
13948    /// Tests that navigation history is cleaned up when files are auto-closed
13949    /// due to deletion from disk.
13950    #[gpui::test]
13951    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13952        init_test(cx);
13953
13954        // Enable the close_on_file_delete setting
13955        cx.update_global(|store: &mut SettingsStore, cx| {
13956            store.update_user_settings(cx, |settings| {
13957                settings.workspace.close_on_file_delete = Some(true);
13958            });
13959        });
13960
13961        let fs = FakeFs::new(cx.background_executor.clone());
13962        let project = Project::test(fs, [], cx).await;
13963        let (workspace, cx) =
13964            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13965        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13966
13967        // Create test items
13968        let item1 = cx.new(|cx| {
13969            TestItem::new(cx)
13970                .with_label("test1.txt")
13971                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13972        });
13973        let item1_id = item1.item_id();
13974
13975        let item2 = cx.new(|cx| {
13976            TestItem::new(cx)
13977                .with_label("test2.txt")
13978                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13979        });
13980
13981        // Add items to workspace
13982        workspace.update_in(cx, |workspace, window, cx| {
13983            workspace.add_item(
13984                pane.clone(),
13985                Box::new(item1.clone()),
13986                None,
13987                false,
13988                false,
13989                window,
13990                cx,
13991            );
13992            workspace.add_item(
13993                pane.clone(),
13994                Box::new(item2.clone()),
13995                None,
13996                false,
13997                false,
13998                window,
13999                cx,
14000            );
14001        });
14002
14003        // Activate item1 to ensure it gets navigation entries
14004        pane.update_in(cx, |pane, window, cx| {
14005            pane.activate_item(0, true, true, window, cx);
14006        });
14007
14008        // Switch to item2 and back to create navigation history
14009        pane.update_in(cx, |pane, window, cx| {
14010            pane.activate_item(1, true, true, window, cx);
14011        });
14012        cx.run_until_parked();
14013
14014        pane.update_in(cx, |pane, window, cx| {
14015            pane.activate_item(0, true, true, window, cx);
14016        });
14017        cx.run_until_parked();
14018
14019        // Simulate file deletion for item1
14020        item1.update(cx, |item, _| {
14021            item.set_has_deleted_file(true);
14022        });
14023
14024        // Emit UpdateTab event to trigger the close behavior
14025        item1.update(cx, |_, cx| {
14026            cx.emit(ItemEvent::UpdateTab);
14027        });
14028        cx.run_until_parked();
14029
14030        // Verify item1 was closed
14031        pane.read_with(cx, |pane, _| {
14032            assert_eq!(
14033                pane.items().count(),
14034                1,
14035                "Should have 1 item remaining after auto-close"
14036            );
14037        });
14038
14039        // Check navigation history after close
14040        let has_item = pane.read_with(cx, |pane, cx| {
14041            let mut has_item = false;
14042            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
14043                if entry.item.id() == item1_id {
14044                    has_item = true;
14045                }
14046            });
14047            has_item
14048        });
14049
14050        assert!(
14051            !has_item,
14052            "Navigation history should not contain closed item entries"
14053        );
14054    }
14055
14056    #[gpui::test]
14057    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
14058        cx: &mut TestAppContext,
14059    ) {
14060        init_test(cx);
14061
14062        let fs = FakeFs::new(cx.background_executor.clone());
14063        let project = Project::test(fs, [], cx).await;
14064        let (workspace, cx) =
14065            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14066        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14067
14068        let dirty_regular_buffer = cx.new(|cx| {
14069            TestItem::new(cx)
14070                .with_dirty(true)
14071                .with_label("1.txt")
14072                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
14073        });
14074        let dirty_regular_buffer_2 = cx.new(|cx| {
14075            TestItem::new(cx)
14076                .with_dirty(true)
14077                .with_label("2.txt")
14078                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
14079        });
14080        let clear_regular_buffer = cx.new(|cx| {
14081            TestItem::new(cx)
14082                .with_label("3.txt")
14083                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
14084        });
14085
14086        let dirty_multi_buffer = cx.new(|cx| {
14087            TestItem::new(cx)
14088                .with_dirty(true)
14089                .with_buffer_kind(ItemBufferKind::Multibuffer)
14090                .with_label("Fake Project Search")
14091                .with_project_items(&[
14092                    dirty_regular_buffer.read(cx).project_items[0].clone(),
14093                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
14094                    clear_regular_buffer.read(cx).project_items[0].clone(),
14095                ])
14096        });
14097        workspace.update_in(cx, |workspace, window, cx| {
14098            workspace.add_item(
14099                pane.clone(),
14100                Box::new(dirty_regular_buffer.clone()),
14101                None,
14102                false,
14103                false,
14104                window,
14105                cx,
14106            );
14107            workspace.add_item(
14108                pane.clone(),
14109                Box::new(dirty_regular_buffer_2.clone()),
14110                None,
14111                false,
14112                false,
14113                window,
14114                cx,
14115            );
14116            workspace.add_item(
14117                pane.clone(),
14118                Box::new(dirty_multi_buffer.clone()),
14119                None,
14120                false,
14121                false,
14122                window,
14123                cx,
14124            );
14125        });
14126
14127        pane.update_in(cx, |pane, window, cx| {
14128            pane.activate_item(2, true, true, window, cx);
14129            assert_eq!(
14130                pane.active_item().unwrap().item_id(),
14131                dirty_multi_buffer.item_id(),
14132                "Should select the multi buffer in the pane"
14133            );
14134        });
14135        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
14136            pane.close_active_item(
14137                &CloseActiveItem {
14138                    save_intent: None,
14139                    close_pinned: false,
14140                },
14141                window,
14142                cx,
14143            )
14144        });
14145        cx.background_executor.run_until_parked();
14146        assert!(
14147            !cx.has_pending_prompt(),
14148            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
14149        );
14150        close_multi_buffer_task
14151            .await
14152            .expect("Closing multi buffer failed");
14153        pane.update(cx, |pane, cx| {
14154            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
14155            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
14156            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
14157            assert_eq!(
14158                pane.items()
14159                    .map(|item| item.item_id())
14160                    .sorted()
14161                    .collect::<Vec<_>>(),
14162                vec![
14163                    dirty_regular_buffer.item_id(),
14164                    dirty_regular_buffer_2.item_id(),
14165                ],
14166                "Should have no multi buffer left in the pane"
14167            );
14168            assert!(dirty_regular_buffer.read(cx).is_dirty);
14169            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
14170        });
14171    }
14172
14173    #[gpui::test]
14174    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
14175        init_test(cx);
14176        let fs = FakeFs::new(cx.executor());
14177        let project = Project::test(fs, [], cx).await;
14178        let (multi_workspace, cx) =
14179            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14180        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14181
14182        // Add a new panel to the right dock, opening the dock and setting the
14183        // focus to the new panel.
14184        let panel = workspace.update_in(cx, |workspace, window, cx| {
14185            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14186            workspace.add_panel(panel.clone(), window, cx);
14187
14188            workspace
14189                .right_dock()
14190                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14191
14192            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14193
14194            panel
14195        });
14196
14197        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
14198        // panel to the next valid position which, in this case, is the left
14199        // dock.
14200        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14201        workspace.update(cx, |workspace, cx| {
14202            assert!(workspace.left_dock().read(cx).is_open());
14203            assert_eq!(panel.read(cx).position, DockPosition::Left);
14204        });
14205
14206        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
14207        // panel to the next valid position which, in this case, is the bottom
14208        // dock.
14209        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14210        workspace.update(cx, |workspace, cx| {
14211            assert!(workspace.bottom_dock().read(cx).is_open());
14212            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
14213        });
14214
14215        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
14216        // around moving the panel to its initial position, the right dock.
14217        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14218        workspace.update(cx, |workspace, cx| {
14219            assert!(workspace.right_dock().read(cx).is_open());
14220            assert_eq!(panel.read(cx).position, DockPosition::Right);
14221        });
14222
14223        // Remove focus from the panel, ensuring that, if the panel is not
14224        // focused, the `MoveFocusedPanelToNextPosition` action does not update
14225        // the panel's position, so the panel is still in the right dock.
14226        workspace.update_in(cx, |workspace, window, cx| {
14227            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14228        });
14229
14230        cx.dispatch_action(MoveFocusedPanelToNextPosition);
14231        workspace.update(cx, |workspace, cx| {
14232            assert!(workspace.right_dock().read(cx).is_open());
14233            assert_eq!(panel.read(cx).position, DockPosition::Right);
14234        });
14235    }
14236
14237    #[gpui::test]
14238    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
14239        init_test(cx);
14240
14241        let fs = FakeFs::new(cx.executor());
14242        let project = Project::test(fs, [], cx).await;
14243        let (workspace, cx) =
14244            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14245
14246        let item_1 = cx.new(|cx| {
14247            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14248        });
14249        workspace.update_in(cx, |workspace, window, cx| {
14250            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14251            workspace.move_item_to_pane_in_direction(
14252                &MoveItemToPaneInDirection {
14253                    direction: SplitDirection::Right,
14254                    focus: true,
14255                    clone: false,
14256                },
14257                window,
14258                cx,
14259            );
14260            workspace.move_item_to_pane_at_index(
14261                &MoveItemToPane {
14262                    destination: 3,
14263                    focus: true,
14264                    clone: false,
14265                },
14266                window,
14267                cx,
14268            );
14269
14270            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
14271            assert_eq!(
14272                pane_items_paths(&workspace.active_pane, cx),
14273                vec!["first.txt".to_string()],
14274                "Single item was not moved anywhere"
14275            );
14276        });
14277
14278        let item_2 = cx.new(|cx| {
14279            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
14280        });
14281        workspace.update_in(cx, |workspace, window, cx| {
14282            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
14283            assert_eq!(
14284                pane_items_paths(&workspace.panes[0], cx),
14285                vec!["first.txt".to_string(), "second.txt".to_string()],
14286            );
14287            workspace.move_item_to_pane_in_direction(
14288                &MoveItemToPaneInDirection {
14289                    direction: SplitDirection::Right,
14290                    focus: true,
14291                    clone: false,
14292                },
14293                window,
14294                cx,
14295            );
14296
14297            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
14298            assert_eq!(
14299                pane_items_paths(&workspace.panes[0], cx),
14300                vec!["first.txt".to_string()],
14301                "After moving, one item should be left in the original pane"
14302            );
14303            assert_eq!(
14304                pane_items_paths(&workspace.panes[1], cx),
14305                vec!["second.txt".to_string()],
14306                "New item should have been moved to the new pane"
14307            );
14308        });
14309
14310        let item_3 = cx.new(|cx| {
14311            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
14312        });
14313        workspace.update_in(cx, |workspace, window, cx| {
14314            let original_pane = workspace.panes[0].clone();
14315            workspace.set_active_pane(&original_pane, window, cx);
14316            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
14317            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
14318            assert_eq!(
14319                pane_items_paths(&workspace.active_pane, cx),
14320                vec!["first.txt".to_string(), "third.txt".to_string()],
14321                "New pane should be ready to move one item out"
14322            );
14323
14324            workspace.move_item_to_pane_at_index(
14325                &MoveItemToPane {
14326                    destination: 3,
14327                    focus: true,
14328                    clone: false,
14329                },
14330                window,
14331                cx,
14332            );
14333            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
14334            assert_eq!(
14335                pane_items_paths(&workspace.active_pane, cx),
14336                vec!["first.txt".to_string()],
14337                "After moving, one item should be left in the original pane"
14338            );
14339            assert_eq!(
14340                pane_items_paths(&workspace.panes[1], cx),
14341                vec!["second.txt".to_string()],
14342                "Previously created pane should be unchanged"
14343            );
14344            assert_eq!(
14345                pane_items_paths(&workspace.panes[2], cx),
14346                vec!["third.txt".to_string()],
14347                "New item should have been moved to the new pane"
14348            );
14349        });
14350    }
14351
14352    #[gpui::test]
14353    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
14354        init_test(cx);
14355
14356        let fs = FakeFs::new(cx.executor());
14357        let project = Project::test(fs, [], cx).await;
14358        let (workspace, cx) =
14359            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14360
14361        let item_1 = cx.new(|cx| {
14362            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14363        });
14364        workspace.update_in(cx, |workspace, window, cx| {
14365            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14366            workspace.move_item_to_pane_in_direction(
14367                &MoveItemToPaneInDirection {
14368                    direction: SplitDirection::Right,
14369                    focus: true,
14370                    clone: true,
14371                },
14372                window,
14373                cx,
14374            );
14375        });
14376        cx.run_until_parked();
14377        workspace.update_in(cx, |workspace, window, cx| {
14378            workspace.move_item_to_pane_at_index(
14379                &MoveItemToPane {
14380                    destination: 3,
14381                    focus: true,
14382                    clone: true,
14383                },
14384                window,
14385                cx,
14386            );
14387        });
14388        cx.run_until_parked();
14389
14390        workspace.update(cx, |workspace, cx| {
14391            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
14392            for pane in workspace.panes() {
14393                assert_eq!(
14394                    pane_items_paths(pane, cx),
14395                    vec!["first.txt".to_string()],
14396                    "Single item exists in all panes"
14397                );
14398            }
14399        });
14400
14401        // verify that the active pane has been updated after waiting for the
14402        // pane focus event to fire and resolve
14403        workspace.read_with(cx, |workspace, _app| {
14404            assert_eq!(
14405                workspace.active_pane(),
14406                &workspace.panes[2],
14407                "The third pane should be the active one: {:?}",
14408                workspace.panes
14409            );
14410        })
14411    }
14412
14413    #[gpui::test]
14414    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
14415        init_test(cx);
14416
14417        let fs = FakeFs::new(cx.executor());
14418        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
14419
14420        let project = Project::test(fs, ["root".as_ref()], cx).await;
14421        let (workspace, cx) =
14422            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14423
14424        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14425        // Add item to pane A with project path
14426        let item_a = cx.new(|cx| {
14427            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14428        });
14429        workspace.update_in(cx, |workspace, window, cx| {
14430            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14431        });
14432
14433        // Split to create pane B
14434        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14435            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14436        });
14437
14438        // Add item with SAME project path to pane B, and pin it
14439        let item_b = cx.new(|cx| {
14440            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14441        });
14442        pane_b.update_in(cx, |pane, window, cx| {
14443            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14444            pane.set_pinned_count(1);
14445        });
14446
14447        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14448        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14449
14450        // close_pinned: false should only close the unpinned copy
14451        workspace.update_in(cx, |workspace, window, cx| {
14452            workspace.close_item_in_all_panes(
14453                &CloseItemInAllPanes {
14454                    save_intent: Some(SaveIntent::Close),
14455                    close_pinned: false,
14456                },
14457                window,
14458                cx,
14459            )
14460        });
14461        cx.executor().run_until_parked();
14462
14463        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14464        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14465        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14466        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14467
14468        // Split again, seeing as closing the previous item also closed its
14469        // pane, so only pane remains, which does not allow us to properly test
14470        // that both items close when `close_pinned: true`.
14471        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14472            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14473        });
14474
14475        // Add an item with the same project path to pane C so that
14476        // close_item_in_all_panes can determine what to close across all panes
14477        // (it reads the active item from the active pane, and split_pane
14478        // creates an empty pane).
14479        let item_c = cx.new(|cx| {
14480            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14481        });
14482        pane_c.update_in(cx, |pane, window, cx| {
14483            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14484        });
14485
14486        // close_pinned: true should close the pinned copy too
14487        workspace.update_in(cx, |workspace, window, cx| {
14488            let panes_count = workspace.panes().len();
14489            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14490
14491            workspace.close_item_in_all_panes(
14492                &CloseItemInAllPanes {
14493                    save_intent: Some(SaveIntent::Close),
14494                    close_pinned: true,
14495                },
14496                window,
14497                cx,
14498            )
14499        });
14500        cx.executor().run_until_parked();
14501
14502        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14503        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14504        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14505        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14506    }
14507
14508    mod register_project_item_tests {
14509
14510        use super::*;
14511
14512        // View
14513        struct TestPngItemView {
14514            focus_handle: FocusHandle,
14515        }
14516        // Model
14517        struct TestPngItem {}
14518
14519        impl project::ProjectItem for TestPngItem {
14520            fn try_open(
14521                _project: &Entity<Project>,
14522                path: &ProjectPath,
14523                cx: &mut App,
14524            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14525                if path.path.extension().unwrap() == "png" {
14526                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14527                } else {
14528                    None
14529                }
14530            }
14531
14532            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14533                None
14534            }
14535
14536            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14537                None
14538            }
14539
14540            fn is_dirty(&self) -> bool {
14541                false
14542            }
14543        }
14544
14545        impl Item for TestPngItemView {
14546            type Event = ();
14547            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14548                "".into()
14549            }
14550        }
14551        impl EventEmitter<()> for TestPngItemView {}
14552        impl Focusable for TestPngItemView {
14553            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14554                self.focus_handle.clone()
14555            }
14556        }
14557
14558        impl Render for TestPngItemView {
14559            fn render(
14560                &mut self,
14561                _window: &mut Window,
14562                _cx: &mut Context<Self>,
14563            ) -> impl IntoElement {
14564                Empty
14565            }
14566        }
14567
14568        impl ProjectItem for TestPngItemView {
14569            type Item = TestPngItem;
14570
14571            fn for_project_item(
14572                _project: Entity<Project>,
14573                _pane: Option<&Pane>,
14574                _item: Entity<Self::Item>,
14575                _: &mut Window,
14576                cx: &mut Context<Self>,
14577            ) -> Self
14578            where
14579                Self: Sized,
14580            {
14581                Self {
14582                    focus_handle: cx.focus_handle(),
14583                }
14584            }
14585        }
14586
14587        // View
14588        struct TestIpynbItemView {
14589            focus_handle: FocusHandle,
14590        }
14591        // Model
14592        struct TestIpynbItem {}
14593
14594        impl project::ProjectItem for TestIpynbItem {
14595            fn try_open(
14596                _project: &Entity<Project>,
14597                path: &ProjectPath,
14598                cx: &mut App,
14599            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14600                if path.path.extension().unwrap() == "ipynb" {
14601                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14602                } else {
14603                    None
14604                }
14605            }
14606
14607            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14608                None
14609            }
14610
14611            fn project_path(&self, _: &App) -> Option<ProjectPath> {
14612                None
14613            }
14614
14615            fn is_dirty(&self) -> bool {
14616                false
14617            }
14618        }
14619
14620        impl Item for TestIpynbItemView {
14621            type Event = ();
14622            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14623                "".into()
14624            }
14625        }
14626        impl EventEmitter<()> for TestIpynbItemView {}
14627        impl Focusable for TestIpynbItemView {
14628            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14629                self.focus_handle.clone()
14630            }
14631        }
14632
14633        impl Render for TestIpynbItemView {
14634            fn render(
14635                &mut self,
14636                _window: &mut Window,
14637                _cx: &mut Context<Self>,
14638            ) -> impl IntoElement {
14639                Empty
14640            }
14641        }
14642
14643        impl ProjectItem for TestIpynbItemView {
14644            type Item = TestIpynbItem;
14645
14646            fn for_project_item(
14647                _project: Entity<Project>,
14648                _pane: Option<&Pane>,
14649                _item: Entity<Self::Item>,
14650                _: &mut Window,
14651                cx: &mut Context<Self>,
14652            ) -> Self
14653            where
14654                Self: Sized,
14655            {
14656                Self {
14657                    focus_handle: cx.focus_handle(),
14658                }
14659            }
14660        }
14661
14662        struct TestAlternatePngItemView {
14663            focus_handle: FocusHandle,
14664        }
14665
14666        impl Item for TestAlternatePngItemView {
14667            type Event = ();
14668            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14669                "".into()
14670            }
14671        }
14672
14673        impl EventEmitter<()> for TestAlternatePngItemView {}
14674        impl Focusable for TestAlternatePngItemView {
14675            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14676                self.focus_handle.clone()
14677            }
14678        }
14679
14680        impl Render for TestAlternatePngItemView {
14681            fn render(
14682                &mut self,
14683                _window: &mut Window,
14684                _cx: &mut Context<Self>,
14685            ) -> impl IntoElement {
14686                Empty
14687            }
14688        }
14689
14690        impl ProjectItem for TestAlternatePngItemView {
14691            type Item = TestPngItem;
14692
14693            fn for_project_item(
14694                _project: Entity<Project>,
14695                _pane: Option<&Pane>,
14696                _item: Entity<Self::Item>,
14697                _: &mut Window,
14698                cx: &mut Context<Self>,
14699            ) -> Self
14700            where
14701                Self: Sized,
14702            {
14703                Self {
14704                    focus_handle: cx.focus_handle(),
14705                }
14706            }
14707        }
14708
14709        #[gpui::test]
14710        async fn test_register_project_item(cx: &mut TestAppContext) {
14711            init_test(cx);
14712
14713            cx.update(|cx| {
14714                register_project_item::<TestPngItemView>(cx);
14715                register_project_item::<TestIpynbItemView>(cx);
14716            });
14717
14718            let fs = FakeFs::new(cx.executor());
14719            fs.insert_tree(
14720                "/root1",
14721                json!({
14722                    "one.png": "BINARYDATAHERE",
14723                    "two.ipynb": "{ totally a notebook }",
14724                    "three.txt": "editing text, sure why not?"
14725                }),
14726            )
14727            .await;
14728
14729            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14730            let (workspace, cx) =
14731                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14732
14733            let worktree_id = project.update(cx, |project, cx| {
14734                project.worktrees(cx).next().unwrap().read(cx).id()
14735            });
14736
14737            let handle = workspace
14738                .update_in(cx, |workspace, window, cx| {
14739                    let project_path = (worktree_id, rel_path("one.png"));
14740                    workspace.open_path(project_path, None, true, window, cx)
14741                })
14742                .await
14743                .unwrap();
14744
14745            // Now we can check if the handle we got back errored or not
14746            assert_eq!(
14747                handle.to_any_view().entity_type(),
14748                TypeId::of::<TestPngItemView>()
14749            );
14750
14751            let handle = workspace
14752                .update_in(cx, |workspace, window, cx| {
14753                    let project_path = (worktree_id, rel_path("two.ipynb"));
14754                    workspace.open_path(project_path, None, true, window, cx)
14755                })
14756                .await
14757                .unwrap();
14758
14759            assert_eq!(
14760                handle.to_any_view().entity_type(),
14761                TypeId::of::<TestIpynbItemView>()
14762            );
14763
14764            let handle = workspace
14765                .update_in(cx, |workspace, window, cx| {
14766                    let project_path = (worktree_id, rel_path("three.txt"));
14767                    workspace.open_path(project_path, None, true, window, cx)
14768                })
14769                .await;
14770            assert!(handle.is_err());
14771        }
14772
14773        #[gpui::test]
14774        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14775            init_test(cx);
14776
14777            cx.update(|cx| {
14778                register_project_item::<TestPngItemView>(cx);
14779                register_project_item::<TestAlternatePngItemView>(cx);
14780            });
14781
14782            let fs = FakeFs::new(cx.executor());
14783            fs.insert_tree(
14784                "/root1",
14785                json!({
14786                    "one.png": "BINARYDATAHERE",
14787                    "two.ipynb": "{ totally a notebook }",
14788                    "three.txt": "editing text, sure why not?"
14789                }),
14790            )
14791            .await;
14792            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14793            let (workspace, cx) =
14794                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14795            let worktree_id = project.update(cx, |project, cx| {
14796                project.worktrees(cx).next().unwrap().read(cx).id()
14797            });
14798
14799            let handle = workspace
14800                .update_in(cx, |workspace, window, cx| {
14801                    let project_path = (worktree_id, rel_path("one.png"));
14802                    workspace.open_path(project_path, None, true, window, cx)
14803                })
14804                .await
14805                .unwrap();
14806
14807            // This _must_ be the second item registered
14808            assert_eq!(
14809                handle.to_any_view().entity_type(),
14810                TypeId::of::<TestAlternatePngItemView>()
14811            );
14812
14813            let handle = workspace
14814                .update_in(cx, |workspace, window, cx| {
14815                    let project_path = (worktree_id, rel_path("three.txt"));
14816                    workspace.open_path(project_path, None, true, window, cx)
14817                })
14818                .await;
14819            assert!(handle.is_err());
14820        }
14821    }
14822
14823    #[gpui::test]
14824    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14825        init_test(cx);
14826
14827        let fs = FakeFs::new(cx.executor());
14828        let project = Project::test(fs, [], cx).await;
14829        let (workspace, _cx) =
14830            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14831
14832        // Test with status bar shown (default)
14833        workspace.read_with(cx, |workspace, cx| {
14834            let visible = workspace.status_bar_visible(cx);
14835            assert!(visible, "Status bar should be visible by default");
14836        });
14837
14838        // Test with status bar hidden
14839        cx.update_global(|store: &mut SettingsStore, cx| {
14840            store.update_user_settings(cx, |settings| {
14841                settings.status_bar.get_or_insert_default().show = Some(false);
14842            });
14843        });
14844
14845        workspace.read_with(cx, |workspace, cx| {
14846            let visible = workspace.status_bar_visible(cx);
14847            assert!(!visible, "Status bar should be hidden when show is false");
14848        });
14849
14850        // Test with status bar shown explicitly
14851        cx.update_global(|store: &mut SettingsStore, cx| {
14852            store.update_user_settings(cx, |settings| {
14853                settings.status_bar.get_or_insert_default().show = Some(true);
14854            });
14855        });
14856
14857        workspace.read_with(cx, |workspace, cx| {
14858            let visible = workspace.status_bar_visible(cx);
14859            assert!(visible, "Status bar should be visible when show is true");
14860        });
14861    }
14862
14863    #[gpui::test]
14864    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14865        init_test(cx);
14866
14867        let fs = FakeFs::new(cx.executor());
14868        let project = Project::test(fs, [], cx).await;
14869        let (multi_workspace, cx) =
14870            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14871        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14872        let panel = workspace.update_in(cx, |workspace, window, cx| {
14873            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14874            workspace.add_panel(panel.clone(), window, cx);
14875
14876            workspace
14877                .right_dock()
14878                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14879
14880            panel
14881        });
14882
14883        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14884        let item_a = cx.new(TestItem::new);
14885        let item_b = cx.new(TestItem::new);
14886        let item_a_id = item_a.entity_id();
14887        let item_b_id = item_b.entity_id();
14888
14889        pane.update_in(cx, |pane, window, cx| {
14890            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14891            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14892        });
14893
14894        pane.read_with(cx, |pane, _| {
14895            assert_eq!(pane.items_len(), 2);
14896            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14897        });
14898
14899        workspace.update_in(cx, |workspace, window, cx| {
14900            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14901        });
14902
14903        workspace.update_in(cx, |_, window, cx| {
14904            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14905        });
14906
14907        // Assert that the `pane::CloseActiveItem` action is handled at the
14908        // workspace level when one of the dock panels is focused and, in that
14909        // case, the center pane's active item is closed but the focus is not
14910        // moved.
14911        cx.dispatch_action(pane::CloseActiveItem::default());
14912        cx.run_until_parked();
14913
14914        pane.read_with(cx, |pane, _| {
14915            assert_eq!(pane.items_len(), 1);
14916            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14917        });
14918
14919        workspace.update_in(cx, |workspace, window, cx| {
14920            assert!(workspace.right_dock().read(cx).is_open());
14921            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14922        });
14923    }
14924
14925    #[gpui::test]
14926    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14927        init_test(cx);
14928        let fs = FakeFs::new(cx.executor());
14929
14930        let project_a = Project::test(fs.clone(), [], cx).await;
14931        let project_b = Project::test(fs, [], cx).await;
14932
14933        let multi_workspace_handle =
14934            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14935        cx.run_until_parked();
14936
14937        multi_workspace_handle
14938            .update(cx, |mw, _window, cx| {
14939                mw.open_sidebar(cx);
14940            })
14941            .unwrap();
14942
14943        let workspace_a = multi_workspace_handle
14944            .read_with(cx, |mw, _| mw.workspace().clone())
14945            .unwrap();
14946
14947        let _workspace_b = multi_workspace_handle
14948            .update(cx, |mw, window, cx| {
14949                mw.test_add_workspace(project_b, window, cx)
14950            })
14951            .unwrap();
14952
14953        // Switch to workspace A
14954        multi_workspace_handle
14955            .update(cx, |mw, window, cx| {
14956                let workspace = mw.workspaces().next().unwrap().clone();
14957                mw.activate(workspace, None, window, cx);
14958            })
14959            .unwrap();
14960
14961        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14962
14963        // Add a panel to workspace A's right dock and open the dock
14964        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14965            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14966            workspace.add_panel(panel.clone(), window, cx);
14967            workspace
14968                .right_dock()
14969                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14970            panel
14971        });
14972
14973        // Focus the panel through the workspace (matching existing test pattern)
14974        workspace_a.update_in(cx, |workspace, window, cx| {
14975            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14976        });
14977
14978        // Zoom the panel
14979        panel.update_in(cx, |panel, window, cx| {
14980            panel.set_zoomed(true, window, cx);
14981        });
14982
14983        // Verify the panel is zoomed and the dock is open
14984        workspace_a.update_in(cx, |workspace, window, cx| {
14985            assert!(
14986                workspace.right_dock().read(cx).is_open(),
14987                "dock should be open before switch"
14988            );
14989            assert!(
14990                panel.is_zoomed(window, cx),
14991                "panel should be zoomed before switch"
14992            );
14993            assert!(
14994                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14995                "panel should be focused before switch"
14996            );
14997        });
14998
14999        // Switch to workspace B
15000        multi_workspace_handle
15001            .update(cx, |mw, window, cx| {
15002                let workspace = mw.workspaces().nth(1).unwrap().clone();
15003                mw.activate(workspace, None, window, cx);
15004            })
15005            .unwrap();
15006        cx.run_until_parked();
15007
15008        // Switch back to workspace A
15009        multi_workspace_handle
15010            .update(cx, |mw, window, cx| {
15011                let workspace = mw.workspaces().next().unwrap().clone();
15012                mw.activate(workspace, None, window, cx);
15013            })
15014            .unwrap();
15015        cx.run_until_parked();
15016
15017        // Verify the panel is still zoomed and the dock is still open
15018        workspace_a.update_in(cx, |workspace, window, cx| {
15019            assert!(
15020                workspace.right_dock().read(cx).is_open(),
15021                "dock should still be open after switching back"
15022            );
15023            assert!(
15024                panel.is_zoomed(window, cx),
15025                "panel should still be zoomed after switching back"
15026            );
15027        });
15028    }
15029
15030    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
15031        pane.read(cx)
15032            .items()
15033            .flat_map(|item| {
15034                item.project_paths(cx)
15035                    .into_iter()
15036                    .map(|path| path.path.display(PathStyle::local()).into_owned())
15037            })
15038            .collect()
15039    }
15040
15041    pub fn init_test(cx: &mut TestAppContext) {
15042        cx.update(|cx| {
15043            let settings_store = SettingsStore::test(cx);
15044            cx.set_global(settings_store);
15045            cx.set_global(db::AppDatabase::test_new());
15046            theme_settings::init(theme::LoadThemes::JustBase, cx);
15047        });
15048    }
15049
15050    #[gpui::test]
15051    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
15052        use settings::{ThemeName, ThemeSelection};
15053        use theme::SystemAppearance;
15054        use zed_actions::theme::ToggleMode;
15055
15056        init_test(cx);
15057
15058        let fs = FakeFs::new(cx.executor());
15059        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
15060
15061        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
15062            .await;
15063
15064        // Build a test project and workspace view so the test can invoke
15065        // the workspace action handler the same way the UI would.
15066        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
15067        let (workspace, cx) =
15068            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
15069
15070        // Seed the settings file with a plain static light theme so the
15071        // first toggle always starts from a known persisted state.
15072        workspace.update_in(cx, |_workspace, _window, cx| {
15073            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
15074            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
15075                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
15076            });
15077        });
15078        cx.executor().advance_clock(Duration::from_millis(200));
15079        cx.run_until_parked();
15080
15081        // Confirm the initial persisted settings contain the static theme
15082        // we just wrote before any toggling happens.
15083        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
15084        assert!(settings_text.contains(r#""theme": "One Light""#));
15085
15086        // Toggle once. This should migrate the persisted theme settings
15087        // into light/dark slots and enable system mode.
15088        workspace.update_in(cx, |workspace, window, cx| {
15089            workspace.toggle_theme_mode(&ToggleMode, window, cx);
15090        });
15091        cx.executor().advance_clock(Duration::from_millis(200));
15092        cx.run_until_parked();
15093
15094        // 1. Static -> Dynamic
15095        // this assertion checks theme changed from static to dynamic.
15096        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
15097        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
15098        assert_eq!(
15099            parsed["theme"],
15100            serde_json::json!({
15101                "mode": "system",
15102                "light": "One Light",
15103                "dark": "One Dark"
15104            })
15105        );
15106
15107        // 2. Toggle again, suppose it will change the mode to light
15108        workspace.update_in(cx, |workspace, window, cx| {
15109            workspace.toggle_theme_mode(&ToggleMode, window, cx);
15110        });
15111        cx.executor().advance_clock(Duration::from_millis(200));
15112        cx.run_until_parked();
15113
15114        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
15115        assert!(settings_text.contains(r#""mode": "light""#));
15116    }
15117
15118    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
15119        let item = TestProjectItem::new(id, path, cx);
15120        item.update(cx, |item, _| {
15121            item.is_dirty = true;
15122        });
15123        item
15124    }
15125
15126    #[gpui::test]
15127    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
15128        cx: &mut gpui::TestAppContext,
15129    ) {
15130        init_test(cx);
15131        let fs = FakeFs::new(cx.executor());
15132
15133        let project = Project::test(fs, [], cx).await;
15134        let (workspace, cx) =
15135            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
15136
15137        let panel = workspace.update_in(cx, |workspace, window, cx| {
15138            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
15139            workspace.add_panel(panel.clone(), window, cx);
15140            workspace
15141                .right_dock()
15142                .update(cx, |dock, cx| dock.set_open(true, window, cx));
15143            panel
15144        });
15145
15146        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
15147        pane.update_in(cx, |pane, window, cx| {
15148            let item = cx.new(TestItem::new);
15149            pane.add_item(Box::new(item), true, true, None, window, cx);
15150        });
15151
15152        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
15153        // mirrors the real-world flow and avoids side effects from directly
15154        // focusing the panel while the center pane is active.
15155        workspace.update_in(cx, |workspace, window, cx| {
15156            workspace.toggle_panel_focus::<TestPanel>(window, cx);
15157        });
15158
15159        panel.update_in(cx, |panel, window, cx| {
15160            panel.set_zoomed(true, window, cx);
15161        });
15162
15163        workspace.update_in(cx, |workspace, window, cx| {
15164            assert!(workspace.right_dock().read(cx).is_open());
15165            assert!(panel.is_zoomed(window, cx));
15166            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
15167        });
15168
15169        // Simulate a spurious pane::Event::Focus on the center pane while the
15170        // panel still has focus. This mirrors what happens during macOS window
15171        // activation: the center pane fires a focus event even though actual
15172        // focus remains on the dock panel.
15173        pane.update_in(cx, |_, _, cx| {
15174            cx.emit(pane::Event::Focus);
15175        });
15176
15177        // The dock must remain open because the panel had focus at the time the
15178        // event was processed. Before the fix, dock_to_preserve was None for
15179        // panels that don't implement pane(), causing the dock to close.
15180        workspace.update_in(cx, |workspace, window, cx| {
15181            assert!(
15182                workspace.right_dock().read(cx).is_open(),
15183                "Dock should stay open when its zoomed panel (without pane()) still has focus"
15184            );
15185            assert!(panel.is_zoomed(window, cx));
15186        });
15187    }
15188
15189    #[gpui::test]
15190    async fn test_panels_stay_open_after_position_change_and_settings_update(
15191        cx: &mut gpui::TestAppContext,
15192    ) {
15193        init_test(cx);
15194        let fs = FakeFs::new(cx.executor());
15195        let project = Project::test(fs, [], cx).await;
15196        let (workspace, cx) =
15197            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
15198
15199        // Add two panels to the left dock and open it.
15200        let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
15201            let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
15202            let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
15203            workspace.add_panel(panel_a.clone(), window, cx);
15204            workspace.add_panel(panel_b.clone(), window, cx);
15205            workspace.left_dock().update(cx, |dock, cx| {
15206                dock.set_open(true, window, cx);
15207                dock.activate_panel(0, window, cx);
15208            });
15209            (panel_a, panel_b)
15210        });
15211
15212        workspace.update_in(cx, |workspace, _, cx| {
15213            assert!(workspace.left_dock().read(cx).is_open());
15214        });
15215
15216        // Simulate a feature flag changing default dock positions: both panels
15217        // move from Left to Right.
15218        workspace.update_in(cx, |_workspace, _window, cx| {
15219            panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
15220            panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
15221            cx.update_global::<SettingsStore, _>(|_, _| {});
15222        });
15223
15224        // Both panels should now be in the right dock.
15225        workspace.update_in(cx, |workspace, _, cx| {
15226            let right_dock = workspace.right_dock().read(cx);
15227            assert_eq!(right_dock.panels_len(), 2);
15228        });
15229
15230        // Open the right dock and activate panel_b (simulating the user
15231        // opening the panel after it moved).
15232        workspace.update_in(cx, |workspace, window, cx| {
15233            workspace.right_dock().update(cx, |dock, cx| {
15234                dock.set_open(true, window, cx);
15235                dock.activate_panel(1, window, cx);
15236            });
15237        });
15238
15239        // Now trigger another SettingsStore change
15240        workspace.update_in(cx, |_workspace, _window, cx| {
15241            cx.update_global::<SettingsStore, _>(|_, _| {});
15242        });
15243
15244        workspace.update_in(cx, |workspace, _, cx| {
15245            assert!(
15246                workspace.right_dock().read(cx).is_open(),
15247                "Right dock should still be open after a settings change"
15248            );
15249            assert_eq!(
15250                workspace.right_dock().read(cx).panels_len(),
15251                2,
15252                "Both panels should still be in the right dock"
15253            );
15254        });
15255    }
15256
15257    #[gpui::test]
15258    async fn test_most_recent_active_path_skips_read_only_paths(cx: &mut TestAppContext) {
15259        init_test(cx);
15260
15261        let fs = FakeFs::new(cx.executor());
15262        fs.insert_tree(
15263            path!("/project"),
15264            json!({
15265                "src": { "main.py": "" },
15266                ".venv": { "lib": { "dep.py": "" } },
15267            }),
15268        )
15269        .await;
15270
15271        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
15272        let (workspace, cx) =
15273            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
15274        let worktree_id = project.update(cx, |project, cx| {
15275            project.worktrees(cx).next().unwrap().read(cx).id()
15276        });
15277
15278        // Configure .venv as read-only
15279        workspace.update_in(cx, |_workspace, _window, cx| {
15280            cx.update_global::<SettingsStore, _>(|store, cx| {
15281                store
15282                    .set_user_settings(r#"{"read_only_files": ["**/.venv/**"]}"#, cx)
15283                    .ok();
15284            });
15285        });
15286
15287        let item_dep = cx.new(|cx| {
15288            TestItem::new(cx).with_project_items(&[TestProjectItem::new_in_worktree(
15289                1001,
15290                ".venv/lib/dep.py",
15291                worktree_id,
15292                cx,
15293            )])
15294        });
15295
15296        // dep.py is active but matches read_only_files → should be skipped
15297        workspace.update_in(cx, |workspace, window, cx| {
15298            workspace.add_item_to_active_pane(Box::new(item_dep.clone()), None, true, window, cx);
15299        });
15300        let path = workspace.read_with(cx, |workspace, cx| workspace.most_recent_active_path(cx));
15301        assert_eq!(path, None);
15302    }
15303}