workspace.rs

    1pub mod dock;
    2pub mod history_manager;
    3pub mod invalid_item_view;
    4pub mod item;
    5mod modal_layer;
    6mod multi_workspace;
    7pub mod notifications;
    8pub mod pane;
    9pub mod pane_group;
   10pub mod path_list {
   11    pub use util::path_list::{PathList, SerializedPathList};
   12}
   13mod persistence;
   14pub mod searchable;
   15mod security_modal;
   16pub mod shared_screen;
   17use db::smol::future::yield_now;
   18pub use shared_screen::SharedScreen;
   19pub mod focus_follows_mouse;
   20mod status_bar;
   21pub mod tasks;
   22mod theme_preview;
   23mod toast_layer;
   24mod toolbar;
   25pub mod welcome;
   26mod workspace_settings;
   27
   28pub use crate::notifications::NotificationFrame;
   29pub use dock::Panel;
   30pub use multi_workspace::{
   31    CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
   32    MultiWorkspaceEvent, NextWorkspace, PreviousWorkspace, Sidebar, SidebarHandle,
   33    ToggleWorkspaceSidebar,
   34};
   35pub use path_list::{PathList, SerializedPathList};
   36pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   37
   38use anyhow::{Context as _, Result, anyhow};
   39use client::{
   40    ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
   41    proto::{self, ErrorCode, PanelId, PeerId},
   42};
   43use collections::{HashMap, HashSet, hash_map};
   44use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   45use fs::Fs;
   46use futures::{
   47    Future, FutureExt, StreamExt,
   48    channel::{
   49        mpsc::{self, UnboundedReceiver, UnboundedSender},
   50        oneshot,
   51    },
   52    future::{Shared, try_join_all},
   53};
   54use gpui::{
   55    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
   56    Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   57    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   58    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   59    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   60    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   61};
   62pub use history_manager::*;
   63pub use item::{
   64    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   65    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   66};
   67use itertools::Itertools;
   68use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   69pub use modal_layer::*;
   70use node_runtime::NodeRuntime;
   71use notifications::{
   72    DetachAndPromptErr, Notifications, dismiss_app_notification,
   73    simple_message_notification::MessageNotification,
   74};
   75pub use pane::*;
   76pub use pane_group::{
   77    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   78    SplitDirection,
   79};
   80use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
   81pub use persistence::{
   82    WorkspaceDb, delete_unloaded_items,
   83    model::{
   84        DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
   85        SessionWorkspace,
   86    },
   87    read_serialized_multi_workspaces, resolve_worktree_workspaces,
   88};
   89use postage::stream::Stream;
   90use project::{
   91    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
   92    WorktreeSettings,
   93    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   94    project_settings::ProjectSettings,
   95    toolchain_store::ToolchainStoreEvent,
   96    trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
   97};
   98use remote::{
   99    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
  100    remote_client::ConnectionIdentifier,
  101};
  102use schemars::JsonSchema;
  103use serde::Deserialize;
  104use session::AppSession;
  105use settings::{
  106    CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
  107};
  108
  109use sqlez::{
  110    bindable::{Bind, Column, StaticColumnCount},
  111    statement::Statement,
  112};
  113use status_bar::StatusBar;
  114pub use status_bar::StatusItemView;
  115use std::{
  116    any::TypeId,
  117    borrow::Cow,
  118    cell::RefCell,
  119    cmp,
  120    collections::VecDeque,
  121    env,
  122    hash::Hash,
  123    path::{Path, PathBuf},
  124    process::ExitStatus,
  125    rc::Rc,
  126    sync::{
  127        Arc, LazyLock, Weak,
  128        atomic::{AtomicBool, AtomicUsize},
  129    },
  130    time::Duration,
  131};
  132use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
  133use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
  134pub use toolbar::{
  135    PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
  136};
  137pub use ui;
  138use ui::{Window, prelude::*};
  139use util::{
  140    ResultExt, TryFutureExt,
  141    paths::{PathStyle, SanitizedPath},
  142    rel_path::RelPath,
  143    serde::default_true,
  144};
  145use uuid::Uuid;
  146pub use workspace_settings::{
  147    AutosaveSetting, BottomDockLayout, FocusFollowsMouse, RestoreOnStartupBehavior,
  148    StatusBarSettings, TabBarSettings, WorkspaceSettings,
  149};
  150use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
  151
  152use crate::{item::ItemBufferKind, notifications::NotificationId};
  153use crate::{
  154    persistence::{
  155        SerializedAxis,
  156        model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
  157    },
  158    security_modal::SecurityModal,
  159};
  160
  161pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  162
  163static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  164    env::var("ZED_WINDOW_SIZE")
  165        .ok()
  166        .as_deref()
  167        .and_then(parse_pixel_size_env_var)
  168});
  169
  170static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  171    env::var("ZED_WINDOW_POSITION")
  172        .ok()
  173        .as_deref()
  174        .and_then(parse_pixel_position_env_var)
  175});
  176
  177pub trait TerminalProvider {
  178    fn spawn(
  179        &self,
  180        task: SpawnInTerminal,
  181        window: &mut Window,
  182        cx: &mut App,
  183    ) -> Task<Option<Result<ExitStatus>>>;
  184}
  185
  186pub trait DebuggerProvider {
  187    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  188    fn start_session(
  189        &self,
  190        definition: DebugScenario,
  191        task_context: SharedTaskContext,
  192        active_buffer: Option<Entity<Buffer>>,
  193        worktree_id: Option<WorktreeId>,
  194        window: &mut Window,
  195        cx: &mut App,
  196    );
  197
  198    fn spawn_task_or_modal(
  199        &self,
  200        workspace: &mut Workspace,
  201        action: &Spawn,
  202        window: &mut Window,
  203        cx: &mut Context<Workspace>,
  204    );
  205
  206    fn task_scheduled(&self, cx: &mut App);
  207    fn debug_scenario_scheduled(&self, cx: &mut App);
  208    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  209
  210    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  211}
  212
  213/// Opens a file or directory.
  214#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  215#[action(namespace = workspace)]
  216pub struct Open {
  217    /// When true, opens in a new window. When false, adds to the current
  218    /// window as a new workspace (multi-workspace).
  219    #[serde(default = "Open::default_create_new_window")]
  220    pub create_new_window: bool,
  221}
  222
  223impl Open {
  224    pub const DEFAULT: Self = Self {
  225        create_new_window: true,
  226    };
  227
  228    /// Used by `#[serde(default)]` on the `create_new_window` field so that
  229    /// the serde default and `Open::DEFAULT` stay in sync.
  230    fn default_create_new_window() -> bool {
  231        Self::DEFAULT.create_new_window
  232    }
  233}
  234
  235impl Default for Open {
  236    fn default() -> Self {
  237        Self::DEFAULT
  238    }
  239}
  240
  241actions!(
  242    workspace,
  243    [
  244        /// Activates the next pane in the workspace.
  245        ActivateNextPane,
  246        /// Activates the previous pane in the workspace.
  247        ActivatePreviousPane,
  248        /// Activates the last pane in the workspace.
  249        ActivateLastPane,
  250        /// Switches to the next window.
  251        ActivateNextWindow,
  252        /// Switches to the previous window.
  253        ActivatePreviousWindow,
  254        /// Adds a folder to the current project.
  255        AddFolderToProject,
  256        /// Clears all notifications.
  257        ClearAllNotifications,
  258        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  259        ClearNavigationHistory,
  260        /// Closes the active dock.
  261        CloseActiveDock,
  262        /// Closes all docks.
  263        CloseAllDocks,
  264        /// Toggles all docks.
  265        ToggleAllDocks,
  266        /// Closes the current window.
  267        CloseWindow,
  268        /// Closes the current project.
  269        CloseProject,
  270        /// Opens the feedback dialog.
  271        Feedback,
  272        /// Follows the next collaborator in the session.
  273        FollowNextCollaborator,
  274        /// Moves the focused panel to the next position.
  275        MoveFocusedPanelToNextPosition,
  276        /// Creates a new file.
  277        NewFile,
  278        /// Creates a new file in a vertical split.
  279        NewFileSplitVertical,
  280        /// Creates a new file in a horizontal split.
  281        NewFileSplitHorizontal,
  282        /// Opens a new search.
  283        NewSearch,
  284        /// Opens a new window.
  285        NewWindow,
  286        /// Opens multiple files.
  287        OpenFiles,
  288        /// Opens the current location in terminal.
  289        OpenInTerminal,
  290        /// Opens the component preview.
  291        OpenComponentPreview,
  292        /// Reloads the active item.
  293        ReloadActiveItem,
  294        /// Resets the active dock to its default size.
  295        ResetActiveDockSize,
  296        /// Resets all open docks to their default sizes.
  297        ResetOpenDocksSize,
  298        /// Reloads the application
  299        Reload,
  300        /// Saves the current file with a new name.
  301        SaveAs,
  302        /// Saves without formatting.
  303        SaveWithoutFormat,
  304        /// Shuts down all debug adapters.
  305        ShutdownDebugAdapters,
  306        /// Suppresses the current notification.
  307        SuppressNotification,
  308        /// Toggles the bottom dock.
  309        ToggleBottomDock,
  310        /// Toggles centered layout mode.
  311        ToggleCenteredLayout,
  312        /// Toggles edit prediction feature globally for all files.
  313        ToggleEditPrediction,
  314        /// Toggles the left dock.
  315        ToggleLeftDock,
  316        /// Toggles the right dock.
  317        ToggleRightDock,
  318        /// Toggles zoom on the active pane.
  319        ToggleZoom,
  320        /// Toggles read-only mode for the active item (if supported by that item).
  321        ToggleReadOnlyFile,
  322        /// Zooms in on the active pane.
  323        ZoomIn,
  324        /// Zooms out of the active pane.
  325        ZoomOut,
  326        /// If any worktrees are in restricted mode, shows a modal with possible actions.
  327        /// If the modal is shown already, closes it without trusting any worktree.
  328        ToggleWorktreeSecurity,
  329        /// Clears all trusted worktrees, placing them in restricted mode on next open.
  330        /// Requires restart to take effect on already opened projects.
  331        ClearTrustedWorktrees,
  332        /// Stops following a collaborator.
  333        Unfollow,
  334        /// Restores the banner.
  335        RestoreBanner,
  336        /// Toggles expansion of the selected item.
  337        ToggleExpandItem,
  338    ]
  339);
  340
  341/// Activates a specific pane by its index.
  342#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  343#[action(namespace = workspace)]
  344pub struct ActivatePane(pub usize);
  345
  346/// Moves an item to a specific pane by index.
  347#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  348#[action(namespace = workspace)]
  349#[serde(deny_unknown_fields)]
  350pub struct MoveItemToPane {
  351    #[serde(default = "default_1")]
  352    pub destination: usize,
  353    #[serde(default = "default_true")]
  354    pub focus: bool,
  355    #[serde(default)]
  356    pub clone: bool,
  357}
  358
  359fn default_1() -> usize {
  360    1
  361}
  362
  363/// Moves an item to a pane in the specified direction.
  364#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  365#[action(namespace = workspace)]
  366#[serde(deny_unknown_fields)]
  367pub struct MoveItemToPaneInDirection {
  368    #[serde(default = "default_right")]
  369    pub direction: SplitDirection,
  370    #[serde(default = "default_true")]
  371    pub focus: bool,
  372    #[serde(default)]
  373    pub clone: bool,
  374}
  375
  376/// Creates a new file in a split of the desired direction.
  377#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  378#[action(namespace = workspace)]
  379#[serde(deny_unknown_fields)]
  380pub struct NewFileSplit(pub SplitDirection);
  381
  382fn default_right() -> SplitDirection {
  383    SplitDirection::Right
  384}
  385
  386/// Saves all open files in the workspace.
  387#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  388#[action(namespace = workspace)]
  389#[serde(deny_unknown_fields)]
  390pub struct SaveAll {
  391    #[serde(default)]
  392    pub save_intent: Option<SaveIntent>,
  393}
  394
  395/// Saves the current file with the specified options.
  396#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  397#[action(namespace = workspace)]
  398#[serde(deny_unknown_fields)]
  399pub struct Save {
  400    #[serde(default)]
  401    pub save_intent: Option<SaveIntent>,
  402}
  403
  404/// Moves Focus to the central panes in the workspace.
  405#[derive(Clone, Debug, PartialEq, Eq, Action)]
  406#[action(namespace = workspace)]
  407pub struct FocusCenterPane;
  408
  409///  Closes all items and panes in the workspace.
  410#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  411#[action(namespace = workspace)]
  412#[serde(deny_unknown_fields)]
  413pub struct CloseAllItemsAndPanes {
  414    #[serde(default)]
  415    pub save_intent: Option<SaveIntent>,
  416}
  417
  418/// Closes all inactive tabs and panes in the workspace.
  419#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  420#[action(namespace = workspace)]
  421#[serde(deny_unknown_fields)]
  422pub struct CloseInactiveTabsAndPanes {
  423    #[serde(default)]
  424    pub save_intent: Option<SaveIntent>,
  425}
  426
  427/// Closes the active item across all panes.
  428#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  429#[action(namespace = workspace)]
  430#[serde(deny_unknown_fields)]
  431pub struct CloseItemInAllPanes {
  432    #[serde(default)]
  433    pub save_intent: Option<SaveIntent>,
  434    #[serde(default)]
  435    pub close_pinned: bool,
  436}
  437
  438/// Sends a sequence of keystrokes to the active element.
  439#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  440#[action(namespace = workspace)]
  441pub struct SendKeystrokes(pub String);
  442
  443actions!(
  444    project_symbols,
  445    [
  446        /// Toggles the project symbols search.
  447        #[action(name = "Toggle")]
  448        ToggleProjectSymbols
  449    ]
  450);
  451
  452/// Toggles the file finder interface.
  453#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  454#[action(namespace = file_finder, name = "Toggle")]
  455#[serde(deny_unknown_fields)]
  456pub struct ToggleFileFinder {
  457    #[serde(default)]
  458    pub separate_history: bool,
  459}
  460
  461/// Opens a new terminal in the center.
  462#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  463#[action(namespace = workspace)]
  464#[serde(deny_unknown_fields)]
  465pub struct NewCenterTerminal {
  466    /// If true, creates a local terminal even in remote projects.
  467    #[serde(default)]
  468    pub local: bool,
  469}
  470
  471/// Opens a new terminal.
  472#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  473#[action(namespace = workspace)]
  474#[serde(deny_unknown_fields)]
  475pub struct NewTerminal {
  476    /// If true, creates a local terminal even in remote projects.
  477    #[serde(default)]
  478    pub local: bool,
  479}
  480
  481/// Increases size of a currently focused dock by a given amount of pixels.
  482#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  483#[action(namespace = workspace)]
  484#[serde(deny_unknown_fields)]
  485pub struct IncreaseActiveDockSize {
  486    /// For 0px parameter, uses UI font size value.
  487    #[serde(default)]
  488    pub px: u32,
  489}
  490
  491/// Decreases size of a currently focused dock by a given amount of pixels.
  492#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  493#[action(namespace = workspace)]
  494#[serde(deny_unknown_fields)]
  495pub struct DecreaseActiveDockSize {
  496    /// For 0px parameter, uses UI font size value.
  497    #[serde(default)]
  498    pub px: u32,
  499}
  500
  501/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  502#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  503#[action(namespace = workspace)]
  504#[serde(deny_unknown_fields)]
  505pub struct IncreaseOpenDocksSize {
  506    /// For 0px parameter, uses UI font size value.
  507    #[serde(default)]
  508    pub px: u32,
  509}
  510
  511/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  512#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  513#[action(namespace = workspace)]
  514#[serde(deny_unknown_fields)]
  515pub struct DecreaseOpenDocksSize {
  516    /// For 0px parameter, uses UI font size value.
  517    #[serde(default)]
  518    pub px: u32,
  519}
  520
  521actions!(
  522    workspace,
  523    [
  524        /// Activates the pane to the left.
  525        ActivatePaneLeft,
  526        /// Activates the pane to the right.
  527        ActivatePaneRight,
  528        /// Activates the pane above.
  529        ActivatePaneUp,
  530        /// Activates the pane below.
  531        ActivatePaneDown,
  532        /// Swaps the current pane with the one to the left.
  533        SwapPaneLeft,
  534        /// Swaps the current pane with the one to the right.
  535        SwapPaneRight,
  536        /// Swaps the current pane with the one above.
  537        SwapPaneUp,
  538        /// Swaps the current pane with the one below.
  539        SwapPaneDown,
  540        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  541        SwapPaneAdjacent,
  542        /// Move the current pane to be at the far left.
  543        MovePaneLeft,
  544        /// Move the current pane to be at the far right.
  545        MovePaneRight,
  546        /// Move the current pane to be at the very top.
  547        MovePaneUp,
  548        /// Move the current pane to be at the very bottom.
  549        MovePaneDown,
  550    ]
  551);
  552
  553#[derive(PartialEq, Eq, Debug)]
  554pub enum CloseIntent {
  555    /// Quit the program entirely.
  556    Quit,
  557    /// Close a window.
  558    CloseWindow,
  559    /// Replace the workspace in an existing window.
  560    ReplaceWindow,
  561}
  562
  563#[derive(Clone)]
  564pub struct Toast {
  565    id: NotificationId,
  566    msg: Cow<'static, str>,
  567    autohide: bool,
  568    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  569}
  570
  571impl Toast {
  572    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  573        Toast {
  574            id,
  575            msg: msg.into(),
  576            on_click: None,
  577            autohide: false,
  578        }
  579    }
  580
  581    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  582    where
  583        M: Into<Cow<'static, str>>,
  584        F: Fn(&mut Window, &mut App) + 'static,
  585    {
  586        self.on_click = Some((message.into(), Arc::new(on_click)));
  587        self
  588    }
  589
  590    pub fn autohide(mut self) -> Self {
  591        self.autohide = true;
  592        self
  593    }
  594}
  595
  596impl PartialEq for Toast {
  597    fn eq(&self, other: &Self) -> bool {
  598        self.id == other.id
  599            && self.msg == other.msg
  600            && self.on_click.is_some() == other.on_click.is_some()
  601    }
  602}
  603
  604/// Opens a new terminal with the specified working directory.
  605#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  606#[action(namespace = workspace)]
  607#[serde(deny_unknown_fields)]
  608pub struct OpenTerminal {
  609    pub working_directory: PathBuf,
  610    /// If true, creates a local terminal even in remote projects.
  611    #[serde(default)]
  612    pub local: bool,
  613}
  614
  615#[derive(
  616    Clone,
  617    Copy,
  618    Debug,
  619    Default,
  620    Hash,
  621    PartialEq,
  622    Eq,
  623    PartialOrd,
  624    Ord,
  625    serde::Serialize,
  626    serde::Deserialize,
  627)]
  628pub struct WorkspaceId(i64);
  629
  630impl WorkspaceId {
  631    pub fn from_i64(value: i64) -> Self {
  632        Self(value)
  633    }
  634}
  635
  636impl StaticColumnCount for WorkspaceId {}
  637impl Bind for WorkspaceId {
  638    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  639        self.0.bind(statement, start_index)
  640    }
  641}
  642impl Column for WorkspaceId {
  643    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  644        i64::column(statement, start_index)
  645            .map(|(i, next_index)| (Self(i), next_index))
  646            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  647    }
  648}
  649impl From<WorkspaceId> for i64 {
  650    fn from(val: WorkspaceId) -> Self {
  651        val.0
  652    }
  653}
  654
  655fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
  656    if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
  657        workspace_window
  658            .update(cx, |multi_workspace, window, cx| {
  659                let workspace = multi_workspace.workspace().clone();
  660                workspace.update(cx, |workspace, cx| {
  661                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  662                });
  663            })
  664            .ok();
  665    } else {
  666        let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, true, cx);
  667        cx.spawn(async move |cx| {
  668            let OpenResult { window, .. } = task.await?;
  669            window.update(cx, |multi_workspace, window, cx| {
  670                window.activate_window();
  671                let workspace = multi_workspace.workspace().clone();
  672                workspace.update(cx, |workspace, cx| {
  673                    prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
  674                });
  675            })?;
  676            anyhow::Ok(())
  677        })
  678        .detach_and_log_err(cx);
  679    }
  680}
  681
  682pub fn prompt_for_open_path_and_open(
  683    workspace: &mut Workspace,
  684    app_state: Arc<AppState>,
  685    options: PathPromptOptions,
  686    create_new_window: bool,
  687    window: &mut Window,
  688    cx: &mut Context<Workspace>,
  689) {
  690    let paths = workspace.prompt_for_open_path(
  691        options,
  692        DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
  693        window,
  694        cx,
  695    );
  696    let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
  697    cx.spawn_in(window, async move |this, cx| {
  698        let Some(paths) = paths.await.log_err().flatten() else {
  699            return;
  700        };
  701        if !create_new_window {
  702            if let Some(handle) = multi_workspace_handle {
  703                if let Some(task) = handle
  704                    .update(cx, |multi_workspace, window, cx| {
  705                        multi_workspace.open_project(paths, window, cx)
  706                    })
  707                    .log_err()
  708                {
  709                    task.await.log_err();
  710                }
  711                return;
  712            }
  713        }
  714        if let Some(task) = this
  715            .update_in(cx, |this, window, cx| {
  716                this.open_workspace_for_paths(false, paths, window, cx)
  717            })
  718            .log_err()
  719        {
  720            task.await.log_err();
  721        }
  722    })
  723    .detach();
  724}
  725
  726pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  727    component::init();
  728    theme_preview::init(cx);
  729    toast_layer::init(cx);
  730    history_manager::init(app_state.fs.clone(), cx);
  731
  732    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  733        .on_action(|_: &Reload, cx| reload(cx))
  734        .on_action({
  735            let app_state = Arc::downgrade(&app_state);
  736            move |_: &Open, cx: &mut App| {
  737                if let Some(app_state) = app_state.upgrade() {
  738                    prompt_and_open_paths(
  739                        app_state,
  740                        PathPromptOptions {
  741                            files: true,
  742                            directories: true,
  743                            multiple: true,
  744                            prompt: None,
  745                        },
  746                        cx,
  747                    );
  748                }
  749            }
  750        })
  751        .on_action({
  752            let app_state = Arc::downgrade(&app_state);
  753            move |_: &OpenFiles, cx: &mut App| {
  754                let directories = cx.can_select_mixed_files_and_dirs();
  755                if let Some(app_state) = app_state.upgrade() {
  756                    prompt_and_open_paths(
  757                        app_state,
  758                        PathPromptOptions {
  759                            files: true,
  760                            directories,
  761                            multiple: true,
  762                            prompt: None,
  763                        },
  764                        cx,
  765                    );
  766                }
  767            }
  768        });
  769}
  770
  771type BuildProjectItemFn =
  772    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  773
  774type BuildProjectItemForPathFn =
  775    fn(
  776        &Entity<Project>,
  777        &ProjectPath,
  778        &mut Window,
  779        &mut App,
  780    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  781
  782#[derive(Clone, Default)]
  783struct ProjectItemRegistry {
  784    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  785    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  786}
  787
  788impl ProjectItemRegistry {
  789    fn register<T: ProjectItem>(&mut self) {
  790        self.build_project_item_fns_by_type.insert(
  791            TypeId::of::<T::Item>(),
  792            |item, project, pane, window, cx| {
  793                let item = item.downcast().unwrap();
  794                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  795                    as Box<dyn ItemHandle>
  796            },
  797        );
  798        self.build_project_item_for_path_fns
  799            .push(|project, project_path, window, cx| {
  800                let project_path = project_path.clone();
  801                let is_file = project
  802                    .read(cx)
  803                    .entry_for_path(&project_path, cx)
  804                    .is_some_and(|entry| entry.is_file());
  805                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  806                let is_local = project.read(cx).is_local();
  807                let project_item =
  808                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  809                let project = project.clone();
  810                Some(window.spawn(cx, async move |cx| {
  811                    match project_item.await.with_context(|| {
  812                        format!(
  813                            "opening project path {:?}",
  814                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  815                        )
  816                    }) {
  817                        Ok(project_item) => {
  818                            let project_item = project_item;
  819                            let project_entry_id: Option<ProjectEntryId> =
  820                                project_item.read_with(cx, project::ProjectItem::entry_id);
  821                            let build_workspace_item = Box::new(
  822                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  823                                    Box::new(cx.new(|cx| {
  824                                        T::for_project_item(
  825                                            project,
  826                                            Some(pane),
  827                                            project_item,
  828                                            window,
  829                                            cx,
  830                                        )
  831                                    })) as Box<dyn ItemHandle>
  832                                },
  833                            ) as Box<_>;
  834                            Ok((project_entry_id, build_workspace_item))
  835                        }
  836                        Err(e) => {
  837                            log::warn!("Failed to open a project item: {e:#}");
  838                            if e.error_code() == ErrorCode::Internal {
  839                                if let Some(abs_path) =
  840                                    entry_abs_path.as_deref().filter(|_| is_file)
  841                                {
  842                                    if let Some(broken_project_item_view) =
  843                                        cx.update(|window, cx| {
  844                                            T::for_broken_project_item(
  845                                                abs_path, is_local, &e, window, cx,
  846                                            )
  847                                        })?
  848                                    {
  849                                        let build_workspace_item = Box::new(
  850                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  851                                                cx.new(|_| broken_project_item_view).boxed_clone()
  852                                            },
  853                                        )
  854                                        as Box<_>;
  855                                        return Ok((None, build_workspace_item));
  856                                    }
  857                                }
  858                            }
  859                            Err(e)
  860                        }
  861                    }
  862                }))
  863            });
  864    }
  865
  866    fn open_path(
  867        &self,
  868        project: &Entity<Project>,
  869        path: &ProjectPath,
  870        window: &mut Window,
  871        cx: &mut App,
  872    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  873        let Some(open_project_item) = self
  874            .build_project_item_for_path_fns
  875            .iter()
  876            .rev()
  877            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  878        else {
  879            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  880        };
  881        open_project_item
  882    }
  883
  884    fn build_item<T: project::ProjectItem>(
  885        &self,
  886        item: Entity<T>,
  887        project: Entity<Project>,
  888        pane: Option<&Pane>,
  889        window: &mut Window,
  890        cx: &mut App,
  891    ) -> Option<Box<dyn ItemHandle>> {
  892        let build = self
  893            .build_project_item_fns_by_type
  894            .get(&TypeId::of::<T>())?;
  895        Some(build(item.into_any(), project, pane, window, cx))
  896    }
  897}
  898
  899type WorkspaceItemBuilder =
  900    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  901
  902impl Global for ProjectItemRegistry {}
  903
  904/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  905/// items will get a chance to open the file, starting from the project item that
  906/// was added last.
  907pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  908    cx.default_global::<ProjectItemRegistry>().register::<I>();
  909}
  910
  911#[derive(Default)]
  912pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  913
  914struct FollowableViewDescriptor {
  915    from_state_proto: fn(
  916        Entity<Workspace>,
  917        ViewId,
  918        &mut Option<proto::view::Variant>,
  919        &mut Window,
  920        &mut App,
  921    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  922    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  923}
  924
  925impl Global for FollowableViewRegistry {}
  926
  927impl FollowableViewRegistry {
  928    pub fn register<I: FollowableItem>(cx: &mut App) {
  929        cx.default_global::<Self>().0.insert(
  930            TypeId::of::<I>(),
  931            FollowableViewDescriptor {
  932                from_state_proto: |workspace, id, state, window, cx| {
  933                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  934                        cx.foreground_executor()
  935                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  936                    })
  937                },
  938                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  939            },
  940        );
  941    }
  942
  943    pub fn from_state_proto(
  944        workspace: Entity<Workspace>,
  945        view_id: ViewId,
  946        mut state: Option<proto::view::Variant>,
  947        window: &mut Window,
  948        cx: &mut App,
  949    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  950        cx.update_default_global(|this: &mut Self, cx| {
  951            this.0.values().find_map(|descriptor| {
  952                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  953            })
  954        })
  955    }
  956
  957    pub fn to_followable_view(
  958        view: impl Into<AnyView>,
  959        cx: &App,
  960    ) -> Option<Box<dyn FollowableItemHandle>> {
  961        let this = cx.try_global::<Self>()?;
  962        let view = view.into();
  963        let descriptor = this.0.get(&view.entity_type())?;
  964        Some((descriptor.to_followable_view)(&view))
  965    }
  966}
  967
  968#[derive(Copy, Clone)]
  969struct SerializableItemDescriptor {
  970    deserialize: fn(
  971        Entity<Project>,
  972        WeakEntity<Workspace>,
  973        WorkspaceId,
  974        ItemId,
  975        &mut Window,
  976        &mut Context<Pane>,
  977    ) -> Task<Result<Box<dyn ItemHandle>>>,
  978    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  979    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  980}
  981
  982#[derive(Default)]
  983struct SerializableItemRegistry {
  984    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  985    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  986}
  987
  988impl Global for SerializableItemRegistry {}
  989
  990impl SerializableItemRegistry {
  991    fn deserialize(
  992        item_kind: &str,
  993        project: Entity<Project>,
  994        workspace: WeakEntity<Workspace>,
  995        workspace_id: WorkspaceId,
  996        item_item: ItemId,
  997        window: &mut Window,
  998        cx: &mut Context<Pane>,
  999    ) -> Task<Result<Box<dyn ItemHandle>>> {
 1000        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1001            return Task::ready(Err(anyhow!(
 1002                "cannot deserialize {}, descriptor not found",
 1003                item_kind
 1004            )));
 1005        };
 1006
 1007        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
 1008    }
 1009
 1010    fn cleanup(
 1011        item_kind: &str,
 1012        workspace_id: WorkspaceId,
 1013        loaded_items: Vec<ItemId>,
 1014        window: &mut Window,
 1015        cx: &mut App,
 1016    ) -> Task<Result<()>> {
 1017        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
 1018            return Task::ready(Err(anyhow!(
 1019                "cannot cleanup {}, descriptor not found",
 1020                item_kind
 1021            )));
 1022        };
 1023
 1024        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
 1025    }
 1026
 1027    fn view_to_serializable_item_handle(
 1028        view: AnyView,
 1029        cx: &App,
 1030    ) -> Option<Box<dyn SerializableItemHandle>> {
 1031        let this = cx.try_global::<Self>()?;
 1032        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
 1033        Some((descriptor.view_to_serializable_item)(view))
 1034    }
 1035
 1036    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
 1037        let this = cx.try_global::<Self>()?;
 1038        this.descriptors_by_kind.get(item_kind).copied()
 1039    }
 1040}
 1041
 1042pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
 1043    let serialized_item_kind = I::serialized_item_kind();
 1044
 1045    let registry = cx.default_global::<SerializableItemRegistry>();
 1046    let descriptor = SerializableItemDescriptor {
 1047        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
 1048            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
 1049            cx.foreground_executor()
 1050                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 1051        },
 1052        cleanup: |workspace_id, loaded_items, window, cx| {
 1053            I::cleanup(workspace_id, loaded_items, window, cx)
 1054        },
 1055        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
 1056    };
 1057    registry
 1058        .descriptors_by_kind
 1059        .insert(Arc::from(serialized_item_kind), descriptor);
 1060    registry
 1061        .descriptors_by_type
 1062        .insert(TypeId::of::<I>(), descriptor);
 1063}
 1064
 1065pub struct AppState {
 1066    pub languages: Arc<LanguageRegistry>,
 1067    pub client: Arc<Client>,
 1068    pub user_store: Entity<UserStore>,
 1069    pub workspace_store: Entity<WorkspaceStore>,
 1070    pub fs: Arc<dyn fs::Fs>,
 1071    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
 1072    pub node_runtime: NodeRuntime,
 1073    pub session: Entity<AppSession>,
 1074}
 1075
 1076struct GlobalAppState(Weak<AppState>);
 1077
 1078impl Global for GlobalAppState {}
 1079
 1080pub struct WorkspaceStore {
 1081    workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
 1082    client: Arc<Client>,
 1083    _subscriptions: Vec<client::Subscription>,
 1084}
 1085
 1086#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
 1087pub enum CollaboratorId {
 1088    PeerId(PeerId),
 1089    Agent,
 1090}
 1091
 1092impl From<PeerId> for CollaboratorId {
 1093    fn from(peer_id: PeerId) -> Self {
 1094        CollaboratorId::PeerId(peer_id)
 1095    }
 1096}
 1097
 1098impl From<&PeerId> for CollaboratorId {
 1099    fn from(peer_id: &PeerId) -> Self {
 1100        CollaboratorId::PeerId(*peer_id)
 1101    }
 1102}
 1103
 1104#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 1105struct Follower {
 1106    project_id: Option<u64>,
 1107    peer_id: PeerId,
 1108}
 1109
 1110impl AppState {
 1111    #[track_caller]
 1112    pub fn global(cx: &App) -> Weak<Self> {
 1113        cx.global::<GlobalAppState>().0.clone()
 1114    }
 1115    pub fn try_global(cx: &App) -> Option<Weak<Self>> {
 1116        cx.try_global::<GlobalAppState>()
 1117            .map(|state| state.0.clone())
 1118    }
 1119    pub fn set_global(state: Weak<AppState>, cx: &mut App) {
 1120        cx.set_global(GlobalAppState(state));
 1121    }
 1122
 1123    #[cfg(any(test, feature = "test-support"))]
 1124    pub fn test(cx: &mut App) -> Arc<Self> {
 1125        use fs::Fs;
 1126        use node_runtime::NodeRuntime;
 1127        use session::Session;
 1128        use settings::SettingsStore;
 1129
 1130        if !cx.has_global::<SettingsStore>() {
 1131            let settings_store = SettingsStore::test(cx);
 1132            cx.set_global(settings_store);
 1133        }
 1134
 1135        let fs = fs::FakeFs::new(cx.background_executor().clone());
 1136        <dyn Fs>::set_global(fs.clone(), cx);
 1137        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
 1138        let clock = Arc::new(clock::FakeSystemClock::new());
 1139        let http_client = http_client::FakeHttpClient::with_404_response();
 1140        let client = Client::new(clock, http_client, cx);
 1141        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 1142        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 1143        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 1144
 1145        theme::init(theme::LoadThemes::JustBase, cx);
 1146        client::init(&client, cx);
 1147
 1148        Arc::new(Self {
 1149            client,
 1150            fs,
 1151            languages,
 1152            user_store,
 1153            workspace_store,
 1154            node_runtime: NodeRuntime::unavailable(),
 1155            build_window_options: |_, _| Default::default(),
 1156            session,
 1157        })
 1158    }
 1159}
 1160
 1161struct DelayedDebouncedEditAction {
 1162    task: Option<Task<()>>,
 1163    cancel_channel: Option<oneshot::Sender<()>>,
 1164}
 1165
 1166impl DelayedDebouncedEditAction {
 1167    fn new() -> DelayedDebouncedEditAction {
 1168        DelayedDebouncedEditAction {
 1169            task: None,
 1170            cancel_channel: None,
 1171        }
 1172    }
 1173
 1174    fn fire_new<F>(
 1175        &mut self,
 1176        delay: Duration,
 1177        window: &mut Window,
 1178        cx: &mut Context<Workspace>,
 1179        func: F,
 1180    ) where
 1181        F: 'static
 1182            + Send
 1183            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1184    {
 1185        if let Some(channel) = self.cancel_channel.take() {
 1186            _ = channel.send(());
 1187        }
 1188
 1189        let (sender, mut receiver) = oneshot::channel::<()>();
 1190        self.cancel_channel = Some(sender);
 1191
 1192        let previous_task = self.task.take();
 1193        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1194            let mut timer = cx.background_executor().timer(delay).fuse();
 1195            if let Some(previous_task) = previous_task {
 1196                previous_task.await;
 1197            }
 1198
 1199            futures::select_biased! {
 1200                _ = receiver => return,
 1201                    _ = timer => {}
 1202            }
 1203
 1204            if let Some(result) = workspace
 1205                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1206                .log_err()
 1207            {
 1208                result.await.log_err();
 1209            }
 1210        }));
 1211    }
 1212}
 1213
 1214pub enum Event {
 1215    PaneAdded(Entity<Pane>),
 1216    PaneRemoved,
 1217    ItemAdded {
 1218        item: Box<dyn ItemHandle>,
 1219    },
 1220    ActiveItemChanged,
 1221    ItemRemoved {
 1222        item_id: EntityId,
 1223    },
 1224    UserSavedItem {
 1225        pane: WeakEntity<Pane>,
 1226        item: Box<dyn WeakItemHandle>,
 1227        save_intent: SaveIntent,
 1228    },
 1229    ContactRequestedJoin(u64),
 1230    WorkspaceCreated(WeakEntity<Workspace>),
 1231    OpenBundledFile {
 1232        text: Cow<'static, str>,
 1233        title: &'static str,
 1234        language: &'static str,
 1235    },
 1236    ZoomChanged,
 1237    ModalOpened,
 1238    Activate,
 1239    PanelAdded(AnyView),
 1240}
 1241
 1242#[derive(Debug, Clone)]
 1243pub enum OpenVisible {
 1244    All,
 1245    None,
 1246    OnlyFiles,
 1247    OnlyDirectories,
 1248}
 1249
 1250enum WorkspaceLocation {
 1251    // Valid local paths or SSH project to serialize
 1252    Location(SerializedWorkspaceLocation, PathList),
 1253    // No valid location found hence clear session id
 1254    DetachFromSession,
 1255    // No valid location found to serialize
 1256    None,
 1257}
 1258
 1259type PromptForNewPath = Box<
 1260    dyn Fn(
 1261        &mut Workspace,
 1262        DirectoryLister,
 1263        Option<String>,
 1264        &mut Window,
 1265        &mut Context<Workspace>,
 1266    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1267>;
 1268
 1269type PromptForOpenPath = Box<
 1270    dyn Fn(
 1271        &mut Workspace,
 1272        DirectoryLister,
 1273        &mut Window,
 1274        &mut Context<Workspace>,
 1275    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1276>;
 1277
 1278#[derive(Default)]
 1279struct DispatchingKeystrokes {
 1280    dispatched: HashSet<Vec<Keystroke>>,
 1281    queue: VecDeque<Keystroke>,
 1282    task: Option<Shared<Task<()>>>,
 1283}
 1284
 1285/// Collects everything project-related for a certain window opened.
 1286/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1287///
 1288/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1289/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1290/// that can be used to register a global action to be triggered from any place in the window.
 1291pub struct Workspace {
 1292    weak_self: WeakEntity<Self>,
 1293    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1294    zoomed: Option<AnyWeakView>,
 1295    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1296    zoomed_position: Option<DockPosition>,
 1297    center: PaneGroup,
 1298    left_dock: Entity<Dock>,
 1299    bottom_dock: Entity<Dock>,
 1300    right_dock: Entity<Dock>,
 1301    panes: Vec<Entity<Pane>>,
 1302    active_worktree_override: Option<WorktreeId>,
 1303    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1304    active_pane: Entity<Pane>,
 1305    last_active_center_pane: Option<WeakEntity<Pane>>,
 1306    last_active_view_id: Option<proto::ViewId>,
 1307    status_bar: Entity<StatusBar>,
 1308    pub(crate) modal_layer: Entity<ModalLayer>,
 1309    toast_layer: Entity<ToastLayer>,
 1310    titlebar_item: Option<AnyView>,
 1311    notifications: Notifications,
 1312    suppressed_notifications: HashSet<NotificationId>,
 1313    project: Entity<Project>,
 1314    follower_states: HashMap<CollaboratorId, FollowerState>,
 1315    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1316    window_edited: bool,
 1317    last_window_title: Option<String>,
 1318    dirty_items: HashMap<EntityId, Subscription>,
 1319    active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
 1320    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1321    database_id: Option<WorkspaceId>,
 1322    app_state: Arc<AppState>,
 1323    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1324    _subscriptions: Vec<Subscription>,
 1325    _apply_leader_updates: Task<Result<()>>,
 1326    _observe_current_user: Task<Result<()>>,
 1327    _schedule_serialize_workspace: Option<Task<()>>,
 1328    _serialize_workspace_task: Option<Task<()>>,
 1329    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1330    pane_history_timestamp: Arc<AtomicUsize>,
 1331    bounds: Bounds<Pixels>,
 1332    pub centered_layout: bool,
 1333    bounds_save_task_queued: Option<Task<()>>,
 1334    on_prompt_for_new_path: Option<PromptForNewPath>,
 1335    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1336    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1337    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1338    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1339    _items_serializer: Task<Result<()>>,
 1340    session_id: Option<String>,
 1341    scheduled_tasks: Vec<Task<()>>,
 1342    last_open_dock_positions: Vec<DockPosition>,
 1343    removing: bool,
 1344    _panels_task: Option<Task<Result<()>>>,
 1345    sidebar_focus_handle: Option<FocusHandle>,
 1346}
 1347
 1348impl EventEmitter<Event> for Workspace {}
 1349
 1350#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1351pub struct ViewId {
 1352    pub creator: CollaboratorId,
 1353    pub id: u64,
 1354}
 1355
 1356pub struct FollowerState {
 1357    center_pane: Entity<Pane>,
 1358    dock_pane: Option<Entity<Pane>>,
 1359    active_view_id: Option<ViewId>,
 1360    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1361}
 1362
 1363struct FollowerView {
 1364    view: Box<dyn FollowableItemHandle>,
 1365    location: Option<proto::PanelId>,
 1366}
 1367
 1368impl Workspace {
 1369    pub fn new(
 1370        workspace_id: Option<WorkspaceId>,
 1371        project: Entity<Project>,
 1372        app_state: Arc<AppState>,
 1373        window: &mut Window,
 1374        cx: &mut Context<Self>,
 1375    ) -> Self {
 1376        if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1377            cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
 1378                if let TrustedWorktreesEvent::Trusted(..) = e {
 1379                    // Do not persist auto trusted worktrees
 1380                    if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1381                        worktrees_store.update(cx, |worktrees_store, cx| {
 1382                            worktrees_store.schedule_serialization(
 1383                                cx,
 1384                                |new_trusted_worktrees, cx| {
 1385                                    let timeout =
 1386                                        cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
 1387                                    let db = WorkspaceDb::global(cx);
 1388                                    cx.background_spawn(async move {
 1389                                        timeout.await;
 1390                                        db.save_trusted_worktrees(new_trusted_worktrees)
 1391                                            .await
 1392                                            .log_err();
 1393                                    })
 1394                                },
 1395                            )
 1396                        });
 1397                    }
 1398                }
 1399            })
 1400            .detach();
 1401
 1402            cx.observe_global::<SettingsStore>(|_, cx| {
 1403                if ProjectSettings::get_global(cx).session.trust_all_worktrees {
 1404                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 1405                        trusted_worktrees.update(cx, |trusted_worktrees, cx| {
 1406                            trusted_worktrees.auto_trust_all(cx);
 1407                        })
 1408                    }
 1409                }
 1410            })
 1411            .detach();
 1412        }
 1413
 1414        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1415            match event {
 1416                project::Event::RemoteIdChanged(_) => {
 1417                    this.update_window_title(window, cx);
 1418                }
 1419
 1420                project::Event::CollaboratorLeft(peer_id) => {
 1421                    this.collaborator_left(*peer_id, window, cx);
 1422                }
 1423
 1424                &project::Event::WorktreeRemoved(_) => {
 1425                    this.update_window_title(window, cx);
 1426                    this.serialize_workspace(window, cx);
 1427                    this.update_history(cx);
 1428                }
 1429
 1430                &project::Event::WorktreeAdded(id) => {
 1431                    this.update_window_title(window, cx);
 1432                    if this
 1433                        .project()
 1434                        .read(cx)
 1435                        .worktree_for_id(id, cx)
 1436                        .is_some_and(|wt| wt.read(cx).is_visible())
 1437                    {
 1438                        this.serialize_workspace(window, cx);
 1439                        this.update_history(cx);
 1440                    }
 1441                }
 1442                project::Event::WorktreeUpdatedEntries(..) => {
 1443                    this.update_window_title(window, cx);
 1444                    this.serialize_workspace(window, cx);
 1445                }
 1446
 1447                project::Event::DisconnectedFromHost => {
 1448                    this.update_window_edited(window, cx);
 1449                    let leaders_to_unfollow =
 1450                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1451                    for leader_id in leaders_to_unfollow {
 1452                        this.unfollow(leader_id, window, cx);
 1453                    }
 1454                }
 1455
 1456                project::Event::DisconnectedFromRemote {
 1457                    server_not_running: _,
 1458                } => {
 1459                    this.update_window_edited(window, cx);
 1460                }
 1461
 1462                project::Event::Closed => {
 1463                    window.remove_window();
 1464                }
 1465
 1466                project::Event::DeletedEntry(_, entry_id) => {
 1467                    for pane in this.panes.iter() {
 1468                        pane.update(cx, |pane, cx| {
 1469                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1470                        });
 1471                    }
 1472                }
 1473
 1474                project::Event::Toast {
 1475                    notification_id,
 1476                    message,
 1477                    link,
 1478                } => this.show_notification(
 1479                    NotificationId::named(notification_id.clone()),
 1480                    cx,
 1481                    |cx| {
 1482                        let mut notification = MessageNotification::new(message.clone(), cx);
 1483                        if let Some(link) = link {
 1484                            notification = notification
 1485                                .more_info_message(link.label)
 1486                                .more_info_url(link.url);
 1487                        }
 1488
 1489                        cx.new(|_| notification)
 1490                    },
 1491                ),
 1492
 1493                project::Event::HideToast { notification_id } => {
 1494                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1495                }
 1496
 1497                project::Event::LanguageServerPrompt(request) => {
 1498                    struct LanguageServerPrompt;
 1499
 1500                    this.show_notification(
 1501                        NotificationId::composite::<LanguageServerPrompt>(request.id),
 1502                        cx,
 1503                        |cx| {
 1504                            cx.new(|cx| {
 1505                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1506                            })
 1507                        },
 1508                    );
 1509                }
 1510
 1511                project::Event::AgentLocationChanged => {
 1512                    this.handle_agent_location_changed(window, cx)
 1513                }
 1514
 1515                _ => {}
 1516            }
 1517            cx.notify()
 1518        })
 1519        .detach();
 1520
 1521        cx.subscribe_in(
 1522            &project.read(cx).breakpoint_store(),
 1523            window,
 1524            |workspace, _, event, window, cx| match event {
 1525                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1526                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1527                    workspace.serialize_workspace(window, cx);
 1528                }
 1529                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1530            },
 1531        )
 1532        .detach();
 1533        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1534            cx.subscribe_in(
 1535                &toolchain_store,
 1536                window,
 1537                |workspace, _, event, window, cx| match event {
 1538                    ToolchainStoreEvent::CustomToolchainsModified => {
 1539                        workspace.serialize_workspace(window, cx);
 1540                    }
 1541                    _ => {}
 1542                },
 1543            )
 1544            .detach();
 1545        }
 1546
 1547        cx.on_focus_lost(window, |this, window, cx| {
 1548            let focus_handle = this.focus_handle(cx);
 1549            window.focus(&focus_handle, cx);
 1550        })
 1551        .detach();
 1552
 1553        let weak_handle = cx.entity().downgrade();
 1554        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1555
 1556        let center_pane = cx.new(|cx| {
 1557            let mut center_pane = Pane::new(
 1558                weak_handle.clone(),
 1559                project.clone(),
 1560                pane_history_timestamp.clone(),
 1561                None,
 1562                NewFile.boxed_clone(),
 1563                true,
 1564                window,
 1565                cx,
 1566            );
 1567            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1568            center_pane.set_should_display_welcome_page(true);
 1569            center_pane
 1570        });
 1571        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1572            .detach();
 1573
 1574        window.focus(&center_pane.focus_handle(cx), cx);
 1575
 1576        cx.emit(Event::PaneAdded(center_pane.clone()));
 1577
 1578        let any_window_handle = window.window_handle();
 1579        app_state.workspace_store.update(cx, |store, _| {
 1580            store
 1581                .workspaces
 1582                .insert((any_window_handle, weak_handle.clone()));
 1583        });
 1584
 1585        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1586        let mut connection_status = app_state.client.status();
 1587        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1588            current_user.next().await;
 1589            connection_status.next().await;
 1590            let mut stream =
 1591                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1592
 1593            while stream.recv().await.is_some() {
 1594                this.update(cx, |_, cx| cx.notify())?;
 1595            }
 1596            anyhow::Ok(())
 1597        });
 1598
 1599        // All leader updates are enqueued and then processed in a single task, so
 1600        // that each asynchronous operation can be run in order.
 1601        let (leader_updates_tx, mut leader_updates_rx) =
 1602            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1603        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1604            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1605                Self::process_leader_update(&this, leader_id, update, cx)
 1606                    .await
 1607                    .log_err();
 1608            }
 1609
 1610            Ok(())
 1611        });
 1612
 1613        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1614        let modal_layer = cx.new(|_| ModalLayer::new());
 1615        let toast_layer = cx.new(|_| ToastLayer::new());
 1616        cx.subscribe(
 1617            &modal_layer,
 1618            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1619                cx.emit(Event::ModalOpened);
 1620            },
 1621        )
 1622        .detach();
 1623
 1624        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1625        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1626        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1627        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1628        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1629        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1630        let status_bar = cx.new(|cx| {
 1631            let mut status_bar = StatusBar::new(&center_pane.clone(), window, cx);
 1632            status_bar.add_left_item(left_dock_buttons, window, cx);
 1633            status_bar.add_right_item(right_dock_buttons, window, cx);
 1634            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1635            status_bar
 1636        });
 1637
 1638        let session_id = app_state.session.read(cx).id().to_owned();
 1639
 1640        let mut active_call = None;
 1641        if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
 1642            let subscriptions =
 1643                vec![
 1644                    call.0
 1645                        .subscribe(window, cx, Box::new(Self::on_active_call_event)),
 1646                ];
 1647            active_call = Some((call, subscriptions));
 1648        }
 1649
 1650        let (serializable_items_tx, serializable_items_rx) =
 1651            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1652        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1653            Self::serialize_items(&this, serializable_items_rx, cx).await
 1654        });
 1655
 1656        let subscriptions = vec![
 1657            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1658            cx.observe_window_bounds(window, move |this, window, cx| {
 1659                if this.bounds_save_task_queued.is_some() {
 1660                    return;
 1661                }
 1662                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1663                    cx.background_executor()
 1664                        .timer(Duration::from_millis(100))
 1665                        .await;
 1666                    this.update_in(cx, |this, window, cx| {
 1667                        this.save_window_bounds(window, cx).detach();
 1668                        this.bounds_save_task_queued.take();
 1669                    })
 1670                    .ok();
 1671                }));
 1672                cx.notify();
 1673            }),
 1674            cx.observe_window_appearance(window, |_, window, cx| {
 1675                let window_appearance = window.appearance();
 1676
 1677                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1678
 1679                GlobalTheme::reload_theme(cx);
 1680                GlobalTheme::reload_icon_theme(cx);
 1681            }),
 1682            cx.on_release({
 1683                let weak_handle = weak_handle.clone();
 1684                move |this, cx| {
 1685                    this.app_state.workspace_store.update(cx, move |store, _| {
 1686                        store.workspaces.retain(|(_, weak)| weak != &weak_handle);
 1687                    })
 1688                }
 1689            }),
 1690        ];
 1691
 1692        cx.defer_in(window, move |this, window, cx| {
 1693            this.update_window_title(window, cx);
 1694            this.show_initial_notifications(cx);
 1695        });
 1696
 1697        let mut center = PaneGroup::new(center_pane.clone());
 1698        center.set_is_center(true);
 1699        center.mark_positions(cx);
 1700
 1701        Workspace {
 1702            weak_self: weak_handle.clone(),
 1703            zoomed: None,
 1704            zoomed_position: None,
 1705            previous_dock_drag_coordinates: None,
 1706            center,
 1707            panes: vec![center_pane.clone()],
 1708            panes_by_item: Default::default(),
 1709            active_pane: center_pane.clone(),
 1710            last_active_center_pane: Some(center_pane.downgrade()),
 1711            last_active_view_id: None,
 1712            status_bar,
 1713            modal_layer,
 1714            toast_layer,
 1715            titlebar_item: None,
 1716            active_worktree_override: None,
 1717            notifications: Notifications::default(),
 1718            suppressed_notifications: HashSet::default(),
 1719            left_dock,
 1720            bottom_dock,
 1721            right_dock,
 1722            _panels_task: None,
 1723            project: project.clone(),
 1724            follower_states: Default::default(),
 1725            last_leaders_by_pane: Default::default(),
 1726            dispatching_keystrokes: Default::default(),
 1727            window_edited: false,
 1728            last_window_title: None,
 1729            dirty_items: Default::default(),
 1730            active_call,
 1731            database_id: workspace_id,
 1732            app_state,
 1733            _observe_current_user,
 1734            _apply_leader_updates,
 1735            _schedule_serialize_workspace: None,
 1736            _serialize_workspace_task: None,
 1737            _schedule_serialize_ssh_paths: None,
 1738            leader_updates_tx,
 1739            _subscriptions: subscriptions,
 1740            pane_history_timestamp,
 1741            workspace_actions: Default::default(),
 1742            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1743            bounds: Default::default(),
 1744            centered_layout: false,
 1745            bounds_save_task_queued: None,
 1746            on_prompt_for_new_path: None,
 1747            on_prompt_for_open_path: None,
 1748            terminal_provider: None,
 1749            debugger_provider: None,
 1750            serializable_items_tx,
 1751            _items_serializer,
 1752            session_id: Some(session_id),
 1753
 1754            scheduled_tasks: Vec::new(),
 1755            last_open_dock_positions: Vec::new(),
 1756            removing: false,
 1757            sidebar_focus_handle: None,
 1758        }
 1759    }
 1760
 1761    pub fn new_local(
 1762        abs_paths: Vec<PathBuf>,
 1763        app_state: Arc<AppState>,
 1764        requesting_window: Option<WindowHandle<MultiWorkspace>>,
 1765        env: Option<HashMap<String, String>>,
 1766        init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
 1767        activate: bool,
 1768        cx: &mut App,
 1769    ) -> Task<anyhow::Result<OpenResult>> {
 1770        let project_handle = Project::local(
 1771            app_state.client.clone(),
 1772            app_state.node_runtime.clone(),
 1773            app_state.user_store.clone(),
 1774            app_state.languages.clone(),
 1775            app_state.fs.clone(),
 1776            env,
 1777            Default::default(),
 1778            cx,
 1779        );
 1780
 1781        let db = WorkspaceDb::global(cx);
 1782        let kvp = db::kvp::KeyValueStore::global(cx);
 1783        cx.spawn(async move |cx| {
 1784            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1785            for path in abs_paths.into_iter() {
 1786                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1787                    paths_to_open.push(canonical)
 1788                } else {
 1789                    paths_to_open.push(path)
 1790                }
 1791            }
 1792
 1793            let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
 1794
 1795            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1796                paths_to_open = paths.ordered_paths().cloned().collect();
 1797                if !paths.is_lexicographically_ordered() {
 1798                    project_handle.update(cx, |project, cx| {
 1799                        project.set_worktrees_reordered(true, cx);
 1800                    });
 1801                }
 1802            }
 1803
 1804            // Get project paths for all of the abs_paths
 1805            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1806                Vec::with_capacity(paths_to_open.len());
 1807
 1808            for path in paths_to_open.into_iter() {
 1809                if let Some((_, project_entry)) = cx
 1810                    .update(|cx| {
 1811                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1812                    })
 1813                    .await
 1814                    .log_err()
 1815                {
 1816                    project_paths.push((path, Some(project_entry)));
 1817                } else {
 1818                    project_paths.push((path, None));
 1819                }
 1820            }
 1821
 1822            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1823                serialized_workspace.id
 1824            } else {
 1825                db.next_id().await.unwrap_or_else(|_| Default::default())
 1826            };
 1827
 1828            let toolchains = db.toolchains(workspace_id).await?;
 1829
 1830            for (toolchain, worktree_path, path) in toolchains {
 1831                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1832                let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
 1833                    this.find_worktree(&worktree_path, cx)
 1834                        .and_then(|(worktree, rel_path)| {
 1835                            if rel_path.is_empty() {
 1836                                Some(worktree.read(cx).id())
 1837                            } else {
 1838                                None
 1839                            }
 1840                        })
 1841                }) else {
 1842                    // We did not find a worktree with a given path, but that's whatever.
 1843                    continue;
 1844                };
 1845                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1846                    continue;
 1847                }
 1848
 1849                project_handle
 1850                    .update(cx, |this, cx| {
 1851                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1852                    })
 1853                    .await;
 1854            }
 1855            if let Some(workspace) = serialized_workspace.as_ref() {
 1856                project_handle.update(cx, |this, cx| {
 1857                    for (scope, toolchains) in &workspace.user_toolchains {
 1858                        for toolchain in toolchains {
 1859                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1860                        }
 1861                    }
 1862                });
 1863            }
 1864
 1865            let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
 1866                if let Some(window) = requesting_window {
 1867                    let centered_layout = serialized_workspace
 1868                        .as_ref()
 1869                        .map(|w| w.centered_layout)
 1870                        .unwrap_or(false);
 1871
 1872                    let workspace = window.update(cx, |multi_workspace, window, cx| {
 1873                        let workspace = cx.new(|cx| {
 1874                            let mut workspace = Workspace::new(
 1875                                Some(workspace_id),
 1876                                project_handle.clone(),
 1877                                app_state.clone(),
 1878                                window,
 1879                                cx,
 1880                            );
 1881
 1882                            workspace.centered_layout = centered_layout;
 1883
 1884                            // Call init callback to add items before window renders
 1885                            if let Some(init) = init {
 1886                                init(&mut workspace, window, cx);
 1887                            }
 1888
 1889                            workspace
 1890                        });
 1891                        if activate {
 1892                            multi_workspace.activate(workspace.clone(), cx);
 1893                        } else {
 1894                            multi_workspace.add_workspace(workspace.clone(), cx);
 1895                        }
 1896                        workspace
 1897                    })?;
 1898                    (window, workspace)
 1899                } else {
 1900                    let window_bounds_override = window_bounds_env_override();
 1901
 1902                    let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1903                        (Some(WindowBounds::Windowed(bounds)), None)
 1904                    } else if let Some(workspace) = serialized_workspace.as_ref()
 1905                        && let Some(display) = workspace.display
 1906                        && let Some(bounds) = workspace.window_bounds.as_ref()
 1907                    {
 1908                        // Reopening an existing workspace - restore its saved bounds
 1909                        (Some(bounds.0), Some(display))
 1910                    } else if let Some((display, bounds)) =
 1911                        persistence::read_default_window_bounds(&kvp)
 1912                    {
 1913                        // New or empty workspace - use the last known window bounds
 1914                        (Some(bounds), Some(display))
 1915                    } else {
 1916                        // New window - let GPUI's default_bounds() handle cascading
 1917                        (None, None)
 1918                    };
 1919
 1920                    // Use the serialized workspace to construct the new window
 1921                    let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
 1922                    options.window_bounds = window_bounds;
 1923                    let centered_layout = serialized_workspace
 1924                        .as_ref()
 1925                        .map(|w| w.centered_layout)
 1926                        .unwrap_or(false);
 1927                    let window = cx.open_window(options, {
 1928                        let app_state = app_state.clone();
 1929                        let project_handle = project_handle.clone();
 1930                        move |window, cx| {
 1931                            let workspace = cx.new(|cx| {
 1932                                let mut workspace = Workspace::new(
 1933                                    Some(workspace_id),
 1934                                    project_handle,
 1935                                    app_state,
 1936                                    window,
 1937                                    cx,
 1938                                );
 1939                                workspace.centered_layout = centered_layout;
 1940
 1941                                // Call init callback to add items before window renders
 1942                                if let Some(init) = init {
 1943                                    init(&mut workspace, window, cx);
 1944                                }
 1945
 1946                                workspace
 1947                            });
 1948                            cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 1949                        }
 1950                    })?;
 1951                    let workspace =
 1952                        window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 1953                            multi_workspace.workspace().clone()
 1954                        })?;
 1955                    (window, workspace)
 1956                };
 1957
 1958            notify_if_database_failed(window, cx);
 1959            // Check if this is an empty workspace (no paths to open)
 1960            // An empty workspace is one where project_paths is empty
 1961            let is_empty_workspace = project_paths.is_empty();
 1962            // Check if serialized workspace has paths before it's moved
 1963            let serialized_workspace_has_paths = serialized_workspace
 1964                .as_ref()
 1965                .map(|ws| !ws.paths.is_empty())
 1966                .unwrap_or(false);
 1967
 1968            let opened_items = window
 1969                .update(cx, |_, window, cx| {
 1970                    workspace.update(cx, |_workspace: &mut Workspace, cx| {
 1971                        open_items(serialized_workspace, project_paths, window, cx)
 1972                    })
 1973                })?
 1974                .await
 1975                .unwrap_or_default();
 1976
 1977            // Restore default dock state for empty workspaces
 1978            // Only restore if:
 1979            // 1. This is an empty workspace (no paths), AND
 1980            // 2. The serialized workspace either doesn't exist or has no paths
 1981            if is_empty_workspace && !serialized_workspace_has_paths {
 1982                if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
 1983                    window
 1984                        .update(cx, |_, window, cx| {
 1985                            workspace.update(cx, |workspace, cx| {
 1986                                for (dock, serialized_dock) in [
 1987                                    (&workspace.right_dock, &default_docks.right),
 1988                                    (&workspace.left_dock, &default_docks.left),
 1989                                    (&workspace.bottom_dock, &default_docks.bottom),
 1990                                ] {
 1991                                    dock.update(cx, |dock, cx| {
 1992                                        dock.serialized_dock = Some(serialized_dock.clone());
 1993                                        dock.restore_state(window, cx);
 1994                                    });
 1995                                }
 1996                                cx.notify();
 1997                            });
 1998                        })
 1999                        .log_err();
 2000                }
 2001            }
 2002
 2003            window
 2004                .update(cx, |_, _window, cx| {
 2005                    workspace.update(cx, |this: &mut Workspace, cx| {
 2006                        this.update_history(cx);
 2007                    });
 2008                })
 2009                .log_err();
 2010            Ok(OpenResult {
 2011                window,
 2012                workspace,
 2013                opened_items,
 2014            })
 2015        })
 2016    }
 2017
 2018    pub fn weak_handle(&self) -> WeakEntity<Self> {
 2019        self.weak_self.clone()
 2020    }
 2021
 2022    pub fn left_dock(&self) -> &Entity<Dock> {
 2023        &self.left_dock
 2024    }
 2025
 2026    pub fn bottom_dock(&self) -> &Entity<Dock> {
 2027        &self.bottom_dock
 2028    }
 2029
 2030    pub fn set_bottom_dock_layout(
 2031        &mut self,
 2032        layout: BottomDockLayout,
 2033        window: &mut Window,
 2034        cx: &mut Context<Self>,
 2035    ) {
 2036        let fs = self.project().read(cx).fs();
 2037        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 2038            content.workspace.bottom_dock_layout = Some(layout);
 2039        });
 2040
 2041        cx.notify();
 2042        self.serialize_workspace(window, cx);
 2043    }
 2044
 2045    pub fn right_dock(&self) -> &Entity<Dock> {
 2046        &self.right_dock
 2047    }
 2048
 2049    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 2050        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 2051    }
 2052
 2053    pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
 2054        let left_dock = self.left_dock.read(cx);
 2055        let left_visible = left_dock.is_open();
 2056        let left_active_panel = left_dock
 2057            .active_panel()
 2058            .map(|panel| panel.persistent_name().to_string());
 2059        // `zoomed_position` is kept in sync with individual panel zoom state
 2060        // by the dock code in `Dock::new` and `Dock::add_panel`.
 2061        let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
 2062
 2063        let right_dock = self.right_dock.read(cx);
 2064        let right_visible = right_dock.is_open();
 2065        let right_active_panel = right_dock
 2066            .active_panel()
 2067            .map(|panel| panel.persistent_name().to_string());
 2068        let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
 2069
 2070        let bottom_dock = self.bottom_dock.read(cx);
 2071        let bottom_visible = bottom_dock.is_open();
 2072        let bottom_active_panel = bottom_dock
 2073            .active_panel()
 2074            .map(|panel| panel.persistent_name().to_string());
 2075        let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
 2076
 2077        DockStructure {
 2078            left: DockData {
 2079                visible: left_visible,
 2080                active_panel: left_active_panel,
 2081                zoom: left_dock_zoom,
 2082            },
 2083            right: DockData {
 2084                visible: right_visible,
 2085                active_panel: right_active_panel,
 2086                zoom: right_dock_zoom,
 2087            },
 2088            bottom: DockData {
 2089                visible: bottom_visible,
 2090                active_panel: bottom_active_panel,
 2091                zoom: bottom_dock_zoom,
 2092            },
 2093        }
 2094    }
 2095
 2096    pub fn set_dock_structure(
 2097        &self,
 2098        docks: DockStructure,
 2099        window: &mut Window,
 2100        cx: &mut Context<Self>,
 2101    ) {
 2102        for (dock, data) in [
 2103            (&self.left_dock, docks.left),
 2104            (&self.bottom_dock, docks.bottom),
 2105            (&self.right_dock, docks.right),
 2106        ] {
 2107            dock.update(cx, |dock, cx| {
 2108                dock.serialized_dock = Some(data);
 2109                dock.restore_state(window, cx);
 2110            });
 2111        }
 2112    }
 2113
 2114    pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
 2115        self.items(cx)
 2116            .filter_map(|item| {
 2117                let project_path = item.project_path(cx)?;
 2118                self.project.read(cx).absolute_path(&project_path, cx)
 2119            })
 2120            .collect()
 2121    }
 2122
 2123    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 2124        match position {
 2125            DockPosition::Left => &self.left_dock,
 2126            DockPosition::Bottom => &self.bottom_dock,
 2127            DockPosition::Right => &self.right_dock,
 2128        }
 2129    }
 2130
 2131    pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
 2132        self.all_docks().into_iter().find_map(|dock| {
 2133            let dock = dock.read(cx);
 2134            let panel = dock.panel::<T>()?;
 2135            dock.stored_panel_size_state(&panel)
 2136        })
 2137    }
 2138
 2139    pub fn persisted_panel_size_state(
 2140        &self,
 2141        panel_key: &'static str,
 2142        cx: &App,
 2143    ) -> Option<dock::PanelSizeState> {
 2144        dock::Dock::load_persisted_size_state(self, panel_key, cx)
 2145    }
 2146
 2147    pub fn persist_panel_size_state(
 2148        &self,
 2149        panel_key: &str,
 2150        size_state: dock::PanelSizeState,
 2151        cx: &mut App,
 2152    ) {
 2153        let Some(workspace_id) = self
 2154            .database_id()
 2155            .map(|id| i64::from(id).to_string())
 2156            .or(self.session_id())
 2157        else {
 2158            return;
 2159        };
 2160
 2161        let kvp = db::kvp::KeyValueStore::global(cx);
 2162        let panel_key = panel_key.to_string();
 2163        cx.background_spawn(async move {
 2164            let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
 2165            scope
 2166                .write(
 2167                    format!("{workspace_id}:{panel_key}"),
 2168                    serde_json::to_string(&size_state)?,
 2169                )
 2170                .await
 2171        })
 2172        .detach_and_log_err(cx);
 2173    }
 2174
 2175    pub fn set_panel_size_state<T: Panel>(
 2176        &mut self,
 2177        size_state: dock::PanelSizeState,
 2178        window: &mut Window,
 2179        cx: &mut Context<Self>,
 2180    ) -> bool {
 2181        let Some(panel) = self.panel::<T>(cx) else {
 2182            return false;
 2183        };
 2184
 2185        let dock = self.dock_at_position(panel.position(window, cx));
 2186        let did_set = dock.update(cx, |dock, cx| {
 2187            dock.set_panel_size_state(&panel, size_state, cx)
 2188        });
 2189
 2190        if did_set {
 2191            self.persist_panel_size_state(T::panel_key(), size_state, cx);
 2192        }
 2193
 2194        did_set
 2195    }
 2196
 2197    pub fn flexible_dock_size(
 2198        &self,
 2199        position: DockPosition,
 2200        ratio: f32,
 2201        window: &Window,
 2202        cx: &App,
 2203    ) -> Option<Pixels> {
 2204        if position.axis() != Axis::Horizontal {
 2205            return None;
 2206        }
 2207
 2208        let available_width = self.available_width_for_horizontal_dock(position, window, cx)?;
 2209        Some((available_width * ratio.clamp(0.0, 1.0)).max(RESIZE_HANDLE_SIZE))
 2210    }
 2211
 2212    pub fn resolved_dock_panel_size(
 2213        &self,
 2214        dock: &Dock,
 2215        panel: &dyn PanelHandle,
 2216        window: &Window,
 2217        cx: &App,
 2218    ) -> Pixels {
 2219        let size_state = dock.stored_panel_size_state(panel).unwrap_or_default();
 2220        dock::resolve_panel_size(size_state, panel, dock.position(), self, window, cx)
 2221    }
 2222
 2223    pub fn flexible_dock_ratio_for_size(
 2224        &self,
 2225        position: DockPosition,
 2226        size: Pixels,
 2227        window: &Window,
 2228        cx: &App,
 2229    ) -> Option<f32> {
 2230        if position.axis() != Axis::Horizontal {
 2231            return None;
 2232        }
 2233
 2234        let available_width = self.available_width_for_horizontal_dock(position, window, cx)?;
 2235        let available_width = available_width.max(RESIZE_HANDLE_SIZE);
 2236        Some((size / available_width).clamp(0.0, 1.0))
 2237    }
 2238
 2239    fn available_width_for_horizontal_dock(
 2240        &self,
 2241        position: DockPosition,
 2242        window: &Window,
 2243        cx: &App,
 2244    ) -> Option<Pixels> {
 2245        let workspace_width = self.bounds.size.width;
 2246        if workspace_width <= Pixels::ZERO {
 2247            return None;
 2248        }
 2249
 2250        let opposite_position = match position {
 2251            DockPosition::Left => DockPosition::Right,
 2252            DockPosition::Right => DockPosition::Left,
 2253            DockPosition::Bottom => return None,
 2254        };
 2255
 2256        let opposite_width = self
 2257            .dock_at_position(opposite_position)
 2258            .read(cx)
 2259            .stored_active_panel_size(window, cx)
 2260            .unwrap_or(Pixels::ZERO);
 2261
 2262        Some((workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE))
 2263    }
 2264
 2265    pub fn default_flexible_dock_ratio(&self, position: DockPosition) -> Option<f32> {
 2266        if position.axis() != Axis::Horizontal {
 2267            return None;
 2268        }
 2269
 2270        let pane = self.last_active_center_pane.clone()?.upgrade()?;
 2271        let pane_fraction = self.center.width_fraction_for_pane(&pane).unwrap_or(1.0);
 2272        Some((pane_fraction / (1.0 + pane_fraction)).clamp(0.0, 1.0))
 2273    }
 2274
 2275    pub fn is_edited(&self) -> bool {
 2276        self.window_edited
 2277    }
 2278
 2279    pub fn add_panel<T: Panel>(
 2280        &mut self,
 2281        panel: Entity<T>,
 2282        window: &mut Window,
 2283        cx: &mut Context<Self>,
 2284    ) {
 2285        let focus_handle = panel.panel_focus_handle(cx);
 2286        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 2287            .detach();
 2288
 2289        let dock_position = panel.position(window, cx);
 2290        let dock = self.dock_at_position(dock_position);
 2291        let any_panel = panel.to_any();
 2292        let persisted_size_state =
 2293            self.persisted_panel_size_state(T::panel_key(), cx)
 2294                .or_else(|| {
 2295                    load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
 2296                        let state = dock::PanelSizeState {
 2297                            size: Some(size),
 2298                            flexible_size_ratio: None,
 2299                        };
 2300                        self.persist_panel_size_state(T::panel_key(), state, cx);
 2301                        state
 2302                    })
 2303                });
 2304
 2305        dock.update(cx, |dock, cx| {
 2306            let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
 2307            if let Some(size_state) = persisted_size_state {
 2308                dock.set_panel_size_state(&panel, size_state, cx);
 2309            }
 2310            index
 2311        });
 2312
 2313        cx.emit(Event::PanelAdded(any_panel));
 2314    }
 2315
 2316    pub fn remove_panel<T: Panel>(
 2317        &mut self,
 2318        panel: &Entity<T>,
 2319        window: &mut Window,
 2320        cx: &mut Context<Self>,
 2321    ) {
 2322        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 2323            dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 2324        }
 2325    }
 2326
 2327    pub fn status_bar(&self) -> &Entity<StatusBar> {
 2328        &self.status_bar
 2329    }
 2330
 2331    pub fn set_workspace_sidebar_open(
 2332        &self,
 2333        open: bool,
 2334        has_notifications: bool,
 2335        show_toggle: bool,
 2336        cx: &mut App,
 2337    ) {
 2338        self.status_bar.update(cx, |status_bar, cx| {
 2339            status_bar.set_workspace_sidebar_open(open, cx);
 2340            status_bar.set_sidebar_has_notifications(has_notifications, cx);
 2341            status_bar.set_show_sidebar_toggle(show_toggle, cx);
 2342        });
 2343    }
 2344
 2345    pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
 2346        self.sidebar_focus_handle = handle;
 2347    }
 2348
 2349    pub fn status_bar_visible(&self, cx: &App) -> bool {
 2350        StatusBarSettings::get_global(cx).show
 2351    }
 2352
 2353    pub fn app_state(&self) -> &Arc<AppState> {
 2354        &self.app_state
 2355    }
 2356
 2357    pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
 2358        self._panels_task = Some(task);
 2359    }
 2360
 2361    pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
 2362        self._panels_task.take()
 2363    }
 2364
 2365    pub fn user_store(&self) -> &Entity<UserStore> {
 2366        &self.app_state.user_store
 2367    }
 2368
 2369    pub fn project(&self) -> &Entity<Project> {
 2370        &self.project
 2371    }
 2372
 2373    pub fn path_style(&self, cx: &App) -> PathStyle {
 2374        self.project.read(cx).path_style(cx)
 2375    }
 2376
 2377    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 2378        let mut history: HashMap<EntityId, usize> = HashMap::default();
 2379
 2380        for pane_handle in &self.panes {
 2381            let pane = pane_handle.read(cx);
 2382
 2383            for entry in pane.activation_history() {
 2384                history.insert(
 2385                    entry.entity_id,
 2386                    history
 2387                        .get(&entry.entity_id)
 2388                        .cloned()
 2389                        .unwrap_or(0)
 2390                        .max(entry.timestamp),
 2391                );
 2392            }
 2393        }
 2394
 2395        history
 2396    }
 2397
 2398    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 2399        let mut recent_item: Option<Entity<T>> = None;
 2400        let mut recent_timestamp = 0;
 2401        for pane_handle in &self.panes {
 2402            let pane = pane_handle.read(cx);
 2403            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 2404                pane.items().map(|item| (item.item_id(), item)).collect();
 2405            for entry in pane.activation_history() {
 2406                if entry.timestamp > recent_timestamp
 2407                    && let Some(&item) = item_map.get(&entry.entity_id)
 2408                    && let Some(typed_item) = item.act_as::<T>(cx)
 2409                {
 2410                    recent_timestamp = entry.timestamp;
 2411                    recent_item = Some(typed_item);
 2412                }
 2413            }
 2414        }
 2415        recent_item
 2416    }
 2417
 2418    pub fn recent_navigation_history_iter(
 2419        &self,
 2420        cx: &App,
 2421    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 2422        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 2423        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 2424
 2425        for pane in &self.panes {
 2426            let pane = pane.read(cx);
 2427
 2428            pane.nav_history()
 2429                .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
 2430                    if let Some(fs_path) = &fs_path {
 2431                        abs_paths_opened
 2432                            .entry(fs_path.clone())
 2433                            .or_default()
 2434                            .insert(project_path.clone());
 2435                    }
 2436                    let timestamp = entry.timestamp;
 2437                    match history.entry(project_path) {
 2438                        hash_map::Entry::Occupied(mut entry) => {
 2439                            let (_, old_timestamp) = entry.get();
 2440                            if &timestamp > old_timestamp {
 2441                                entry.insert((fs_path, timestamp));
 2442                            }
 2443                        }
 2444                        hash_map::Entry::Vacant(entry) => {
 2445                            entry.insert((fs_path, timestamp));
 2446                        }
 2447                    }
 2448                });
 2449
 2450            if let Some(item) = pane.active_item()
 2451                && let Some(project_path) = item.project_path(cx)
 2452            {
 2453                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 2454
 2455                if let Some(fs_path) = &fs_path {
 2456                    abs_paths_opened
 2457                        .entry(fs_path.clone())
 2458                        .or_default()
 2459                        .insert(project_path.clone());
 2460                }
 2461
 2462                history.insert(project_path, (fs_path, std::usize::MAX));
 2463            }
 2464        }
 2465
 2466        history
 2467            .into_iter()
 2468            .sorted_by_key(|(_, (_, order))| *order)
 2469            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 2470            .rev()
 2471            .filter(move |(history_path, abs_path)| {
 2472                let latest_project_path_opened = abs_path
 2473                    .as_ref()
 2474                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 2475                    .and_then(|project_paths| {
 2476                        project_paths
 2477                            .iter()
 2478                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 2479                    });
 2480
 2481                latest_project_path_opened.is_none_or(|path| path == history_path)
 2482            })
 2483    }
 2484
 2485    pub fn recent_navigation_history(
 2486        &self,
 2487        limit: Option<usize>,
 2488        cx: &App,
 2489    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 2490        self.recent_navigation_history_iter(cx)
 2491            .take(limit.unwrap_or(usize::MAX))
 2492            .collect()
 2493    }
 2494
 2495    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 2496        for pane in &self.panes {
 2497            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 2498        }
 2499    }
 2500
 2501    fn navigate_history(
 2502        &mut self,
 2503        pane: WeakEntity<Pane>,
 2504        mode: NavigationMode,
 2505        window: &mut Window,
 2506        cx: &mut Context<Workspace>,
 2507    ) -> Task<Result<()>> {
 2508        self.navigate_history_impl(
 2509            pane,
 2510            mode,
 2511            window,
 2512            &mut |history, cx| history.pop(mode, cx),
 2513            cx,
 2514        )
 2515    }
 2516
 2517    fn navigate_tag_history(
 2518        &mut self,
 2519        pane: WeakEntity<Pane>,
 2520        mode: TagNavigationMode,
 2521        window: &mut Window,
 2522        cx: &mut Context<Workspace>,
 2523    ) -> Task<Result<()>> {
 2524        self.navigate_history_impl(
 2525            pane,
 2526            NavigationMode::Normal,
 2527            window,
 2528            &mut |history, _cx| history.pop_tag(mode),
 2529            cx,
 2530        )
 2531    }
 2532
 2533    fn navigate_history_impl(
 2534        &mut self,
 2535        pane: WeakEntity<Pane>,
 2536        mode: NavigationMode,
 2537        window: &mut Window,
 2538        cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
 2539        cx: &mut Context<Workspace>,
 2540    ) -> Task<Result<()>> {
 2541        let to_load = if let Some(pane) = pane.upgrade() {
 2542            pane.update(cx, |pane, cx| {
 2543                window.focus(&pane.focus_handle(cx), cx);
 2544                loop {
 2545                    // Retrieve the weak item handle from the history.
 2546                    let entry = cb(pane.nav_history_mut(), cx)?;
 2547
 2548                    // If the item is still present in this pane, then activate it.
 2549                    if let Some(index) = entry
 2550                        .item
 2551                        .upgrade()
 2552                        .and_then(|v| pane.index_for_item(v.as_ref()))
 2553                    {
 2554                        let prev_active_item_index = pane.active_item_index();
 2555                        pane.nav_history_mut().set_mode(mode);
 2556                        pane.activate_item(index, true, true, window, cx);
 2557                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2558
 2559                        let mut navigated = prev_active_item_index != pane.active_item_index();
 2560                        if let Some(data) = entry.data {
 2561                            navigated |= pane.active_item()?.navigate(data, window, cx);
 2562                        }
 2563
 2564                        if navigated {
 2565                            break None;
 2566                        }
 2567                    } else {
 2568                        // If the item is no longer present in this pane, then retrieve its
 2569                        // path info in order to reopen it.
 2570                        break pane
 2571                            .nav_history()
 2572                            .path_for_item(entry.item.id())
 2573                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 2574                    }
 2575                }
 2576            })
 2577        } else {
 2578            None
 2579        };
 2580
 2581        if let Some((project_path, abs_path, entry)) = to_load {
 2582            // If the item was no longer present, then load it again from its previous path, first try the local path
 2583            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2584
 2585            cx.spawn_in(window, async move  |workspace, cx| {
 2586                let open_by_project_path = open_by_project_path.await;
 2587                let mut navigated = false;
 2588                match open_by_project_path
 2589                    .with_context(|| format!("Navigating to {project_path:?}"))
 2590                {
 2591                    Ok((project_entry_id, build_item)) => {
 2592                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2593                            pane.nav_history_mut().set_mode(mode);
 2594                            pane.active_item().map(|p| p.item_id())
 2595                        })?;
 2596
 2597                        pane.update_in(cx, |pane, window, cx| {
 2598                            let item = pane.open_item(
 2599                                project_entry_id,
 2600                                project_path,
 2601                                true,
 2602                                entry.is_preview,
 2603                                true,
 2604                                None,
 2605                                window, cx,
 2606                                build_item,
 2607                            );
 2608                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2609                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2610                            if let Some(data) = entry.data {
 2611                                navigated |= item.navigate(data, window, cx);
 2612                            }
 2613                        })?;
 2614                    }
 2615                    Err(open_by_project_path_e) => {
 2616                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2617                        // and its worktree is now dropped
 2618                        if let Some(abs_path) = abs_path {
 2619                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2620                                pane.nav_history_mut().set_mode(mode);
 2621                                pane.active_item().map(|p| p.item_id())
 2622                            })?;
 2623                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2624                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2625                            })?;
 2626                            match open_by_abs_path
 2627                                .await
 2628                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2629                            {
 2630                                Ok(item) => {
 2631                                    pane.update_in(cx, |pane, window, cx| {
 2632                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2633                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2634                                        if let Some(data) = entry.data {
 2635                                            navigated |= item.navigate(data, window, cx);
 2636                                        }
 2637                                    })?;
 2638                                }
 2639                                Err(open_by_abs_path_e) => {
 2640                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2641                                }
 2642                            }
 2643                        }
 2644                    }
 2645                }
 2646
 2647                if !navigated {
 2648                    workspace
 2649                        .update_in(cx, |workspace, window, cx| {
 2650                            Self::navigate_history(workspace, pane, mode, window, cx)
 2651                        })?
 2652                        .await?;
 2653                }
 2654
 2655                Ok(())
 2656            })
 2657        } else {
 2658            Task::ready(Ok(()))
 2659        }
 2660    }
 2661
 2662    pub fn go_back(
 2663        &mut self,
 2664        pane: WeakEntity<Pane>,
 2665        window: &mut Window,
 2666        cx: &mut Context<Workspace>,
 2667    ) -> Task<Result<()>> {
 2668        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2669    }
 2670
 2671    pub fn go_forward(
 2672        &mut self,
 2673        pane: WeakEntity<Pane>,
 2674        window: &mut Window,
 2675        cx: &mut Context<Workspace>,
 2676    ) -> Task<Result<()>> {
 2677        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2678    }
 2679
 2680    pub fn reopen_closed_item(
 2681        &mut self,
 2682        window: &mut Window,
 2683        cx: &mut Context<Workspace>,
 2684    ) -> Task<Result<()>> {
 2685        self.navigate_history(
 2686            self.active_pane().downgrade(),
 2687            NavigationMode::ReopeningClosedItem,
 2688            window,
 2689            cx,
 2690        )
 2691    }
 2692
 2693    pub fn client(&self) -> &Arc<Client> {
 2694        &self.app_state.client
 2695    }
 2696
 2697    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2698        self.titlebar_item = Some(item);
 2699        cx.notify();
 2700    }
 2701
 2702    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2703        self.on_prompt_for_new_path = Some(prompt)
 2704    }
 2705
 2706    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2707        self.on_prompt_for_open_path = Some(prompt)
 2708    }
 2709
 2710    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2711        self.terminal_provider = Some(Box::new(provider));
 2712    }
 2713
 2714    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2715        self.debugger_provider = Some(Arc::new(provider));
 2716    }
 2717
 2718    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2719        self.debugger_provider.clone()
 2720    }
 2721
 2722    pub fn prompt_for_open_path(
 2723        &mut self,
 2724        path_prompt_options: PathPromptOptions,
 2725        lister: DirectoryLister,
 2726        window: &mut Window,
 2727        cx: &mut Context<Self>,
 2728    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2729        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2730            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2731            let rx = prompt(self, lister, window, cx);
 2732            self.on_prompt_for_open_path = Some(prompt);
 2733            rx
 2734        } else {
 2735            let (tx, rx) = oneshot::channel();
 2736            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2737
 2738            cx.spawn_in(window, async move |workspace, cx| {
 2739                let Ok(result) = abs_path.await else {
 2740                    return Ok(());
 2741                };
 2742
 2743                match result {
 2744                    Ok(result) => {
 2745                        tx.send(result).ok();
 2746                    }
 2747                    Err(err) => {
 2748                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2749                            workspace.show_portal_error(err.to_string(), cx);
 2750                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2751                            let rx = prompt(workspace, lister, window, cx);
 2752                            workspace.on_prompt_for_open_path = Some(prompt);
 2753                            rx
 2754                        })?;
 2755                        if let Ok(path) = rx.await {
 2756                            tx.send(path).ok();
 2757                        }
 2758                    }
 2759                };
 2760                anyhow::Ok(())
 2761            })
 2762            .detach();
 2763
 2764            rx
 2765        }
 2766    }
 2767
 2768    pub fn prompt_for_new_path(
 2769        &mut self,
 2770        lister: DirectoryLister,
 2771        suggested_name: Option<String>,
 2772        window: &mut Window,
 2773        cx: &mut Context<Self>,
 2774    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2775        if self.project.read(cx).is_via_collab()
 2776            || self.project.read(cx).is_via_remote_server()
 2777            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2778        {
 2779            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2780            let rx = prompt(self, lister, suggested_name, window, cx);
 2781            self.on_prompt_for_new_path = Some(prompt);
 2782            return rx;
 2783        }
 2784
 2785        let (tx, rx) = oneshot::channel();
 2786        cx.spawn_in(window, async move |workspace, cx| {
 2787            let abs_path = workspace.update(cx, |workspace, cx| {
 2788                let relative_to = workspace
 2789                    .most_recent_active_path(cx)
 2790                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2791                    .or_else(|| {
 2792                        let project = workspace.project.read(cx);
 2793                        project.visible_worktrees(cx).find_map(|worktree| {
 2794                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2795                        })
 2796                    })
 2797                    .or_else(std::env::home_dir)
 2798                    .unwrap_or_else(|| PathBuf::from(""));
 2799                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2800            })?;
 2801            let abs_path = match abs_path.await? {
 2802                Ok(path) => path,
 2803                Err(err) => {
 2804                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2805                        workspace.show_portal_error(err.to_string(), cx);
 2806
 2807                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2808                        let rx = prompt(workspace, lister, suggested_name, window, cx);
 2809                        workspace.on_prompt_for_new_path = Some(prompt);
 2810                        rx
 2811                    })?;
 2812                    if let Ok(path) = rx.await {
 2813                        tx.send(path).ok();
 2814                    }
 2815                    return anyhow::Ok(());
 2816                }
 2817            };
 2818
 2819            tx.send(abs_path.map(|path| vec![path])).ok();
 2820            anyhow::Ok(())
 2821        })
 2822        .detach();
 2823
 2824        rx
 2825    }
 2826
 2827    pub fn titlebar_item(&self) -> Option<AnyView> {
 2828        self.titlebar_item.clone()
 2829    }
 2830
 2831    /// Returns the worktree override set by the user (e.g., via the project dropdown).
 2832    /// When set, git-related operations should use this worktree instead of deriving
 2833    /// the active worktree from the focused file.
 2834    pub fn active_worktree_override(&self) -> Option<WorktreeId> {
 2835        self.active_worktree_override
 2836    }
 2837
 2838    pub fn set_active_worktree_override(
 2839        &mut self,
 2840        worktree_id: Option<WorktreeId>,
 2841        cx: &mut Context<Self>,
 2842    ) {
 2843        self.active_worktree_override = worktree_id;
 2844        cx.notify();
 2845    }
 2846
 2847    pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
 2848        self.active_worktree_override = None;
 2849        cx.notify();
 2850    }
 2851
 2852    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2853    ///
 2854    /// If the given workspace has a local project, then it will be passed
 2855    /// to the callback. Otherwise, a new empty window will be created.
 2856    pub fn with_local_workspace<T, F>(
 2857        &mut self,
 2858        window: &mut Window,
 2859        cx: &mut Context<Self>,
 2860        callback: F,
 2861    ) -> Task<Result<T>>
 2862    where
 2863        T: 'static,
 2864        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2865    {
 2866        if self.project.read(cx).is_local() {
 2867            Task::ready(Ok(callback(self, window, cx)))
 2868        } else {
 2869            let env = self.project.read(cx).cli_environment(cx);
 2870            let task = Self::new_local(
 2871                Vec::new(),
 2872                self.app_state.clone(),
 2873                None,
 2874                env,
 2875                None,
 2876                true,
 2877                cx,
 2878            );
 2879            cx.spawn_in(window, async move |_vh, cx| {
 2880                let OpenResult {
 2881                    window: multi_workspace_window,
 2882                    ..
 2883                } = task.await?;
 2884                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2885                    let workspace = multi_workspace.workspace().clone();
 2886                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2887                })
 2888            })
 2889        }
 2890    }
 2891
 2892    /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
 2893    ///
 2894    /// If the given workspace has a local project, then it will be passed
 2895    /// to the callback. Otherwise, a new empty window will be created.
 2896    pub fn with_local_or_wsl_workspace<T, F>(
 2897        &mut self,
 2898        window: &mut Window,
 2899        cx: &mut Context<Self>,
 2900        callback: F,
 2901    ) -> Task<Result<T>>
 2902    where
 2903        T: 'static,
 2904        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2905    {
 2906        let project = self.project.read(cx);
 2907        if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
 2908            Task::ready(Ok(callback(self, window, cx)))
 2909        } else {
 2910            let env = self.project.read(cx).cli_environment(cx);
 2911            let task = Self::new_local(
 2912                Vec::new(),
 2913                self.app_state.clone(),
 2914                None,
 2915                env,
 2916                None,
 2917                true,
 2918                cx,
 2919            );
 2920            cx.spawn_in(window, async move |_vh, cx| {
 2921                let OpenResult {
 2922                    window: multi_workspace_window,
 2923                    ..
 2924                } = task.await?;
 2925                multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 2926                    let workspace = multi_workspace.workspace().clone();
 2927                    workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
 2928                })
 2929            })
 2930        }
 2931    }
 2932
 2933    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2934        self.project.read(cx).worktrees(cx)
 2935    }
 2936
 2937    pub fn visible_worktrees<'a>(
 2938        &self,
 2939        cx: &'a App,
 2940    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2941        self.project.read(cx).visible_worktrees(cx)
 2942    }
 2943
 2944    #[cfg(any(test, feature = "test-support"))]
 2945    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2946        let futures = self
 2947            .worktrees(cx)
 2948            .filter_map(|worktree| worktree.read(cx).as_local())
 2949            .map(|worktree| worktree.scan_complete())
 2950            .collect::<Vec<_>>();
 2951        async move {
 2952            for future in futures {
 2953                future.await;
 2954            }
 2955        }
 2956    }
 2957
 2958    pub fn close_global(cx: &mut App) {
 2959        cx.defer(|cx| {
 2960            cx.windows().iter().find(|window| {
 2961                window
 2962                    .update(cx, |_, window, _| {
 2963                        if window.is_window_active() {
 2964                            //This can only get called when the window's project connection has been lost
 2965                            //so we don't need to prompt the user for anything and instead just close the window
 2966                            window.remove_window();
 2967                            true
 2968                        } else {
 2969                            false
 2970                        }
 2971                    })
 2972                    .unwrap_or(false)
 2973            });
 2974        });
 2975    }
 2976
 2977    pub fn move_focused_panel_to_next_position(
 2978        &mut self,
 2979        _: &MoveFocusedPanelToNextPosition,
 2980        window: &mut Window,
 2981        cx: &mut Context<Self>,
 2982    ) {
 2983        let docks = self.all_docks();
 2984        let active_dock = docks
 2985            .into_iter()
 2986            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 2987
 2988        if let Some(dock) = active_dock {
 2989            dock.update(cx, |dock, cx| {
 2990                let active_panel = dock
 2991                    .active_panel()
 2992                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 2993
 2994                if let Some(panel) = active_panel {
 2995                    panel.move_to_next_position(window, cx);
 2996                }
 2997            })
 2998        }
 2999    }
 3000
 3001    pub fn prepare_to_close(
 3002        &mut self,
 3003        close_intent: CloseIntent,
 3004        window: &mut Window,
 3005        cx: &mut Context<Self>,
 3006    ) -> Task<Result<bool>> {
 3007        let active_call = self.active_global_call();
 3008
 3009        cx.spawn_in(window, async move |this, cx| {
 3010            this.update(cx, |this, _| {
 3011                if close_intent == CloseIntent::CloseWindow {
 3012                    this.removing = true;
 3013                }
 3014            })?;
 3015
 3016            let workspace_count = cx.update(|_window, cx| {
 3017                cx.windows()
 3018                    .iter()
 3019                    .filter(|window| window.downcast::<MultiWorkspace>().is_some())
 3020                    .count()
 3021            })?;
 3022
 3023            #[cfg(target_os = "macos")]
 3024            let save_last_workspace = false;
 3025
 3026            // On Linux and Windows, closing the last window should restore the last workspace.
 3027            #[cfg(not(target_os = "macos"))]
 3028            let save_last_workspace = {
 3029                let remaining_workspaces = cx.update(|_window, cx| {
 3030                    cx.windows()
 3031                        .iter()
 3032                        .filter_map(|window| window.downcast::<MultiWorkspace>())
 3033                        .filter_map(|multi_workspace| {
 3034                            multi_workspace
 3035                                .update(cx, |multi_workspace, _, cx| {
 3036                                    multi_workspace.workspace().read(cx).removing
 3037                                })
 3038                                .ok()
 3039                        })
 3040                        .filter(|removing| !removing)
 3041                        .count()
 3042                })?;
 3043
 3044                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 3045            };
 3046
 3047            if let Some(active_call) = active_call
 3048                && workspace_count == 1
 3049                && cx
 3050                    .update(|_window, cx| active_call.0.is_in_room(cx))
 3051                    .unwrap_or(false)
 3052            {
 3053                if close_intent == CloseIntent::CloseWindow {
 3054                    this.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3055                    let answer = cx.update(|window, cx| {
 3056                        window.prompt(
 3057                            PromptLevel::Warning,
 3058                            "Do you want to leave the current call?",
 3059                            None,
 3060                            &["Close window and hang up", "Cancel"],
 3061                            cx,
 3062                        )
 3063                    })?;
 3064
 3065                    if answer.await.log_err() == Some(1) {
 3066                        return anyhow::Ok(false);
 3067                    } else {
 3068                        if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
 3069                            task.await.log_err();
 3070                        }
 3071                    }
 3072                }
 3073                if close_intent == CloseIntent::ReplaceWindow {
 3074                    _ = cx.update(|_window, cx| {
 3075                        let multi_workspace = cx
 3076                            .windows()
 3077                            .iter()
 3078                            .filter_map(|window| window.downcast::<MultiWorkspace>())
 3079                            .next()
 3080                            .unwrap();
 3081                        let project = multi_workspace
 3082                            .read(cx)?
 3083                            .workspace()
 3084                            .read(cx)
 3085                            .project
 3086                            .clone();
 3087                        if project.read(cx).is_shared() {
 3088                            active_call.0.unshare_project(project, cx)?;
 3089                        }
 3090                        Ok::<_, anyhow::Error>(())
 3091                    });
 3092                }
 3093            }
 3094
 3095            let save_result = this
 3096                .update_in(cx, |this, window, cx| {
 3097                    this.save_all_internal(SaveIntent::Close, window, cx)
 3098                })?
 3099                .await;
 3100
 3101            // If we're not quitting, but closing, we remove the workspace from
 3102            // the current session.
 3103            if close_intent != CloseIntent::Quit
 3104                && !save_last_workspace
 3105                && save_result.as_ref().is_ok_and(|&res| res)
 3106            {
 3107                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 3108                    .await;
 3109            }
 3110
 3111            save_result
 3112        })
 3113    }
 3114
 3115    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 3116        self.save_all_internal(
 3117            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 3118            window,
 3119            cx,
 3120        )
 3121        .detach_and_log_err(cx);
 3122    }
 3123
 3124    fn send_keystrokes(
 3125        &mut self,
 3126        action: &SendKeystrokes,
 3127        window: &mut Window,
 3128        cx: &mut Context<Self>,
 3129    ) {
 3130        let keystrokes: Vec<Keystroke> = action
 3131            .0
 3132            .split(' ')
 3133            .flat_map(|k| Keystroke::parse(k).log_err())
 3134            .map(|k| {
 3135                cx.keyboard_mapper()
 3136                    .map_key_equivalent(k, false)
 3137                    .inner()
 3138                    .clone()
 3139            })
 3140            .collect();
 3141        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 3142    }
 3143
 3144    pub fn send_keystrokes_impl(
 3145        &mut self,
 3146        keystrokes: Vec<Keystroke>,
 3147        window: &mut Window,
 3148        cx: &mut Context<Self>,
 3149    ) -> Shared<Task<()>> {
 3150        let mut state = self.dispatching_keystrokes.borrow_mut();
 3151        if !state.dispatched.insert(keystrokes.clone()) {
 3152            cx.propagate();
 3153            return state.task.clone().unwrap();
 3154        }
 3155
 3156        state.queue.extend(keystrokes);
 3157
 3158        let keystrokes = self.dispatching_keystrokes.clone();
 3159        if state.task.is_none() {
 3160            state.task = Some(
 3161                window
 3162                    .spawn(cx, async move |cx| {
 3163                        // limit to 100 keystrokes to avoid infinite recursion.
 3164                        for _ in 0..100 {
 3165                            let keystroke = {
 3166                                let mut state = keystrokes.borrow_mut();
 3167                                let Some(keystroke) = state.queue.pop_front() else {
 3168                                    state.dispatched.clear();
 3169                                    state.task.take();
 3170                                    return;
 3171                                };
 3172                                keystroke
 3173                            };
 3174                            cx.update(|window, cx| {
 3175                                let focused = window.focused(cx);
 3176                                window.dispatch_keystroke(keystroke.clone(), cx);
 3177                                if window.focused(cx) != focused {
 3178                                    // dispatch_keystroke may cause the focus to change.
 3179                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 3180                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 3181                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 3182                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 3183                                    // )
 3184                                    window.draw(cx).clear();
 3185                                }
 3186                            })
 3187                            .ok();
 3188
 3189                            // Yield between synthetic keystrokes so deferred focus and
 3190                            // other effects can settle before dispatching the next key.
 3191                            yield_now().await;
 3192                        }
 3193
 3194                        *keystrokes.borrow_mut() = Default::default();
 3195                        log::error!("over 100 keystrokes passed to send_keystrokes");
 3196                    })
 3197                    .shared(),
 3198            );
 3199        }
 3200        state.task.clone().unwrap()
 3201    }
 3202
 3203    fn save_all_internal(
 3204        &mut self,
 3205        mut save_intent: SaveIntent,
 3206        window: &mut Window,
 3207        cx: &mut Context<Self>,
 3208    ) -> Task<Result<bool>> {
 3209        if self.project.read(cx).is_disconnected(cx) {
 3210            return Task::ready(Ok(true));
 3211        }
 3212        let dirty_items = self
 3213            .panes
 3214            .iter()
 3215            .flat_map(|pane| {
 3216                pane.read(cx).items().filter_map(|item| {
 3217                    if item.is_dirty(cx) {
 3218                        item.tab_content_text(0, cx);
 3219                        Some((pane.downgrade(), item.boxed_clone()))
 3220                    } else {
 3221                        None
 3222                    }
 3223                })
 3224            })
 3225            .collect::<Vec<_>>();
 3226
 3227        let project = self.project.clone();
 3228        cx.spawn_in(window, async move |workspace, cx| {
 3229            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 3230                let (serialize_tasks, remaining_dirty_items) =
 3231                    workspace.update_in(cx, |workspace, window, cx| {
 3232                        let mut remaining_dirty_items = Vec::new();
 3233                        let mut serialize_tasks = Vec::new();
 3234                        for (pane, item) in dirty_items {
 3235                            if let Some(task) = item
 3236                                .to_serializable_item_handle(cx)
 3237                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 3238                            {
 3239                                serialize_tasks.push(task);
 3240                            } else {
 3241                                remaining_dirty_items.push((pane, item));
 3242                            }
 3243                        }
 3244                        (serialize_tasks, remaining_dirty_items)
 3245                    })?;
 3246
 3247                futures::future::try_join_all(serialize_tasks).await?;
 3248
 3249                if !remaining_dirty_items.is_empty() {
 3250                    workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
 3251                }
 3252
 3253                if remaining_dirty_items.len() > 1 {
 3254                    let answer = workspace.update_in(cx, |_, window, cx| {
 3255                        let detail = Pane::file_names_for_prompt(
 3256                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 3257                            cx,
 3258                        );
 3259                        window.prompt(
 3260                            PromptLevel::Warning,
 3261                            "Do you want to save all changes in the following files?",
 3262                            Some(&detail),
 3263                            &["Save all", "Discard all", "Cancel"],
 3264                            cx,
 3265                        )
 3266                    })?;
 3267                    match answer.await.log_err() {
 3268                        Some(0) => save_intent = SaveIntent::SaveAll,
 3269                        Some(1) => save_intent = SaveIntent::Skip,
 3270                        Some(2) => return Ok(false),
 3271                        _ => {}
 3272                    }
 3273                }
 3274
 3275                remaining_dirty_items
 3276            } else {
 3277                dirty_items
 3278            };
 3279
 3280            for (pane, item) in dirty_items {
 3281                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 3282                    (
 3283                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 3284                        item.project_entry_ids(cx),
 3285                    )
 3286                })?;
 3287                if (singleton || !project_entry_ids.is_empty())
 3288                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 3289                {
 3290                    return Ok(false);
 3291                }
 3292            }
 3293            Ok(true)
 3294        })
 3295    }
 3296
 3297    pub fn open_workspace_for_paths(
 3298        &mut self,
 3299        replace_current_window: bool,
 3300        paths: Vec<PathBuf>,
 3301        window: &mut Window,
 3302        cx: &mut Context<Self>,
 3303    ) -> Task<Result<Entity<Workspace>>> {
 3304        let window_handle = window.window_handle().downcast::<MultiWorkspace>();
 3305        let is_remote = self.project.read(cx).is_via_collab();
 3306        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 3307        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 3308
 3309        let window_to_replace = if replace_current_window {
 3310            window_handle
 3311        } else if is_remote || has_worktree || has_dirty_items {
 3312            None
 3313        } else {
 3314            window_handle
 3315        };
 3316        let app_state = self.app_state.clone();
 3317
 3318        cx.spawn(async move |_, cx| {
 3319            let OpenResult { workspace, .. } = cx
 3320                .update(|cx| {
 3321                    open_paths(
 3322                        &paths,
 3323                        app_state,
 3324                        OpenOptions {
 3325                            replace_window: window_to_replace,
 3326                            ..Default::default()
 3327                        },
 3328                        cx,
 3329                    )
 3330                })
 3331                .await?;
 3332            Ok(workspace)
 3333        })
 3334    }
 3335
 3336    #[allow(clippy::type_complexity)]
 3337    pub fn open_paths(
 3338        &mut self,
 3339        mut abs_paths: Vec<PathBuf>,
 3340        options: OpenOptions,
 3341        pane: Option<WeakEntity<Pane>>,
 3342        window: &mut Window,
 3343        cx: &mut Context<Self>,
 3344    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 3345        let fs = self.app_state.fs.clone();
 3346
 3347        let caller_ordered_abs_paths = abs_paths.clone();
 3348
 3349        // Sort the paths to ensure we add worktrees for parents before their children.
 3350        abs_paths.sort_unstable();
 3351        cx.spawn_in(window, async move |this, cx| {
 3352            let mut tasks = Vec::with_capacity(abs_paths.len());
 3353
 3354            for abs_path in &abs_paths {
 3355                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3356                    OpenVisible::All => Some(true),
 3357                    OpenVisible::None => Some(false),
 3358                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 3359                        Some(Some(metadata)) => Some(!metadata.is_dir),
 3360                        Some(None) => Some(true),
 3361                        None => None,
 3362                    },
 3363                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 3364                        Some(Some(metadata)) => Some(metadata.is_dir),
 3365                        Some(None) => Some(false),
 3366                        None => None,
 3367                    },
 3368                };
 3369                let project_path = match visible {
 3370                    Some(visible) => match this
 3371                        .update(cx, |this, cx| {
 3372                            Workspace::project_path_for_path(
 3373                                this.project.clone(),
 3374                                abs_path,
 3375                                visible,
 3376                                cx,
 3377                            )
 3378                        })
 3379                        .log_err()
 3380                    {
 3381                        Some(project_path) => project_path.await.log_err(),
 3382                        None => None,
 3383                    },
 3384                    None => None,
 3385                };
 3386
 3387                let this = this.clone();
 3388                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 3389                let fs = fs.clone();
 3390                let pane = pane.clone();
 3391                let task = cx.spawn(async move |cx| {
 3392                    let (_worktree, project_path) = project_path?;
 3393                    if fs.is_dir(&abs_path).await {
 3394                        // Opening a directory should not race to update the active entry.
 3395                        // We'll select/reveal a deterministic final entry after all paths finish opening.
 3396                        None
 3397                    } else {
 3398                        Some(
 3399                            this.update_in(cx, |this, window, cx| {
 3400                                this.open_path(
 3401                                    project_path,
 3402                                    pane,
 3403                                    options.focus.unwrap_or(true),
 3404                                    window,
 3405                                    cx,
 3406                                )
 3407                            })
 3408                            .ok()?
 3409                            .await,
 3410                        )
 3411                    }
 3412                });
 3413                tasks.push(task);
 3414            }
 3415
 3416            let results = futures::future::join_all(tasks).await;
 3417
 3418            // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
 3419            let mut winner: Option<(PathBuf, bool)> = None;
 3420            for abs_path in caller_ordered_abs_paths.into_iter().rev() {
 3421                if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
 3422                    if !metadata.is_dir {
 3423                        winner = Some((abs_path, false));
 3424                        break;
 3425                    }
 3426                    if winner.is_none() {
 3427                        winner = Some((abs_path, true));
 3428                    }
 3429                } else if winner.is_none() {
 3430                    winner = Some((abs_path, false));
 3431                }
 3432            }
 3433
 3434            // Compute the winner entry id on the foreground thread and emit once, after all
 3435            // paths finish opening. This avoids races between concurrently-opening paths
 3436            // (directories in particular) and makes the resulting project panel selection
 3437            // deterministic.
 3438            if let Some((winner_abs_path, winner_is_dir)) = winner {
 3439                'emit_winner: {
 3440                    let winner_abs_path: Arc<Path> =
 3441                        SanitizedPath::new(&winner_abs_path).as_path().into();
 3442
 3443                    let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 3444                        OpenVisible::All => true,
 3445                        OpenVisible::None => false,
 3446                        OpenVisible::OnlyFiles => !winner_is_dir,
 3447                        OpenVisible::OnlyDirectories => winner_is_dir,
 3448                    };
 3449
 3450                    let Some(worktree_task) = this
 3451                        .update(cx, |workspace, cx| {
 3452                            workspace.project.update(cx, |project, cx| {
 3453                                project.find_or_create_worktree(
 3454                                    winner_abs_path.as_ref(),
 3455                                    visible,
 3456                                    cx,
 3457                                )
 3458                            })
 3459                        })
 3460                        .ok()
 3461                    else {
 3462                        break 'emit_winner;
 3463                    };
 3464
 3465                    let Ok((worktree, _)) = worktree_task.await else {
 3466                        break 'emit_winner;
 3467                    };
 3468
 3469                    let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
 3470                        let worktree = worktree.read(cx);
 3471                        let worktree_abs_path = worktree.abs_path();
 3472                        let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
 3473                            worktree.root_entry()
 3474                        } else {
 3475                            winner_abs_path
 3476                                .strip_prefix(worktree_abs_path.as_ref())
 3477                                .ok()
 3478                                .and_then(|relative_path| {
 3479                                    let relative_path =
 3480                                        RelPath::new(relative_path, PathStyle::local())
 3481                                            .log_err()?;
 3482                                    worktree.entry_for_path(&relative_path)
 3483                                })
 3484                        }?;
 3485                        Some(entry.id)
 3486                    }) else {
 3487                        break 'emit_winner;
 3488                    };
 3489
 3490                    this.update(cx, |workspace, cx| {
 3491                        workspace.project.update(cx, |_, cx| {
 3492                            cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 3493                        });
 3494                    })
 3495                    .ok();
 3496                }
 3497            }
 3498
 3499            results
 3500        })
 3501    }
 3502
 3503    pub fn open_resolved_path(
 3504        &mut self,
 3505        path: ResolvedPath,
 3506        window: &mut Window,
 3507        cx: &mut Context<Self>,
 3508    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3509        match path {
 3510            ResolvedPath::ProjectPath { project_path, .. } => {
 3511                self.open_path(project_path, None, true, window, cx)
 3512            }
 3513            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 3514                PathBuf::from(path),
 3515                OpenOptions {
 3516                    visible: Some(OpenVisible::None),
 3517                    ..Default::default()
 3518                },
 3519                window,
 3520                cx,
 3521            ),
 3522        }
 3523    }
 3524
 3525    pub fn absolute_path_of_worktree(
 3526        &self,
 3527        worktree_id: WorktreeId,
 3528        cx: &mut Context<Self>,
 3529    ) -> Option<PathBuf> {
 3530        self.project
 3531            .read(cx)
 3532            .worktree_for_id(worktree_id, cx)
 3533            // TODO: use `abs_path` or `root_dir`
 3534            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 3535    }
 3536
 3537    pub fn add_folder_to_project(
 3538        &mut self,
 3539        _: &AddFolderToProject,
 3540        window: &mut Window,
 3541        cx: &mut Context<Self>,
 3542    ) {
 3543        let project = self.project.read(cx);
 3544        if project.is_via_collab() {
 3545            self.show_error(
 3546                &anyhow!("You cannot add folders to someone else's project"),
 3547                cx,
 3548            );
 3549            return;
 3550        }
 3551        let paths = self.prompt_for_open_path(
 3552            PathPromptOptions {
 3553                files: false,
 3554                directories: true,
 3555                multiple: true,
 3556                prompt: None,
 3557            },
 3558            DirectoryLister::Project(self.project.clone()),
 3559            window,
 3560            cx,
 3561        );
 3562        cx.spawn_in(window, async move |this, cx| {
 3563            if let Some(paths) = paths.await.log_err().flatten() {
 3564                let results = this
 3565                    .update_in(cx, |this, window, cx| {
 3566                        this.open_paths(
 3567                            paths,
 3568                            OpenOptions {
 3569                                visible: Some(OpenVisible::All),
 3570                                ..Default::default()
 3571                            },
 3572                            None,
 3573                            window,
 3574                            cx,
 3575                        )
 3576                    })?
 3577                    .await;
 3578                for result in results.into_iter().flatten() {
 3579                    result.log_err();
 3580                }
 3581            }
 3582            anyhow::Ok(())
 3583        })
 3584        .detach_and_log_err(cx);
 3585    }
 3586
 3587    pub fn project_path_for_path(
 3588        project: Entity<Project>,
 3589        abs_path: &Path,
 3590        visible: bool,
 3591        cx: &mut App,
 3592    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 3593        let entry = project.update(cx, |project, cx| {
 3594            project.find_or_create_worktree(abs_path, visible, cx)
 3595        });
 3596        cx.spawn(async move |cx| {
 3597            let (worktree, path) = entry.await?;
 3598            let worktree_id = worktree.read_with(cx, |t, _| t.id());
 3599            Ok((worktree, ProjectPath { worktree_id, path }))
 3600        })
 3601    }
 3602
 3603    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 3604        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 3605    }
 3606
 3607    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 3608        self.items_of_type(cx).max_by_key(|item| item.item_id())
 3609    }
 3610
 3611    pub fn items_of_type<'a, T: Item>(
 3612        &'a self,
 3613        cx: &'a App,
 3614    ) -> impl 'a + Iterator<Item = Entity<T>> {
 3615        self.panes
 3616            .iter()
 3617            .flat_map(|pane| pane.read(cx).items_of_type())
 3618    }
 3619
 3620    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 3621        self.active_pane().read(cx).active_item()
 3622    }
 3623
 3624    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 3625        let item = self.active_item(cx)?;
 3626        item.to_any_view().downcast::<I>().ok()
 3627    }
 3628
 3629    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 3630        self.active_item(cx).and_then(|item| item.project_path(cx))
 3631    }
 3632
 3633    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 3634        self.recent_navigation_history_iter(cx)
 3635            .filter_map(|(path, abs_path)| {
 3636                let worktree = self
 3637                    .project
 3638                    .read(cx)
 3639                    .worktree_for_id(path.worktree_id, cx)?;
 3640                if worktree.read(cx).is_visible() {
 3641                    abs_path
 3642                } else {
 3643                    None
 3644                }
 3645            })
 3646            .next()
 3647    }
 3648
 3649    pub fn save_active_item(
 3650        &mut self,
 3651        save_intent: SaveIntent,
 3652        window: &mut Window,
 3653        cx: &mut App,
 3654    ) -> Task<Result<()>> {
 3655        let project = self.project.clone();
 3656        let pane = self.active_pane();
 3657        let item = pane.read(cx).active_item();
 3658        let pane = pane.downgrade();
 3659
 3660        window.spawn(cx, async move |cx| {
 3661            if let Some(item) = item {
 3662                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 3663                    .await
 3664                    .map(|_| ())
 3665            } else {
 3666                Ok(())
 3667            }
 3668        })
 3669    }
 3670
 3671    pub fn close_inactive_items_and_panes(
 3672        &mut self,
 3673        action: &CloseInactiveTabsAndPanes,
 3674        window: &mut Window,
 3675        cx: &mut Context<Self>,
 3676    ) {
 3677        if let Some(task) = self.close_all_internal(
 3678            true,
 3679            action.save_intent.unwrap_or(SaveIntent::Close),
 3680            window,
 3681            cx,
 3682        ) {
 3683            task.detach_and_log_err(cx)
 3684        }
 3685    }
 3686
 3687    pub fn close_all_items_and_panes(
 3688        &mut self,
 3689        action: &CloseAllItemsAndPanes,
 3690        window: &mut Window,
 3691        cx: &mut Context<Self>,
 3692    ) {
 3693        if let Some(task) = self.close_all_internal(
 3694            false,
 3695            action.save_intent.unwrap_or(SaveIntent::Close),
 3696            window,
 3697            cx,
 3698        ) {
 3699            task.detach_and_log_err(cx)
 3700        }
 3701    }
 3702
 3703    /// Closes the active item across all panes.
 3704    pub fn close_item_in_all_panes(
 3705        &mut self,
 3706        action: &CloseItemInAllPanes,
 3707        window: &mut Window,
 3708        cx: &mut Context<Self>,
 3709    ) {
 3710        let Some(active_item) = self.active_pane().read(cx).active_item() else {
 3711            return;
 3712        };
 3713
 3714        let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
 3715        let close_pinned = action.close_pinned;
 3716
 3717        if let Some(project_path) = active_item.project_path(cx) {
 3718            self.close_items_with_project_path(
 3719                &project_path,
 3720                save_intent,
 3721                close_pinned,
 3722                window,
 3723                cx,
 3724            );
 3725        } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
 3726            let item_id = active_item.item_id();
 3727            self.active_pane().update(cx, |pane, cx| {
 3728                pane.close_item_by_id(item_id, save_intent, window, cx)
 3729                    .detach_and_log_err(cx);
 3730            });
 3731        }
 3732    }
 3733
 3734    /// Closes all items with the given project path across all panes.
 3735    pub fn close_items_with_project_path(
 3736        &mut self,
 3737        project_path: &ProjectPath,
 3738        save_intent: SaveIntent,
 3739        close_pinned: bool,
 3740        window: &mut Window,
 3741        cx: &mut Context<Self>,
 3742    ) {
 3743        let panes = self.panes().to_vec();
 3744        for pane in panes {
 3745            pane.update(cx, |pane, cx| {
 3746                pane.close_items_for_project_path(
 3747                    project_path,
 3748                    save_intent,
 3749                    close_pinned,
 3750                    window,
 3751                    cx,
 3752                )
 3753                .detach_and_log_err(cx);
 3754            });
 3755        }
 3756    }
 3757
 3758    fn close_all_internal(
 3759        &mut self,
 3760        retain_active_pane: bool,
 3761        save_intent: SaveIntent,
 3762        window: &mut Window,
 3763        cx: &mut Context<Self>,
 3764    ) -> Option<Task<Result<()>>> {
 3765        let current_pane = self.active_pane();
 3766
 3767        let mut tasks = Vec::new();
 3768
 3769        if retain_active_pane {
 3770            let current_pane_close = current_pane.update(cx, |pane, cx| {
 3771                pane.close_other_items(
 3772                    &CloseOtherItems {
 3773                        save_intent: None,
 3774                        close_pinned: false,
 3775                    },
 3776                    None,
 3777                    window,
 3778                    cx,
 3779                )
 3780            });
 3781
 3782            tasks.push(current_pane_close);
 3783        }
 3784
 3785        for pane in self.panes() {
 3786            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3787                continue;
 3788            }
 3789
 3790            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3791                pane.close_all_items(
 3792                    &CloseAllItems {
 3793                        save_intent: Some(save_intent),
 3794                        close_pinned: false,
 3795                    },
 3796                    window,
 3797                    cx,
 3798                )
 3799            });
 3800
 3801            tasks.push(close_pane_items)
 3802        }
 3803
 3804        if tasks.is_empty() {
 3805            None
 3806        } else {
 3807            Some(cx.spawn_in(window, async move |_, _| {
 3808                for task in tasks {
 3809                    task.await?
 3810                }
 3811                Ok(())
 3812            }))
 3813        }
 3814    }
 3815
 3816    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3817        self.dock_at_position(position).read(cx).is_open()
 3818    }
 3819
 3820    pub fn toggle_dock(
 3821        &mut self,
 3822        dock_side: DockPosition,
 3823        window: &mut Window,
 3824        cx: &mut Context<Self>,
 3825    ) {
 3826        let mut focus_center = false;
 3827        let mut reveal_dock = false;
 3828
 3829        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3830        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3831
 3832        if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
 3833            telemetry::event!(
 3834                "Panel Button Clicked",
 3835                name = panel.persistent_name(),
 3836                toggle_state = !was_visible
 3837            );
 3838        }
 3839        if was_visible {
 3840            self.save_open_dock_positions(cx);
 3841        }
 3842
 3843        let dock = self.dock_at_position(dock_side);
 3844        dock.update(cx, |dock, cx| {
 3845            dock.set_open(!was_visible, window, cx);
 3846
 3847            if dock.active_panel().is_none() {
 3848                let Some(panel_ix) = dock
 3849                    .first_enabled_panel_idx(cx)
 3850                    .log_with_level(log::Level::Info)
 3851                else {
 3852                    return;
 3853                };
 3854                dock.activate_panel(panel_ix, window, cx);
 3855            }
 3856
 3857            if let Some(active_panel) = dock.active_panel() {
 3858                if was_visible {
 3859                    if active_panel
 3860                        .panel_focus_handle(cx)
 3861                        .contains_focused(window, cx)
 3862                    {
 3863                        focus_center = true;
 3864                    }
 3865                } else {
 3866                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3867                    window.focus(focus_handle, cx);
 3868                    reveal_dock = true;
 3869                }
 3870            }
 3871        });
 3872
 3873        if reveal_dock {
 3874            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3875        }
 3876
 3877        if focus_center {
 3878            self.active_pane
 3879                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 3880        }
 3881
 3882        cx.notify();
 3883        self.serialize_workspace(window, cx);
 3884    }
 3885
 3886    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3887        self.all_docks().into_iter().find(|&dock| {
 3888            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3889        })
 3890    }
 3891
 3892    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3893        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3894            self.save_open_dock_positions(cx);
 3895            dock.update(cx, |dock, cx| {
 3896                dock.set_open(false, window, cx);
 3897            });
 3898            return true;
 3899        }
 3900        false
 3901    }
 3902
 3903    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3904        self.save_open_dock_positions(cx);
 3905        for dock in self.all_docks() {
 3906            dock.update(cx, |dock, cx| {
 3907                dock.set_open(false, window, cx);
 3908            });
 3909        }
 3910
 3911        cx.focus_self(window);
 3912        cx.notify();
 3913        self.serialize_workspace(window, cx);
 3914    }
 3915
 3916    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 3917        self.all_docks()
 3918            .into_iter()
 3919            .filter_map(|dock| {
 3920                let dock_ref = dock.read(cx);
 3921                if dock_ref.is_open() {
 3922                    Some(dock_ref.position())
 3923                } else {
 3924                    None
 3925                }
 3926            })
 3927            .collect()
 3928    }
 3929
 3930    /// Saves the positions of currently open docks.
 3931    ///
 3932    /// Updates `last_open_dock_positions` with positions of all currently open
 3933    /// docks, to later be restored by the 'Toggle All Docks' action.
 3934    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 3935        let open_dock_positions = self.get_open_dock_positions(cx);
 3936        if !open_dock_positions.is_empty() {
 3937            self.last_open_dock_positions = open_dock_positions;
 3938        }
 3939    }
 3940
 3941    /// Toggles all docks between open and closed states.
 3942    ///
 3943    /// If any docks are open, closes all and remembers their positions. If all
 3944    /// docks are closed, restores the last remembered dock configuration.
 3945    fn toggle_all_docks(
 3946        &mut self,
 3947        _: &ToggleAllDocks,
 3948        window: &mut Window,
 3949        cx: &mut Context<Self>,
 3950    ) {
 3951        let open_dock_positions = self.get_open_dock_positions(cx);
 3952
 3953        if !open_dock_positions.is_empty() {
 3954            self.close_all_docks(window, cx);
 3955        } else if !self.last_open_dock_positions.is_empty() {
 3956            self.restore_last_open_docks(window, cx);
 3957        }
 3958    }
 3959
 3960    /// Reopens docks from the most recently remembered configuration.
 3961    ///
 3962    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 3963    /// and clears the stored positions.
 3964    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3965        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 3966
 3967        for position in positions_to_open {
 3968            let dock = self.dock_at_position(position);
 3969            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 3970        }
 3971
 3972        cx.focus_self(window);
 3973        cx.notify();
 3974        self.serialize_workspace(window, cx);
 3975    }
 3976
 3977    /// Transfer focus to the panel of the given type.
 3978    pub fn focus_panel<T: Panel>(
 3979        &mut self,
 3980        window: &mut Window,
 3981        cx: &mut Context<Self>,
 3982    ) -> Option<Entity<T>> {
 3983        let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
 3984        panel.to_any().downcast().ok()
 3985    }
 3986
 3987    /// Focus the panel of the given type if it isn't already focused. If it is
 3988    /// already focused, then transfer focus back to the workspace center.
 3989    /// When the `close_panel_on_toggle` setting is enabled, also closes the
 3990    /// panel when transferring focus back to the center.
 3991    pub fn toggle_panel_focus<T: Panel>(
 3992        &mut self,
 3993        window: &mut Window,
 3994        cx: &mut Context<Self>,
 3995    ) -> bool {
 3996        let mut did_focus_panel = false;
 3997        self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
 3998            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 3999            did_focus_panel
 4000        });
 4001
 4002        if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
 4003            self.close_panel::<T>(window, cx);
 4004        }
 4005
 4006        telemetry::event!(
 4007            "Panel Button Clicked",
 4008            name = T::persistent_name(),
 4009            toggle_state = did_focus_panel
 4010        );
 4011
 4012        did_focus_panel
 4013    }
 4014
 4015    pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4016        if let Some(item) = self.active_item(cx) {
 4017            item.item_focus_handle(cx).focus(window, cx);
 4018        } else {
 4019            log::error!("Could not find a focus target when switching focus to the center panes",);
 4020        }
 4021    }
 4022
 4023    pub fn activate_panel_for_proto_id(
 4024        &mut self,
 4025        panel_id: PanelId,
 4026        window: &mut Window,
 4027        cx: &mut Context<Self>,
 4028    ) -> Option<Arc<dyn PanelHandle>> {
 4029        let mut panel = None;
 4030        for dock in self.all_docks() {
 4031            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 4032                panel = dock.update(cx, |dock, cx| {
 4033                    dock.activate_panel(panel_index, window, cx);
 4034                    dock.set_open(true, window, cx);
 4035                    dock.active_panel().cloned()
 4036                });
 4037                break;
 4038            }
 4039        }
 4040
 4041        if panel.is_some() {
 4042            cx.notify();
 4043            self.serialize_workspace(window, cx);
 4044        }
 4045
 4046        panel
 4047    }
 4048
 4049    /// Focus or unfocus the given panel type, depending on the given callback.
 4050    fn focus_or_unfocus_panel<T: Panel>(
 4051        &mut self,
 4052        window: &mut Window,
 4053        cx: &mut Context<Self>,
 4054        should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 4055    ) -> Option<Arc<dyn PanelHandle>> {
 4056        let mut result_panel = None;
 4057        let mut serialize = false;
 4058        for dock in self.all_docks() {
 4059            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4060                let mut focus_center = false;
 4061                let panel = dock.update(cx, |dock, cx| {
 4062                    dock.activate_panel(panel_index, window, cx);
 4063
 4064                    let panel = dock.active_panel().cloned();
 4065                    if let Some(panel) = panel.as_ref() {
 4066                        if should_focus(&**panel, window, cx) {
 4067                            dock.set_open(true, window, cx);
 4068                            panel.panel_focus_handle(cx).focus(window, cx);
 4069                        } else {
 4070                            focus_center = true;
 4071                        }
 4072                    }
 4073                    panel
 4074                });
 4075
 4076                if focus_center {
 4077                    self.active_pane
 4078                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4079                }
 4080
 4081                result_panel = panel;
 4082                serialize = true;
 4083                break;
 4084            }
 4085        }
 4086
 4087        if serialize {
 4088            self.serialize_workspace(window, cx);
 4089        }
 4090
 4091        cx.notify();
 4092        result_panel
 4093    }
 4094
 4095    /// Open the panel of the given type
 4096    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4097        for dock in self.all_docks() {
 4098            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 4099                dock.update(cx, |dock, cx| {
 4100                    dock.activate_panel(panel_index, window, cx);
 4101                    dock.set_open(true, window, cx);
 4102                });
 4103            }
 4104        }
 4105    }
 4106
 4107    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 4108        for dock in self.all_docks().iter() {
 4109            dock.update(cx, |dock, cx| {
 4110                if dock.panel::<T>().is_some() {
 4111                    dock.set_open(false, window, cx)
 4112                }
 4113            })
 4114        }
 4115    }
 4116
 4117    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 4118        self.all_docks()
 4119            .iter()
 4120            .find_map(|dock| dock.read(cx).panel::<T>())
 4121    }
 4122
 4123    fn dismiss_zoomed_items_to_reveal(
 4124        &mut self,
 4125        dock_to_reveal: Option<DockPosition>,
 4126        window: &mut Window,
 4127        cx: &mut Context<Self>,
 4128    ) {
 4129        // If a center pane is zoomed, unzoom it.
 4130        for pane in &self.panes {
 4131            if pane != &self.active_pane || dock_to_reveal.is_some() {
 4132                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4133            }
 4134        }
 4135
 4136        // If another dock is zoomed, hide it.
 4137        let mut focus_center = false;
 4138        for dock in self.all_docks() {
 4139            dock.update(cx, |dock, cx| {
 4140                if Some(dock.position()) != dock_to_reveal
 4141                    && let Some(panel) = dock.active_panel()
 4142                    && panel.is_zoomed(window, cx)
 4143                {
 4144                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 4145                    dock.set_open(false, window, cx);
 4146                }
 4147            });
 4148        }
 4149
 4150        if focus_center {
 4151            self.active_pane
 4152                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
 4153        }
 4154
 4155        if self.zoomed_position != dock_to_reveal {
 4156            self.zoomed = None;
 4157            self.zoomed_position = None;
 4158            cx.emit(Event::ZoomChanged);
 4159        }
 4160
 4161        cx.notify();
 4162    }
 4163
 4164    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4165        let pane = cx.new(|cx| {
 4166            let mut pane = Pane::new(
 4167                self.weak_handle(),
 4168                self.project.clone(),
 4169                self.pane_history_timestamp.clone(),
 4170                None,
 4171                NewFile.boxed_clone(),
 4172                true,
 4173                window,
 4174                cx,
 4175            );
 4176            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 4177            pane
 4178        });
 4179        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 4180            .detach();
 4181        self.panes.push(pane.clone());
 4182
 4183        window.focus(&pane.focus_handle(cx), cx);
 4184
 4185        cx.emit(Event::PaneAdded(pane.clone()));
 4186        pane
 4187    }
 4188
 4189    pub fn add_item_to_center(
 4190        &mut self,
 4191        item: Box<dyn ItemHandle>,
 4192        window: &mut Window,
 4193        cx: &mut Context<Self>,
 4194    ) -> bool {
 4195        if let Some(center_pane) = self.last_active_center_pane.clone() {
 4196            if let Some(center_pane) = center_pane.upgrade() {
 4197                center_pane.update(cx, |pane, cx| {
 4198                    pane.add_item(item, true, true, None, window, cx)
 4199                });
 4200                true
 4201            } else {
 4202                false
 4203            }
 4204        } else {
 4205            false
 4206        }
 4207    }
 4208
 4209    pub fn add_item_to_active_pane(
 4210        &mut self,
 4211        item: Box<dyn ItemHandle>,
 4212        destination_index: Option<usize>,
 4213        focus_item: bool,
 4214        window: &mut Window,
 4215        cx: &mut App,
 4216    ) {
 4217        self.add_item(
 4218            self.active_pane.clone(),
 4219            item,
 4220            destination_index,
 4221            false,
 4222            focus_item,
 4223            window,
 4224            cx,
 4225        )
 4226    }
 4227
 4228    pub fn add_item(
 4229        &mut self,
 4230        pane: Entity<Pane>,
 4231        item: Box<dyn ItemHandle>,
 4232        destination_index: Option<usize>,
 4233        activate_pane: bool,
 4234        focus_item: bool,
 4235        window: &mut Window,
 4236        cx: &mut App,
 4237    ) {
 4238        pane.update(cx, |pane, cx| {
 4239            pane.add_item(
 4240                item,
 4241                activate_pane,
 4242                focus_item,
 4243                destination_index,
 4244                window,
 4245                cx,
 4246            )
 4247        });
 4248    }
 4249
 4250    pub fn split_item(
 4251        &mut self,
 4252        split_direction: SplitDirection,
 4253        item: Box<dyn ItemHandle>,
 4254        window: &mut Window,
 4255        cx: &mut Context<Self>,
 4256    ) {
 4257        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 4258        self.add_item(new_pane, item, None, true, true, window, cx);
 4259    }
 4260
 4261    pub fn open_abs_path(
 4262        &mut self,
 4263        abs_path: PathBuf,
 4264        options: OpenOptions,
 4265        window: &mut Window,
 4266        cx: &mut Context<Self>,
 4267    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4268        cx.spawn_in(window, async move |workspace, cx| {
 4269            let open_paths_task_result = workspace
 4270                .update_in(cx, |workspace, window, cx| {
 4271                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 4272                })
 4273                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 4274                .await;
 4275            anyhow::ensure!(
 4276                open_paths_task_result.len() == 1,
 4277                "open abs path {abs_path:?} task returned incorrect number of results"
 4278            );
 4279            match open_paths_task_result
 4280                .into_iter()
 4281                .next()
 4282                .expect("ensured single task result")
 4283            {
 4284                Some(open_result) => {
 4285                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 4286                }
 4287                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 4288            }
 4289        })
 4290    }
 4291
 4292    pub fn split_abs_path(
 4293        &mut self,
 4294        abs_path: PathBuf,
 4295        visible: bool,
 4296        window: &mut Window,
 4297        cx: &mut Context<Self>,
 4298    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4299        let project_path_task =
 4300            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 4301        cx.spawn_in(window, async move |this, cx| {
 4302            let (_, path) = project_path_task.await?;
 4303            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 4304                .await
 4305        })
 4306    }
 4307
 4308    pub fn open_path(
 4309        &mut self,
 4310        path: impl Into<ProjectPath>,
 4311        pane: Option<WeakEntity<Pane>>,
 4312        focus_item: bool,
 4313        window: &mut Window,
 4314        cx: &mut App,
 4315    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4316        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 4317    }
 4318
 4319    pub fn open_path_preview(
 4320        &mut self,
 4321        path: impl Into<ProjectPath>,
 4322        pane: Option<WeakEntity<Pane>>,
 4323        focus_item: bool,
 4324        allow_preview: bool,
 4325        activate: bool,
 4326        window: &mut Window,
 4327        cx: &mut App,
 4328    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4329        let pane = pane.unwrap_or_else(|| {
 4330            self.last_active_center_pane.clone().unwrap_or_else(|| {
 4331                self.panes
 4332                    .first()
 4333                    .expect("There must be an active pane")
 4334                    .downgrade()
 4335            })
 4336        });
 4337
 4338        let project_path = path.into();
 4339        let task = self.load_path(project_path.clone(), window, cx);
 4340        window.spawn(cx, async move |cx| {
 4341            let (project_entry_id, build_item) = task.await?;
 4342
 4343            pane.update_in(cx, |pane, window, cx| {
 4344                pane.open_item(
 4345                    project_entry_id,
 4346                    project_path,
 4347                    focus_item,
 4348                    allow_preview,
 4349                    activate,
 4350                    None,
 4351                    window,
 4352                    cx,
 4353                    build_item,
 4354                )
 4355            })
 4356        })
 4357    }
 4358
 4359    pub fn split_path(
 4360        &mut self,
 4361        path: impl Into<ProjectPath>,
 4362        window: &mut Window,
 4363        cx: &mut Context<Self>,
 4364    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4365        self.split_path_preview(path, false, None, window, cx)
 4366    }
 4367
 4368    pub fn split_path_preview(
 4369        &mut self,
 4370        path: impl Into<ProjectPath>,
 4371        allow_preview: bool,
 4372        split_direction: Option<SplitDirection>,
 4373        window: &mut Window,
 4374        cx: &mut Context<Self>,
 4375    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 4376        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 4377            self.panes
 4378                .first()
 4379                .expect("There must be an active pane")
 4380                .downgrade()
 4381        });
 4382
 4383        if let Member::Pane(center_pane) = &self.center.root
 4384            && center_pane.read(cx).items_len() == 0
 4385        {
 4386            return self.open_path(path, Some(pane), true, window, cx);
 4387        }
 4388
 4389        let project_path = path.into();
 4390        let task = self.load_path(project_path.clone(), window, cx);
 4391        cx.spawn_in(window, async move |this, cx| {
 4392            let (project_entry_id, build_item) = task.await?;
 4393            this.update_in(cx, move |this, window, cx| -> Option<_> {
 4394                let pane = pane.upgrade()?;
 4395                let new_pane = this.split_pane(
 4396                    pane,
 4397                    split_direction.unwrap_or(SplitDirection::Right),
 4398                    window,
 4399                    cx,
 4400                );
 4401                new_pane.update(cx, |new_pane, cx| {
 4402                    Some(new_pane.open_item(
 4403                        project_entry_id,
 4404                        project_path,
 4405                        true,
 4406                        allow_preview,
 4407                        true,
 4408                        None,
 4409                        window,
 4410                        cx,
 4411                        build_item,
 4412                    ))
 4413                })
 4414            })
 4415            .map(|option| option.context("pane was dropped"))?
 4416        })
 4417    }
 4418
 4419    fn load_path(
 4420        &mut self,
 4421        path: ProjectPath,
 4422        window: &mut Window,
 4423        cx: &mut App,
 4424    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 4425        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 4426        registry.open_path(self.project(), &path, window, cx)
 4427    }
 4428
 4429    pub fn find_project_item<T>(
 4430        &self,
 4431        pane: &Entity<Pane>,
 4432        project_item: &Entity<T::Item>,
 4433        cx: &App,
 4434    ) -> Option<Entity<T>>
 4435    where
 4436        T: ProjectItem,
 4437    {
 4438        use project::ProjectItem as _;
 4439        let project_item = project_item.read(cx);
 4440        let entry_id = project_item.entry_id(cx);
 4441        let project_path = project_item.project_path(cx);
 4442
 4443        let mut item = None;
 4444        if let Some(entry_id) = entry_id {
 4445            item = pane.read(cx).item_for_entry(entry_id, cx);
 4446        }
 4447        if item.is_none()
 4448            && let Some(project_path) = project_path
 4449        {
 4450            item = pane.read(cx).item_for_path(project_path, cx);
 4451        }
 4452
 4453        item.and_then(|item| item.downcast::<T>())
 4454    }
 4455
 4456    pub fn is_project_item_open<T>(
 4457        &self,
 4458        pane: &Entity<Pane>,
 4459        project_item: &Entity<T::Item>,
 4460        cx: &App,
 4461    ) -> bool
 4462    where
 4463        T: ProjectItem,
 4464    {
 4465        self.find_project_item::<T>(pane, project_item, cx)
 4466            .is_some()
 4467    }
 4468
 4469    pub fn open_project_item<T>(
 4470        &mut self,
 4471        pane: Entity<Pane>,
 4472        project_item: Entity<T::Item>,
 4473        activate_pane: bool,
 4474        focus_item: bool,
 4475        keep_old_preview: bool,
 4476        allow_new_preview: bool,
 4477        window: &mut Window,
 4478        cx: &mut Context<Self>,
 4479    ) -> Entity<T>
 4480    where
 4481        T: ProjectItem,
 4482    {
 4483        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 4484
 4485        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 4486            if !keep_old_preview
 4487                && let Some(old_id) = old_item_id
 4488                && old_id != item.item_id()
 4489            {
 4490                // switching to a different item, so unpreview old active item
 4491                pane.update(cx, |pane, _| {
 4492                    pane.unpreview_item_if_preview(old_id);
 4493                });
 4494            }
 4495
 4496            self.activate_item(&item, activate_pane, focus_item, window, cx);
 4497            if !allow_new_preview {
 4498                pane.update(cx, |pane, _| {
 4499                    pane.unpreview_item_if_preview(item.item_id());
 4500                });
 4501            }
 4502            return item;
 4503        }
 4504
 4505        let item = pane.update(cx, |pane, cx| {
 4506            cx.new(|cx| {
 4507                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 4508            })
 4509        });
 4510        let mut destination_index = None;
 4511        pane.update(cx, |pane, cx| {
 4512            if !keep_old_preview && let Some(old_id) = old_item_id {
 4513                pane.unpreview_item_if_preview(old_id);
 4514            }
 4515            if allow_new_preview {
 4516                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 4517            }
 4518        });
 4519
 4520        self.add_item(
 4521            pane,
 4522            Box::new(item.clone()),
 4523            destination_index,
 4524            activate_pane,
 4525            focus_item,
 4526            window,
 4527            cx,
 4528        );
 4529        item
 4530    }
 4531
 4532    pub fn open_shared_screen(
 4533        &mut self,
 4534        peer_id: PeerId,
 4535        window: &mut Window,
 4536        cx: &mut Context<Self>,
 4537    ) {
 4538        if let Some(shared_screen) =
 4539            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 4540        {
 4541            self.active_pane.update(cx, |pane, cx| {
 4542                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 4543            });
 4544        }
 4545    }
 4546
 4547    pub fn activate_item(
 4548        &mut self,
 4549        item: &dyn ItemHandle,
 4550        activate_pane: bool,
 4551        focus_item: bool,
 4552        window: &mut Window,
 4553        cx: &mut App,
 4554    ) -> bool {
 4555        let result = self.panes.iter().find_map(|pane| {
 4556            pane.read(cx)
 4557                .index_for_item(item)
 4558                .map(|ix| (pane.clone(), ix))
 4559        });
 4560        if let Some((pane, ix)) = result {
 4561            pane.update(cx, |pane, cx| {
 4562                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 4563            });
 4564            true
 4565        } else {
 4566            false
 4567        }
 4568    }
 4569
 4570    fn activate_pane_at_index(
 4571        &mut self,
 4572        action: &ActivatePane,
 4573        window: &mut Window,
 4574        cx: &mut Context<Self>,
 4575    ) {
 4576        let panes = self.center.panes();
 4577        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 4578            window.focus(&pane.focus_handle(cx), cx);
 4579        } else {
 4580            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4581                .detach();
 4582        }
 4583    }
 4584
 4585    fn move_item_to_pane_at_index(
 4586        &mut self,
 4587        action: &MoveItemToPane,
 4588        window: &mut Window,
 4589        cx: &mut Context<Self>,
 4590    ) {
 4591        let panes = self.center.panes();
 4592        let destination = match panes.get(action.destination) {
 4593            Some(&destination) => destination.clone(),
 4594            None => {
 4595                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4596                    return;
 4597                }
 4598                let direction = SplitDirection::Right;
 4599                let split_off_pane = self
 4600                    .find_pane_in_direction(direction, cx)
 4601                    .unwrap_or_else(|| self.active_pane.clone());
 4602                let new_pane = self.add_pane(window, cx);
 4603                self.center.split(&split_off_pane, &new_pane, direction, cx);
 4604                new_pane
 4605            }
 4606        };
 4607
 4608        if action.clone {
 4609            if self
 4610                .active_pane
 4611                .read(cx)
 4612                .active_item()
 4613                .is_some_and(|item| item.can_split(cx))
 4614            {
 4615                clone_active_item(
 4616                    self.database_id(),
 4617                    &self.active_pane,
 4618                    &destination,
 4619                    action.focus,
 4620                    window,
 4621                    cx,
 4622                );
 4623                return;
 4624            }
 4625        }
 4626        move_active_item(
 4627            &self.active_pane,
 4628            &destination,
 4629            action.focus,
 4630            true,
 4631            window,
 4632            cx,
 4633        )
 4634    }
 4635
 4636    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 4637        let panes = self.center.panes();
 4638        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4639            let next_ix = (ix + 1) % panes.len();
 4640            let next_pane = panes[next_ix].clone();
 4641            window.focus(&next_pane.focus_handle(cx), cx);
 4642        }
 4643    }
 4644
 4645    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 4646        let panes = self.center.panes();
 4647        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 4648            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 4649            let prev_pane = panes[prev_ix].clone();
 4650            window.focus(&prev_pane.focus_handle(cx), cx);
 4651        }
 4652    }
 4653
 4654    pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
 4655        let last_pane = self.center.last_pane();
 4656        window.focus(&last_pane.focus_handle(cx), cx);
 4657    }
 4658
 4659    pub fn activate_pane_in_direction(
 4660        &mut self,
 4661        direction: SplitDirection,
 4662        window: &mut Window,
 4663        cx: &mut App,
 4664    ) {
 4665        use ActivateInDirectionTarget as Target;
 4666        enum Origin {
 4667            Sidebar,
 4668            LeftDock,
 4669            RightDock,
 4670            BottomDock,
 4671            Center,
 4672        }
 4673
 4674        let origin: Origin = if self
 4675            .sidebar_focus_handle
 4676            .as_ref()
 4677            .is_some_and(|h| h.contains_focused(window, cx))
 4678        {
 4679            Origin::Sidebar
 4680        } else {
 4681            [
 4682                (&self.left_dock, Origin::LeftDock),
 4683                (&self.right_dock, Origin::RightDock),
 4684                (&self.bottom_dock, Origin::BottomDock),
 4685            ]
 4686            .into_iter()
 4687            .find_map(|(dock, origin)| {
 4688                if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 4689                    Some(origin)
 4690                } else {
 4691                    None
 4692                }
 4693            })
 4694            .unwrap_or(Origin::Center)
 4695        };
 4696
 4697        let get_last_active_pane = || {
 4698            let pane = self
 4699                .last_active_center_pane
 4700                .clone()
 4701                .unwrap_or_else(|| {
 4702                    self.panes
 4703                        .first()
 4704                        .expect("There must be an active pane")
 4705                        .downgrade()
 4706                })
 4707                .upgrade()?;
 4708            (pane.read(cx).items_len() != 0).then_some(pane)
 4709        };
 4710
 4711        let try_dock =
 4712            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 4713
 4714        let sidebar_target = self
 4715            .sidebar_focus_handle
 4716            .as_ref()
 4717            .map(|h| Target::Sidebar(h.clone()));
 4718
 4719        let target = match (origin, direction) {
 4720            // From the sidebar, only Right navigates into the workspace.
 4721            (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
 4722                .or_else(|| get_last_active_pane().map(Target::Pane))
 4723                .or_else(|| try_dock(&self.bottom_dock))
 4724                .or_else(|| try_dock(&self.right_dock)),
 4725
 4726            (Origin::Sidebar, _) => None,
 4727
 4728            // We're in the center, so we first try to go to a different pane,
 4729            // otherwise try to go to a dock.
 4730            (Origin::Center, direction) => {
 4731                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 4732                    Some(Target::Pane(pane))
 4733                } else {
 4734                    match direction {
 4735                        SplitDirection::Up => None,
 4736                        SplitDirection::Down => try_dock(&self.bottom_dock),
 4737                        SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
 4738                        SplitDirection::Right => try_dock(&self.right_dock),
 4739                    }
 4740                }
 4741            }
 4742
 4743            (Origin::LeftDock, SplitDirection::Right) => {
 4744                if let Some(last_active_pane) = get_last_active_pane() {
 4745                    Some(Target::Pane(last_active_pane))
 4746                } else {
 4747                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 4748                }
 4749            }
 4750
 4751            (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
 4752
 4753            (Origin::LeftDock, SplitDirection::Down)
 4754            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 4755
 4756            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 4757            (Origin::BottomDock, SplitDirection::Left) => {
 4758                try_dock(&self.left_dock).or(sidebar_target)
 4759            }
 4760            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 4761
 4762            (Origin::RightDock, SplitDirection::Left) => {
 4763                if let Some(last_active_pane) = get_last_active_pane() {
 4764                    Some(Target::Pane(last_active_pane))
 4765                } else {
 4766                    try_dock(&self.bottom_dock)
 4767                        .or_else(|| try_dock(&self.left_dock))
 4768                        .or(sidebar_target)
 4769                }
 4770            }
 4771
 4772            _ => None,
 4773        };
 4774
 4775        match target {
 4776            Some(ActivateInDirectionTarget::Pane(pane)) => {
 4777                let pane = pane.read(cx);
 4778                if let Some(item) = pane.active_item() {
 4779                    item.item_focus_handle(cx).focus(window, cx);
 4780                } else {
 4781                    log::error!(
 4782                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 4783                    );
 4784                }
 4785            }
 4786            Some(ActivateInDirectionTarget::Dock(dock)) => {
 4787                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 4788                window.defer(cx, move |window, cx| {
 4789                    let dock = dock.read(cx);
 4790                    if let Some(panel) = dock.active_panel() {
 4791                        panel.panel_focus_handle(cx).focus(window, cx);
 4792                    } else {
 4793                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 4794                    }
 4795                })
 4796            }
 4797            Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
 4798                focus_handle.focus(window, cx);
 4799            }
 4800            None => {}
 4801        }
 4802    }
 4803
 4804    pub fn move_item_to_pane_in_direction(
 4805        &mut self,
 4806        action: &MoveItemToPaneInDirection,
 4807        window: &mut Window,
 4808        cx: &mut Context<Self>,
 4809    ) {
 4810        let destination = match self.find_pane_in_direction(action.direction, cx) {
 4811            Some(destination) => destination,
 4812            None => {
 4813                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 4814                    return;
 4815                }
 4816                let new_pane = self.add_pane(window, cx);
 4817                self.center
 4818                    .split(&self.active_pane, &new_pane, action.direction, cx);
 4819                new_pane
 4820            }
 4821        };
 4822
 4823        if action.clone {
 4824            if self
 4825                .active_pane
 4826                .read(cx)
 4827                .active_item()
 4828                .is_some_and(|item| item.can_split(cx))
 4829            {
 4830                clone_active_item(
 4831                    self.database_id(),
 4832                    &self.active_pane,
 4833                    &destination,
 4834                    action.focus,
 4835                    window,
 4836                    cx,
 4837                );
 4838                return;
 4839            }
 4840        }
 4841        move_active_item(
 4842            &self.active_pane,
 4843            &destination,
 4844            action.focus,
 4845            true,
 4846            window,
 4847            cx,
 4848        );
 4849    }
 4850
 4851    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4852        self.center.bounding_box_for_pane(pane)
 4853    }
 4854
 4855    pub fn find_pane_in_direction(
 4856        &mut self,
 4857        direction: SplitDirection,
 4858        cx: &App,
 4859    ) -> Option<Entity<Pane>> {
 4860        self.center
 4861            .find_pane_in_direction(&self.active_pane, direction, cx)
 4862            .cloned()
 4863    }
 4864
 4865    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4866        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4867            self.center.swap(&self.active_pane, &to, cx);
 4868            cx.notify();
 4869        }
 4870    }
 4871
 4872    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4873        if self
 4874            .center
 4875            .move_to_border(&self.active_pane, direction, cx)
 4876            .unwrap()
 4877        {
 4878            cx.notify();
 4879        }
 4880    }
 4881
 4882    pub fn resize_pane(
 4883        &mut self,
 4884        axis: gpui::Axis,
 4885        amount: Pixels,
 4886        window: &mut Window,
 4887        cx: &mut Context<Self>,
 4888    ) {
 4889        let docks = self.all_docks();
 4890        let active_dock = docks
 4891            .into_iter()
 4892            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4893
 4894        if let Some(dock_entity) = active_dock {
 4895            let dock = dock_entity.read(cx);
 4896            let Some(panel_size) = dock
 4897                .active_panel()
 4898                .map(|panel| self.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx))
 4899            else {
 4900                return;
 4901            };
 4902            match dock.position() {
 4903                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4904                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4905                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4906            }
 4907        } else {
 4908            self.center
 4909                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 4910        }
 4911        cx.notify();
 4912    }
 4913
 4914    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 4915        self.center.reset_pane_sizes(cx);
 4916        cx.notify();
 4917    }
 4918
 4919    fn handle_pane_focused(
 4920        &mut self,
 4921        pane: Entity<Pane>,
 4922        window: &mut Window,
 4923        cx: &mut Context<Self>,
 4924    ) {
 4925        // This is explicitly hoisted out of the following check for pane identity as
 4926        // terminal panel panes are not registered as a center panes.
 4927        self.status_bar.update(cx, |status_bar, cx| {
 4928            status_bar.set_active_pane(&pane, window, cx);
 4929        });
 4930        if self.active_pane != pane {
 4931            self.set_active_pane(&pane, window, cx);
 4932        }
 4933
 4934        if self.last_active_center_pane.is_none() {
 4935            self.last_active_center_pane = Some(pane.downgrade());
 4936        }
 4937
 4938        // If this pane is in a dock, preserve that dock when dismissing zoomed items.
 4939        // This prevents the dock from closing when focus events fire during window activation.
 4940        // We also preserve any dock whose active panel itself has focus — this covers
 4941        // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
 4942        let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
 4943            let dock_read = dock.read(cx);
 4944            if let Some(panel) = dock_read.active_panel() {
 4945                if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
 4946                    || panel.panel_focus_handle(cx).contains_focused(window, cx)
 4947                {
 4948                    return Some(dock_read.position());
 4949                }
 4950            }
 4951            None
 4952        });
 4953
 4954        self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
 4955        if pane.read(cx).is_zoomed() {
 4956            self.zoomed = Some(pane.downgrade().into());
 4957        } else {
 4958            self.zoomed = None;
 4959        }
 4960        self.zoomed_position = None;
 4961        cx.emit(Event::ZoomChanged);
 4962        self.update_active_view_for_followers(window, cx);
 4963        pane.update(cx, |pane, _| {
 4964            pane.track_alternate_file_items();
 4965        });
 4966
 4967        cx.notify();
 4968    }
 4969
 4970    fn set_active_pane(
 4971        &mut self,
 4972        pane: &Entity<Pane>,
 4973        window: &mut Window,
 4974        cx: &mut Context<Self>,
 4975    ) {
 4976        self.active_pane = pane.clone();
 4977        self.active_item_path_changed(true, window, cx);
 4978        self.last_active_center_pane = Some(pane.downgrade());
 4979    }
 4980
 4981    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4982        self.update_active_view_for_followers(window, cx);
 4983    }
 4984
 4985    fn handle_pane_event(
 4986        &mut self,
 4987        pane: &Entity<Pane>,
 4988        event: &pane::Event,
 4989        window: &mut Window,
 4990        cx: &mut Context<Self>,
 4991    ) {
 4992        let mut serialize_workspace = true;
 4993        match event {
 4994            pane::Event::AddItem { item } => {
 4995                item.added_to_pane(self, pane.clone(), window, cx);
 4996                cx.emit(Event::ItemAdded {
 4997                    item: item.boxed_clone(),
 4998                });
 4999            }
 5000            pane::Event::Split { direction, mode } => {
 5001                match mode {
 5002                    SplitMode::ClonePane => {
 5003                        self.split_and_clone(pane.clone(), *direction, window, cx)
 5004                            .detach();
 5005                    }
 5006                    SplitMode::EmptyPane => {
 5007                        self.split_pane(pane.clone(), *direction, window, cx);
 5008                    }
 5009                    SplitMode::MovePane => {
 5010                        self.split_and_move(pane.clone(), *direction, window, cx);
 5011                    }
 5012                };
 5013            }
 5014            pane::Event::JoinIntoNext => {
 5015                self.join_pane_into_next(pane.clone(), window, cx);
 5016            }
 5017            pane::Event::JoinAll => {
 5018                self.join_all_panes(window, cx);
 5019            }
 5020            pane::Event::Remove { focus_on_pane } => {
 5021                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 5022            }
 5023            pane::Event::ActivateItem {
 5024                local,
 5025                focus_changed,
 5026            } => {
 5027                window.invalidate_character_coordinates();
 5028
 5029                pane.update(cx, |pane, _| {
 5030                    pane.track_alternate_file_items();
 5031                });
 5032                if *local {
 5033                    self.unfollow_in_pane(pane, window, cx);
 5034                }
 5035                serialize_workspace = *focus_changed || pane != self.active_pane();
 5036                if pane == self.active_pane() {
 5037                    self.active_item_path_changed(*focus_changed, window, cx);
 5038                    self.update_active_view_for_followers(window, cx);
 5039                } else if *local {
 5040                    self.set_active_pane(pane, window, cx);
 5041                }
 5042            }
 5043            pane::Event::UserSavedItem { item, save_intent } => {
 5044                cx.emit(Event::UserSavedItem {
 5045                    pane: pane.downgrade(),
 5046                    item: item.boxed_clone(),
 5047                    save_intent: *save_intent,
 5048                });
 5049                serialize_workspace = false;
 5050            }
 5051            pane::Event::ChangeItemTitle => {
 5052                if *pane == self.active_pane {
 5053                    self.active_item_path_changed(false, window, cx);
 5054                }
 5055                serialize_workspace = false;
 5056            }
 5057            pane::Event::RemovedItem { item } => {
 5058                cx.emit(Event::ActiveItemChanged);
 5059                self.update_window_edited(window, cx);
 5060                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 5061                    && entry.get().entity_id() == pane.entity_id()
 5062                {
 5063                    entry.remove();
 5064                }
 5065                cx.emit(Event::ItemRemoved {
 5066                    item_id: item.item_id(),
 5067                });
 5068            }
 5069            pane::Event::Focus => {
 5070                window.invalidate_character_coordinates();
 5071                self.handle_pane_focused(pane.clone(), window, cx);
 5072            }
 5073            pane::Event::ZoomIn => {
 5074                if *pane == self.active_pane {
 5075                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 5076                    if pane.read(cx).has_focus(window, cx) {
 5077                        self.zoomed = Some(pane.downgrade().into());
 5078                        self.zoomed_position = None;
 5079                        cx.emit(Event::ZoomChanged);
 5080                    }
 5081                    cx.notify();
 5082                }
 5083            }
 5084            pane::Event::ZoomOut => {
 5085                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 5086                if self.zoomed_position.is_none() {
 5087                    self.zoomed = None;
 5088                    cx.emit(Event::ZoomChanged);
 5089                }
 5090                cx.notify();
 5091            }
 5092            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 5093        }
 5094
 5095        if serialize_workspace {
 5096            self.serialize_workspace(window, cx);
 5097        }
 5098    }
 5099
 5100    pub fn unfollow_in_pane(
 5101        &mut self,
 5102        pane: &Entity<Pane>,
 5103        window: &mut Window,
 5104        cx: &mut Context<Workspace>,
 5105    ) -> Option<CollaboratorId> {
 5106        let leader_id = self.leader_for_pane(pane)?;
 5107        self.unfollow(leader_id, window, cx);
 5108        Some(leader_id)
 5109    }
 5110
 5111    pub fn split_pane(
 5112        &mut self,
 5113        pane_to_split: Entity<Pane>,
 5114        split_direction: SplitDirection,
 5115        window: &mut Window,
 5116        cx: &mut Context<Self>,
 5117    ) -> Entity<Pane> {
 5118        let new_pane = self.add_pane(window, cx);
 5119        self.center
 5120            .split(&pane_to_split, &new_pane, split_direction, cx);
 5121        cx.notify();
 5122        new_pane
 5123    }
 5124
 5125    pub fn split_and_move(
 5126        &mut self,
 5127        pane: Entity<Pane>,
 5128        direction: SplitDirection,
 5129        window: &mut Window,
 5130        cx: &mut Context<Self>,
 5131    ) {
 5132        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 5133            return;
 5134        };
 5135        let new_pane = self.add_pane(window, cx);
 5136        new_pane.update(cx, |pane, cx| {
 5137            pane.add_item(item, true, true, None, window, cx)
 5138        });
 5139        self.center.split(&pane, &new_pane, direction, cx);
 5140        cx.notify();
 5141    }
 5142
 5143    pub fn split_and_clone(
 5144        &mut self,
 5145        pane: Entity<Pane>,
 5146        direction: SplitDirection,
 5147        window: &mut Window,
 5148        cx: &mut Context<Self>,
 5149    ) -> Task<Option<Entity<Pane>>> {
 5150        let Some(item) = pane.read(cx).active_item() else {
 5151            return Task::ready(None);
 5152        };
 5153        if !item.can_split(cx) {
 5154            return Task::ready(None);
 5155        }
 5156        let task = item.clone_on_split(self.database_id(), window, cx);
 5157        cx.spawn_in(window, async move |this, cx| {
 5158            if let Some(clone) = task.await {
 5159                this.update_in(cx, |this, window, cx| {
 5160                    let new_pane = this.add_pane(window, cx);
 5161                    let nav_history = pane.read(cx).fork_nav_history();
 5162                    new_pane.update(cx, |pane, cx| {
 5163                        pane.set_nav_history(nav_history, cx);
 5164                        pane.add_item(clone, true, true, None, window, cx)
 5165                    });
 5166                    this.center.split(&pane, &new_pane, direction, cx);
 5167                    cx.notify();
 5168                    new_pane
 5169                })
 5170                .ok()
 5171            } else {
 5172                None
 5173            }
 5174        })
 5175    }
 5176
 5177    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5178        let active_item = self.active_pane.read(cx).active_item();
 5179        for pane in &self.panes {
 5180            join_pane_into_active(&self.active_pane, pane, window, cx);
 5181        }
 5182        if let Some(active_item) = active_item {
 5183            self.activate_item(active_item.as_ref(), true, true, window, cx);
 5184        }
 5185        cx.notify();
 5186    }
 5187
 5188    pub fn join_pane_into_next(
 5189        &mut self,
 5190        pane: Entity<Pane>,
 5191        window: &mut Window,
 5192        cx: &mut Context<Self>,
 5193    ) {
 5194        let next_pane = self
 5195            .find_pane_in_direction(SplitDirection::Right, cx)
 5196            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 5197            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 5198            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 5199        let Some(next_pane) = next_pane else {
 5200            return;
 5201        };
 5202        move_all_items(&pane, &next_pane, window, cx);
 5203        cx.notify();
 5204    }
 5205
 5206    fn remove_pane(
 5207        &mut self,
 5208        pane: Entity<Pane>,
 5209        focus_on: Option<Entity<Pane>>,
 5210        window: &mut Window,
 5211        cx: &mut Context<Self>,
 5212    ) {
 5213        if self.center.remove(&pane, cx).unwrap() {
 5214            self.force_remove_pane(&pane, &focus_on, window, cx);
 5215            self.unfollow_in_pane(&pane, window, cx);
 5216            self.last_leaders_by_pane.remove(&pane.downgrade());
 5217            for removed_item in pane.read(cx).items() {
 5218                self.panes_by_item.remove(&removed_item.item_id());
 5219            }
 5220
 5221            cx.notify();
 5222        } else {
 5223            self.active_item_path_changed(true, window, cx);
 5224        }
 5225        cx.emit(Event::PaneRemoved);
 5226    }
 5227
 5228    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 5229        &mut self.panes
 5230    }
 5231
 5232    pub fn panes(&self) -> &[Entity<Pane>] {
 5233        &self.panes
 5234    }
 5235
 5236    pub fn active_pane(&self) -> &Entity<Pane> {
 5237        &self.active_pane
 5238    }
 5239
 5240    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 5241        for dock in self.all_docks() {
 5242            if dock.focus_handle(cx).contains_focused(window, cx)
 5243                && let Some(pane) = dock
 5244                    .read(cx)
 5245                    .active_panel()
 5246                    .and_then(|panel| panel.pane(cx))
 5247            {
 5248                return pane;
 5249            }
 5250        }
 5251        self.active_pane().clone()
 5252    }
 5253
 5254    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 5255        self.find_pane_in_direction(SplitDirection::Right, cx)
 5256            .unwrap_or_else(|| {
 5257                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 5258            })
 5259    }
 5260
 5261    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 5262        self.pane_for_item_id(handle.item_id())
 5263    }
 5264
 5265    pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
 5266        let weak_pane = self.panes_by_item.get(&item_id)?;
 5267        weak_pane.upgrade()
 5268    }
 5269
 5270    pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
 5271        self.panes
 5272            .iter()
 5273            .find(|pane| pane.entity_id() == entity_id)
 5274            .cloned()
 5275    }
 5276
 5277    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 5278        self.follower_states.retain(|leader_id, state| {
 5279            if *leader_id == CollaboratorId::PeerId(peer_id) {
 5280                for item in state.items_by_leader_view_id.values() {
 5281                    item.view.set_leader_id(None, window, cx);
 5282                }
 5283                false
 5284            } else {
 5285                true
 5286            }
 5287        });
 5288        cx.notify();
 5289    }
 5290
 5291    pub fn start_following(
 5292        &mut self,
 5293        leader_id: impl Into<CollaboratorId>,
 5294        window: &mut Window,
 5295        cx: &mut Context<Self>,
 5296    ) -> Option<Task<Result<()>>> {
 5297        let leader_id = leader_id.into();
 5298        let pane = self.active_pane().clone();
 5299
 5300        self.last_leaders_by_pane
 5301            .insert(pane.downgrade(), leader_id);
 5302        self.unfollow(leader_id, window, cx);
 5303        self.unfollow_in_pane(&pane, window, cx);
 5304        self.follower_states.insert(
 5305            leader_id,
 5306            FollowerState {
 5307                center_pane: pane.clone(),
 5308                dock_pane: None,
 5309                active_view_id: None,
 5310                items_by_leader_view_id: Default::default(),
 5311            },
 5312        );
 5313        cx.notify();
 5314
 5315        match leader_id {
 5316            CollaboratorId::PeerId(leader_peer_id) => {
 5317                let room_id = self.active_call()?.room_id(cx)?;
 5318                let project_id = self.project.read(cx).remote_id();
 5319                let request = self.app_state.client.request(proto::Follow {
 5320                    room_id,
 5321                    project_id,
 5322                    leader_id: Some(leader_peer_id),
 5323                });
 5324
 5325                Some(cx.spawn_in(window, async move |this, cx| {
 5326                    let response = request.await?;
 5327                    this.update(cx, |this, _| {
 5328                        let state = this
 5329                            .follower_states
 5330                            .get_mut(&leader_id)
 5331                            .context("following interrupted")?;
 5332                        state.active_view_id = response
 5333                            .active_view
 5334                            .as_ref()
 5335                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5336                        anyhow::Ok(())
 5337                    })??;
 5338                    if let Some(view) = response.active_view {
 5339                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 5340                    }
 5341                    this.update_in(cx, |this, window, cx| {
 5342                        this.leader_updated(leader_id, window, cx)
 5343                    })?;
 5344                    Ok(())
 5345                }))
 5346            }
 5347            CollaboratorId::Agent => {
 5348                self.leader_updated(leader_id, window, cx)?;
 5349                Some(Task::ready(Ok(())))
 5350            }
 5351        }
 5352    }
 5353
 5354    pub fn follow_next_collaborator(
 5355        &mut self,
 5356        _: &FollowNextCollaborator,
 5357        window: &mut Window,
 5358        cx: &mut Context<Self>,
 5359    ) {
 5360        let collaborators = self.project.read(cx).collaborators();
 5361        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 5362            let mut collaborators = collaborators.keys().copied();
 5363            for peer_id in collaborators.by_ref() {
 5364                if CollaboratorId::PeerId(peer_id) == leader_id {
 5365                    break;
 5366                }
 5367            }
 5368            collaborators.next().map(CollaboratorId::PeerId)
 5369        } else if let Some(last_leader_id) =
 5370            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 5371        {
 5372            match last_leader_id {
 5373                CollaboratorId::PeerId(peer_id) => {
 5374                    if collaborators.contains_key(peer_id) {
 5375                        Some(*last_leader_id)
 5376                    } else {
 5377                        None
 5378                    }
 5379                }
 5380                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 5381            }
 5382        } else {
 5383            None
 5384        };
 5385
 5386        let pane = self.active_pane.clone();
 5387        let Some(leader_id) = next_leader_id.or_else(|| {
 5388            Some(CollaboratorId::PeerId(
 5389                collaborators.keys().copied().next()?,
 5390            ))
 5391        }) else {
 5392            return;
 5393        };
 5394        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 5395            return;
 5396        }
 5397        if let Some(task) = self.start_following(leader_id, window, cx) {
 5398            task.detach_and_log_err(cx)
 5399        }
 5400    }
 5401
 5402    pub fn follow(
 5403        &mut self,
 5404        leader_id: impl Into<CollaboratorId>,
 5405        window: &mut Window,
 5406        cx: &mut Context<Self>,
 5407    ) {
 5408        let leader_id = leader_id.into();
 5409
 5410        if let CollaboratorId::PeerId(peer_id) = leader_id {
 5411            let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
 5412                return;
 5413            };
 5414            let Some(remote_participant) =
 5415                active_call.0.remote_participant_for_peer_id(peer_id, cx)
 5416            else {
 5417                return;
 5418            };
 5419
 5420            let project = self.project.read(cx);
 5421
 5422            let other_project_id = match remote_participant.location {
 5423                ParticipantLocation::External => None,
 5424                ParticipantLocation::UnsharedProject => None,
 5425                ParticipantLocation::SharedProject { project_id } => {
 5426                    if Some(project_id) == project.remote_id() {
 5427                        None
 5428                    } else {
 5429                        Some(project_id)
 5430                    }
 5431                }
 5432            };
 5433
 5434            // if they are active in another project, follow there.
 5435            if let Some(project_id) = other_project_id {
 5436                let app_state = self.app_state.clone();
 5437                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 5438                    .detach_and_log_err(cx);
 5439            }
 5440        }
 5441
 5442        // if you're already following, find the right pane and focus it.
 5443        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 5444            window.focus(&follower_state.pane().focus_handle(cx), cx);
 5445
 5446            return;
 5447        }
 5448
 5449        // Otherwise, follow.
 5450        if let Some(task) = self.start_following(leader_id, window, cx) {
 5451            task.detach_and_log_err(cx)
 5452        }
 5453    }
 5454
 5455    pub fn unfollow(
 5456        &mut self,
 5457        leader_id: impl Into<CollaboratorId>,
 5458        window: &mut Window,
 5459        cx: &mut Context<Self>,
 5460    ) -> Option<()> {
 5461        cx.notify();
 5462
 5463        let leader_id = leader_id.into();
 5464        let state = self.follower_states.remove(&leader_id)?;
 5465        for (_, item) in state.items_by_leader_view_id {
 5466            item.view.set_leader_id(None, window, cx);
 5467        }
 5468
 5469        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 5470            let project_id = self.project.read(cx).remote_id();
 5471            let room_id = self.active_call()?.room_id(cx)?;
 5472            self.app_state
 5473                .client
 5474                .send(proto::Unfollow {
 5475                    room_id,
 5476                    project_id,
 5477                    leader_id: Some(leader_peer_id),
 5478                })
 5479                .log_err();
 5480        }
 5481
 5482        Some(())
 5483    }
 5484
 5485    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 5486        self.follower_states.contains_key(&id.into())
 5487    }
 5488
 5489    fn active_item_path_changed(
 5490        &mut self,
 5491        focus_changed: bool,
 5492        window: &mut Window,
 5493        cx: &mut Context<Self>,
 5494    ) {
 5495        cx.emit(Event::ActiveItemChanged);
 5496        let active_entry = self.active_project_path(cx);
 5497        self.project.update(cx, |project, cx| {
 5498            project.set_active_path(active_entry.clone(), cx)
 5499        });
 5500
 5501        if focus_changed && let Some(project_path) = &active_entry {
 5502            let git_store_entity = self.project.read(cx).git_store().clone();
 5503            git_store_entity.update(cx, |git_store, cx| {
 5504                git_store.set_active_repo_for_path(project_path, cx);
 5505            });
 5506        }
 5507
 5508        self.update_window_title(window, cx);
 5509    }
 5510
 5511    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 5512        let project = self.project().read(cx);
 5513        let mut title = String::new();
 5514
 5515        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 5516            let name = {
 5517                let settings_location = SettingsLocation {
 5518                    worktree_id: worktree.read(cx).id(),
 5519                    path: RelPath::empty(),
 5520                };
 5521
 5522                let settings = WorktreeSettings::get(Some(settings_location), cx);
 5523                match &settings.project_name {
 5524                    Some(name) => name.as_str(),
 5525                    None => worktree.read(cx).root_name_str(),
 5526                }
 5527            };
 5528            if i > 0 {
 5529                title.push_str(", ");
 5530            }
 5531            title.push_str(name);
 5532        }
 5533
 5534        if title.is_empty() {
 5535            title = "empty project".to_string();
 5536        }
 5537
 5538        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 5539            let filename = path.path.file_name().or_else(|| {
 5540                Some(
 5541                    project
 5542                        .worktree_for_id(path.worktree_id, cx)?
 5543                        .read(cx)
 5544                        .root_name_str(),
 5545                )
 5546            });
 5547
 5548            if let Some(filename) = filename {
 5549                title.push_str("");
 5550                title.push_str(filename.as_ref());
 5551            }
 5552        }
 5553
 5554        if project.is_via_collab() {
 5555            title.push_str("");
 5556        } else if project.is_shared() {
 5557            title.push_str("");
 5558        }
 5559
 5560        if let Some(last_title) = self.last_window_title.as_ref()
 5561            && &title == last_title
 5562        {
 5563            return;
 5564        }
 5565        window.set_window_title(&title);
 5566        SystemWindowTabController::update_tab_title(
 5567            cx,
 5568            window.window_handle().window_id(),
 5569            SharedString::from(&title),
 5570        );
 5571        self.last_window_title = Some(title);
 5572    }
 5573
 5574    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 5575        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 5576        if is_edited != self.window_edited {
 5577            self.window_edited = is_edited;
 5578            window.set_window_edited(self.window_edited)
 5579        }
 5580    }
 5581
 5582    fn update_item_dirty_state(
 5583        &mut self,
 5584        item: &dyn ItemHandle,
 5585        window: &mut Window,
 5586        cx: &mut App,
 5587    ) {
 5588        let is_dirty = item.is_dirty(cx);
 5589        let item_id = item.item_id();
 5590        let was_dirty = self.dirty_items.contains_key(&item_id);
 5591        if is_dirty == was_dirty {
 5592            return;
 5593        }
 5594        if was_dirty {
 5595            self.dirty_items.remove(&item_id);
 5596            self.update_window_edited(window, cx);
 5597            return;
 5598        }
 5599
 5600        let workspace = self.weak_handle();
 5601        let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
 5602            return;
 5603        };
 5604        let on_release_callback = Box::new(move |cx: &mut App| {
 5605            window_handle
 5606                .update(cx, |_, window, cx| {
 5607                    workspace
 5608                        .update(cx, |workspace, cx| {
 5609                            workspace.dirty_items.remove(&item_id);
 5610                            workspace.update_window_edited(window, cx)
 5611                        })
 5612                        .ok();
 5613                })
 5614                .ok();
 5615        });
 5616
 5617        let s = item.on_release(cx, on_release_callback);
 5618        self.dirty_items.insert(item_id, s);
 5619        self.update_window_edited(window, cx);
 5620    }
 5621
 5622    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 5623        if self.notifications.is_empty() {
 5624            None
 5625        } else {
 5626            Some(
 5627                div()
 5628                    .absolute()
 5629                    .right_3()
 5630                    .bottom_3()
 5631                    .w_112()
 5632                    .h_full()
 5633                    .flex()
 5634                    .flex_col()
 5635                    .justify_end()
 5636                    .gap_2()
 5637                    .children(
 5638                        self.notifications
 5639                            .iter()
 5640                            .map(|(_, notification)| notification.clone().into_any()),
 5641                    ),
 5642            )
 5643        }
 5644    }
 5645
 5646    // RPC handlers
 5647
 5648    fn active_view_for_follower(
 5649        &self,
 5650        follower_project_id: Option<u64>,
 5651        window: &mut Window,
 5652        cx: &mut Context<Self>,
 5653    ) -> Option<proto::View> {
 5654        let (item, panel_id) = self.active_item_for_followers(window, cx);
 5655        let item = item?;
 5656        let leader_id = self
 5657            .pane_for(&*item)
 5658            .and_then(|pane| self.leader_for_pane(&pane));
 5659        let leader_peer_id = match leader_id {
 5660            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5661            Some(CollaboratorId::Agent) | None => None,
 5662        };
 5663
 5664        let item_handle = item.to_followable_item_handle(cx)?;
 5665        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 5666        let variant = item_handle.to_state_proto(window, cx)?;
 5667
 5668        if item_handle.is_project_item(window, cx)
 5669            && (follower_project_id.is_none()
 5670                || follower_project_id != self.project.read(cx).remote_id())
 5671        {
 5672            return None;
 5673        }
 5674
 5675        Some(proto::View {
 5676            id: id.to_proto(),
 5677            leader_id: leader_peer_id,
 5678            variant: Some(variant),
 5679            panel_id: panel_id.map(|id| id as i32),
 5680        })
 5681    }
 5682
 5683    fn handle_follow(
 5684        &mut self,
 5685        follower_project_id: Option<u64>,
 5686        window: &mut Window,
 5687        cx: &mut Context<Self>,
 5688    ) -> proto::FollowResponse {
 5689        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 5690
 5691        cx.notify();
 5692        proto::FollowResponse {
 5693            views: active_view.iter().cloned().collect(),
 5694            active_view,
 5695        }
 5696    }
 5697
 5698    fn handle_update_followers(
 5699        &mut self,
 5700        leader_id: PeerId,
 5701        message: proto::UpdateFollowers,
 5702        _window: &mut Window,
 5703        _cx: &mut Context<Self>,
 5704    ) {
 5705        self.leader_updates_tx
 5706            .unbounded_send((leader_id, message))
 5707            .ok();
 5708    }
 5709
 5710    async fn process_leader_update(
 5711        this: &WeakEntity<Self>,
 5712        leader_id: PeerId,
 5713        update: proto::UpdateFollowers,
 5714        cx: &mut AsyncWindowContext,
 5715    ) -> Result<()> {
 5716        match update.variant.context("invalid update")? {
 5717            proto::update_followers::Variant::CreateView(view) => {
 5718                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 5719                let should_add_view = this.update(cx, |this, _| {
 5720                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5721                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 5722                    } else {
 5723                        anyhow::Ok(false)
 5724                    }
 5725                })??;
 5726
 5727                if should_add_view {
 5728                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5729                }
 5730            }
 5731            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 5732                let should_add_view = this.update(cx, |this, _| {
 5733                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 5734                        state.active_view_id = update_active_view
 5735                            .view
 5736                            .as_ref()
 5737                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 5738
 5739                        if state.active_view_id.is_some_and(|view_id| {
 5740                            !state.items_by_leader_view_id.contains_key(&view_id)
 5741                        }) {
 5742                            anyhow::Ok(true)
 5743                        } else {
 5744                            anyhow::Ok(false)
 5745                        }
 5746                    } else {
 5747                        anyhow::Ok(false)
 5748                    }
 5749                })??;
 5750
 5751                if should_add_view && let Some(view) = update_active_view.view {
 5752                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 5753                }
 5754            }
 5755            proto::update_followers::Variant::UpdateView(update_view) => {
 5756                let variant = update_view.variant.context("missing update view variant")?;
 5757                let id = update_view.id.context("missing update view id")?;
 5758                let mut tasks = Vec::new();
 5759                this.update_in(cx, |this, window, cx| {
 5760                    let project = this.project.clone();
 5761                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 5762                        let view_id = ViewId::from_proto(id.clone())?;
 5763                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 5764                            tasks.push(item.view.apply_update_proto(
 5765                                &project,
 5766                                variant.clone(),
 5767                                window,
 5768                                cx,
 5769                            ));
 5770                        }
 5771                    }
 5772                    anyhow::Ok(())
 5773                })??;
 5774                try_join_all(tasks).await.log_err();
 5775            }
 5776        }
 5777        this.update_in(cx, |this, window, cx| {
 5778            this.leader_updated(leader_id, window, cx)
 5779        })?;
 5780        Ok(())
 5781    }
 5782
 5783    async fn add_view_from_leader(
 5784        this: WeakEntity<Self>,
 5785        leader_id: PeerId,
 5786        view: &proto::View,
 5787        cx: &mut AsyncWindowContext,
 5788    ) -> Result<()> {
 5789        let this = this.upgrade().context("workspace dropped")?;
 5790
 5791        let Some(id) = view.id.clone() else {
 5792            anyhow::bail!("no id for view");
 5793        };
 5794        let id = ViewId::from_proto(id)?;
 5795        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 5796
 5797        let pane = this.update(cx, |this, _cx| {
 5798            let state = this
 5799                .follower_states
 5800                .get(&leader_id.into())
 5801                .context("stopped following")?;
 5802            anyhow::Ok(state.pane().clone())
 5803        })?;
 5804        let existing_item = pane.update_in(cx, |pane, window, cx| {
 5805            let client = this.read(cx).client().clone();
 5806            pane.items().find_map(|item| {
 5807                let item = item.to_followable_item_handle(cx)?;
 5808                if item.remote_id(&client, window, cx) == Some(id) {
 5809                    Some(item)
 5810                } else {
 5811                    None
 5812                }
 5813            })
 5814        })?;
 5815        let item = if let Some(existing_item) = existing_item {
 5816            existing_item
 5817        } else {
 5818            let variant = view.variant.clone();
 5819            anyhow::ensure!(variant.is_some(), "missing view variant");
 5820
 5821            let task = cx.update(|window, cx| {
 5822                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 5823            })?;
 5824
 5825            let Some(task) = task else {
 5826                anyhow::bail!(
 5827                    "failed to construct view from leader (maybe from a different version of zed?)"
 5828                );
 5829            };
 5830
 5831            let mut new_item = task.await?;
 5832            pane.update_in(cx, |pane, window, cx| {
 5833                let mut item_to_remove = None;
 5834                for (ix, item) in pane.items().enumerate() {
 5835                    if let Some(item) = item.to_followable_item_handle(cx) {
 5836                        match new_item.dedup(item.as_ref(), window, cx) {
 5837                            Some(item::Dedup::KeepExisting) => {
 5838                                new_item =
 5839                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 5840                                break;
 5841                            }
 5842                            Some(item::Dedup::ReplaceExisting) => {
 5843                                item_to_remove = Some((ix, item.item_id()));
 5844                                break;
 5845                            }
 5846                            None => {}
 5847                        }
 5848                    }
 5849                }
 5850
 5851                if let Some((ix, id)) = item_to_remove {
 5852                    pane.remove_item(id, false, false, window, cx);
 5853                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 5854                }
 5855            })?;
 5856
 5857            new_item
 5858        };
 5859
 5860        this.update_in(cx, |this, window, cx| {
 5861            let state = this.follower_states.get_mut(&leader_id.into())?;
 5862            item.set_leader_id(Some(leader_id.into()), window, cx);
 5863            state.items_by_leader_view_id.insert(
 5864                id,
 5865                FollowerView {
 5866                    view: item,
 5867                    location: panel_id,
 5868                },
 5869            );
 5870
 5871            Some(())
 5872        })
 5873        .context("no follower state")?;
 5874
 5875        Ok(())
 5876    }
 5877
 5878    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5879        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5880            return;
 5881        };
 5882
 5883        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5884            let buffer_entity_id = agent_location.buffer.entity_id();
 5885            let view_id = ViewId {
 5886                creator: CollaboratorId::Agent,
 5887                id: buffer_entity_id.as_u64(),
 5888            };
 5889            follower_state.active_view_id = Some(view_id);
 5890
 5891            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5892                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5893                hash_map::Entry::Vacant(entry) => {
 5894                    let existing_view =
 5895                        follower_state
 5896                            .center_pane
 5897                            .read(cx)
 5898                            .items()
 5899                            .find_map(|item| {
 5900                                let item = item.to_followable_item_handle(cx)?;
 5901                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5902                                    && item.project_item_model_ids(cx).as_slice()
 5903                                        == [buffer_entity_id]
 5904                                {
 5905                                    Some(item)
 5906                                } else {
 5907                                    None
 5908                                }
 5909                            });
 5910                    let view = existing_view.or_else(|| {
 5911                        agent_location.buffer.upgrade().and_then(|buffer| {
 5912                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 5913                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 5914                            })?
 5915                            .to_followable_item_handle(cx)
 5916                        })
 5917                    });
 5918
 5919                    view.map(|view| {
 5920                        entry.insert(FollowerView {
 5921                            view,
 5922                            location: None,
 5923                        })
 5924                    })
 5925                }
 5926            };
 5927
 5928            if let Some(item) = item {
 5929                item.view
 5930                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 5931                item.view
 5932                    .update_agent_location(agent_location.position, window, cx);
 5933            }
 5934        } else {
 5935            follower_state.active_view_id = None;
 5936        }
 5937
 5938        self.leader_updated(CollaboratorId::Agent, window, cx);
 5939    }
 5940
 5941    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 5942        let mut is_project_item = true;
 5943        let mut update = proto::UpdateActiveView::default();
 5944        if window.is_window_active() {
 5945            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 5946
 5947            if let Some(item) = active_item
 5948                && item.item_focus_handle(cx).contains_focused(window, cx)
 5949            {
 5950                let leader_id = self
 5951                    .pane_for(&*item)
 5952                    .and_then(|pane| self.leader_for_pane(&pane));
 5953                let leader_peer_id = match leader_id {
 5954                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5955                    Some(CollaboratorId::Agent) | None => None,
 5956                };
 5957
 5958                if let Some(item) = item.to_followable_item_handle(cx) {
 5959                    let id = item
 5960                        .remote_id(&self.app_state.client, window, cx)
 5961                        .map(|id| id.to_proto());
 5962
 5963                    if let Some(id) = id
 5964                        && let Some(variant) = item.to_state_proto(window, cx)
 5965                    {
 5966                        let view = Some(proto::View {
 5967                            id,
 5968                            leader_id: leader_peer_id,
 5969                            variant: Some(variant),
 5970                            panel_id: panel_id.map(|id| id as i32),
 5971                        });
 5972
 5973                        is_project_item = item.is_project_item(window, cx);
 5974                        update = proto::UpdateActiveView { view };
 5975                    };
 5976                }
 5977            }
 5978        }
 5979
 5980        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 5981        if active_view_id != self.last_active_view_id.as_ref() {
 5982            self.last_active_view_id = active_view_id.cloned();
 5983            self.update_followers(
 5984                is_project_item,
 5985                proto::update_followers::Variant::UpdateActiveView(update),
 5986                window,
 5987                cx,
 5988            );
 5989        }
 5990    }
 5991
 5992    fn active_item_for_followers(
 5993        &self,
 5994        window: &mut Window,
 5995        cx: &mut App,
 5996    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 5997        let mut active_item = None;
 5998        let mut panel_id = None;
 5999        for dock in self.all_docks() {
 6000            if dock.focus_handle(cx).contains_focused(window, cx)
 6001                && let Some(panel) = dock.read(cx).active_panel()
 6002                && let Some(pane) = panel.pane(cx)
 6003                && let Some(item) = pane.read(cx).active_item()
 6004            {
 6005                active_item = Some(item);
 6006                panel_id = panel.remote_id();
 6007                break;
 6008            }
 6009        }
 6010
 6011        if active_item.is_none() {
 6012            active_item = self.active_pane().read(cx).active_item();
 6013        }
 6014        (active_item, panel_id)
 6015    }
 6016
 6017    fn update_followers(
 6018        &self,
 6019        project_only: bool,
 6020        update: proto::update_followers::Variant,
 6021        _: &mut Window,
 6022        cx: &mut App,
 6023    ) -> Option<()> {
 6024        // If this update only applies to for followers in the current project,
 6025        // then skip it unless this project is shared. If it applies to all
 6026        // followers, regardless of project, then set `project_id` to none,
 6027        // indicating that it goes to all followers.
 6028        let project_id = if project_only {
 6029            Some(self.project.read(cx).remote_id()?)
 6030        } else {
 6031            None
 6032        };
 6033        self.app_state().workspace_store.update(cx, |store, cx| {
 6034            store.update_followers(project_id, update, cx)
 6035        })
 6036    }
 6037
 6038    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 6039        self.follower_states.iter().find_map(|(leader_id, state)| {
 6040            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 6041                Some(*leader_id)
 6042            } else {
 6043                None
 6044            }
 6045        })
 6046    }
 6047
 6048    fn leader_updated(
 6049        &mut self,
 6050        leader_id: impl Into<CollaboratorId>,
 6051        window: &mut Window,
 6052        cx: &mut Context<Self>,
 6053    ) -> Option<Box<dyn ItemHandle>> {
 6054        cx.notify();
 6055
 6056        let leader_id = leader_id.into();
 6057        let (panel_id, item) = match leader_id {
 6058            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 6059            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 6060        };
 6061
 6062        let state = self.follower_states.get(&leader_id)?;
 6063        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 6064        let pane;
 6065        if let Some(panel_id) = panel_id {
 6066            pane = self
 6067                .activate_panel_for_proto_id(panel_id, window, cx)?
 6068                .pane(cx)?;
 6069            let state = self.follower_states.get_mut(&leader_id)?;
 6070            state.dock_pane = Some(pane.clone());
 6071        } else {
 6072            pane = state.center_pane.clone();
 6073            let state = self.follower_states.get_mut(&leader_id)?;
 6074            if let Some(dock_pane) = state.dock_pane.take() {
 6075                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 6076            }
 6077        }
 6078
 6079        pane.update(cx, |pane, cx| {
 6080            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 6081            if let Some(index) = pane.index_for_item(item.as_ref()) {
 6082                pane.activate_item(index, false, false, window, cx);
 6083            } else {
 6084                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 6085            }
 6086
 6087            if focus_active_item {
 6088                pane.focus_active_item(window, cx)
 6089            }
 6090        });
 6091
 6092        Some(item)
 6093    }
 6094
 6095    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 6096        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 6097        let active_view_id = state.active_view_id?;
 6098        Some(
 6099            state
 6100                .items_by_leader_view_id
 6101                .get(&active_view_id)?
 6102                .view
 6103                .boxed_clone(),
 6104        )
 6105    }
 6106
 6107    fn active_item_for_peer(
 6108        &self,
 6109        peer_id: PeerId,
 6110        window: &mut Window,
 6111        cx: &mut Context<Self>,
 6112    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 6113        let call = self.active_call()?;
 6114        let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
 6115        let leader_in_this_app;
 6116        let leader_in_this_project;
 6117        match participant.location {
 6118            ParticipantLocation::SharedProject { project_id } => {
 6119                leader_in_this_app = true;
 6120                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 6121            }
 6122            ParticipantLocation::UnsharedProject => {
 6123                leader_in_this_app = true;
 6124                leader_in_this_project = false;
 6125            }
 6126            ParticipantLocation::External => {
 6127                leader_in_this_app = false;
 6128                leader_in_this_project = false;
 6129            }
 6130        };
 6131        let state = self.follower_states.get(&peer_id.into())?;
 6132        let mut item_to_activate = None;
 6133        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 6134            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 6135                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 6136            {
 6137                item_to_activate = Some((item.location, item.view.boxed_clone()));
 6138            }
 6139        } else if let Some(shared_screen) =
 6140            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 6141        {
 6142            item_to_activate = Some((None, Box::new(shared_screen)));
 6143        }
 6144        item_to_activate
 6145    }
 6146
 6147    fn shared_screen_for_peer(
 6148        &self,
 6149        peer_id: PeerId,
 6150        pane: &Entity<Pane>,
 6151        window: &mut Window,
 6152        cx: &mut App,
 6153    ) -> Option<Entity<SharedScreen>> {
 6154        self.active_call()?
 6155            .create_shared_screen(peer_id, pane, window, cx)
 6156    }
 6157
 6158    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6159        if window.is_window_active() {
 6160            self.update_active_view_for_followers(window, cx);
 6161
 6162            if let Some(database_id) = self.database_id {
 6163                let db = WorkspaceDb::global(cx);
 6164                cx.background_spawn(async move { db.update_timestamp(database_id).await })
 6165                    .detach();
 6166            }
 6167        } else {
 6168            for pane in &self.panes {
 6169                pane.update(cx, |pane, cx| {
 6170                    if let Some(item) = pane.active_item() {
 6171                        item.workspace_deactivated(window, cx);
 6172                    }
 6173                    for item in pane.items() {
 6174                        if matches!(
 6175                            item.workspace_settings(cx).autosave,
 6176                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 6177                        ) {
 6178                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 6179                                .detach_and_log_err(cx);
 6180                        }
 6181                    }
 6182                });
 6183            }
 6184        }
 6185    }
 6186
 6187    pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
 6188        self.active_call.as_ref().map(|(call, _)| &*call.0)
 6189    }
 6190
 6191    pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
 6192        self.active_call.as_ref().map(|(call, _)| call.clone())
 6193    }
 6194
 6195    fn on_active_call_event(
 6196        &mut self,
 6197        event: &ActiveCallEvent,
 6198        window: &mut Window,
 6199        cx: &mut Context<Self>,
 6200    ) {
 6201        match event {
 6202            ActiveCallEvent::ParticipantLocationChanged { participant_id }
 6203            | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
 6204                self.leader_updated(participant_id, window, cx);
 6205            }
 6206        }
 6207    }
 6208
 6209    pub fn database_id(&self) -> Option<WorkspaceId> {
 6210        self.database_id
 6211    }
 6212
 6213    #[cfg(any(test, feature = "test-support"))]
 6214    pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
 6215        self.database_id = Some(id);
 6216    }
 6217
 6218    pub fn session_id(&self) -> Option<String> {
 6219        self.session_id.clone()
 6220    }
 6221
 6222    fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6223        let Some(display) = window.display(cx) else {
 6224            return Task::ready(());
 6225        };
 6226        let Ok(display_uuid) = display.uuid() else {
 6227            return Task::ready(());
 6228        };
 6229
 6230        let window_bounds = window.inner_window_bounds();
 6231        let database_id = self.database_id;
 6232        let has_paths = !self.root_paths(cx).is_empty();
 6233        let db = WorkspaceDb::global(cx);
 6234        let kvp = db::kvp::KeyValueStore::global(cx);
 6235
 6236        cx.background_executor().spawn(async move {
 6237            if !has_paths {
 6238                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6239                    .await
 6240                    .log_err();
 6241            }
 6242            if let Some(database_id) = database_id {
 6243                db.set_window_open_status(
 6244                    database_id,
 6245                    SerializedWindowBounds(window_bounds),
 6246                    display_uuid,
 6247                )
 6248                .await
 6249                .log_err();
 6250            } else {
 6251                persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
 6252                    .await
 6253                    .log_err();
 6254            }
 6255        })
 6256    }
 6257
 6258    /// Bypass the 200ms serialization throttle and write workspace state to
 6259    /// the DB immediately. Returns a task the caller can await to ensure the
 6260    /// write completes. Used by the quit handler so the most recent state
 6261    /// isn't lost to a pending throttle timer when the process exits.
 6262    pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6263        self._schedule_serialize_workspace.take();
 6264        self._serialize_workspace_task.take();
 6265        self.bounds_save_task_queued.take();
 6266
 6267        let bounds_task = self.save_window_bounds(window, cx);
 6268        let serialize_task = self.serialize_workspace_internal(window, cx);
 6269        cx.spawn(async move |_| {
 6270            bounds_task.await;
 6271            serialize_task.await;
 6272        })
 6273    }
 6274
 6275    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 6276        let project = self.project().read(cx);
 6277        project
 6278            .visible_worktrees(cx)
 6279            .map(|worktree| worktree.read(cx).abs_path())
 6280            .collect::<Vec<_>>()
 6281    }
 6282
 6283    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 6284        match member {
 6285            Member::Axis(PaneAxis { members, .. }) => {
 6286                for child in members.iter() {
 6287                    self.remove_panes(child.clone(), window, cx)
 6288                }
 6289            }
 6290            Member::Pane(pane) => {
 6291                self.force_remove_pane(&pane, &None, window, cx);
 6292            }
 6293        }
 6294    }
 6295
 6296    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 6297        self.session_id.take();
 6298        self.serialize_workspace_internal(window, cx)
 6299    }
 6300
 6301    fn force_remove_pane(
 6302        &mut self,
 6303        pane: &Entity<Pane>,
 6304        focus_on: &Option<Entity<Pane>>,
 6305        window: &mut Window,
 6306        cx: &mut Context<Workspace>,
 6307    ) {
 6308        self.panes.retain(|p| p != pane);
 6309        if let Some(focus_on) = focus_on {
 6310            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6311        } else if self.active_pane() == pane {
 6312            self.panes
 6313                .last()
 6314                .unwrap()
 6315                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 6316        }
 6317        if self.last_active_center_pane == Some(pane.downgrade()) {
 6318            self.last_active_center_pane = None;
 6319        }
 6320        cx.notify();
 6321    }
 6322
 6323    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6324        if self._schedule_serialize_workspace.is_none() {
 6325            self._schedule_serialize_workspace =
 6326                Some(cx.spawn_in(window, async move |this, cx| {
 6327                    cx.background_executor()
 6328                        .timer(SERIALIZATION_THROTTLE_TIME)
 6329                        .await;
 6330                    this.update_in(cx, |this, window, cx| {
 6331                        this._serialize_workspace_task =
 6332                            Some(this.serialize_workspace_internal(window, cx));
 6333                        this._schedule_serialize_workspace.take();
 6334                    })
 6335                    .log_err();
 6336                }));
 6337        }
 6338    }
 6339
 6340    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 6341        let Some(database_id) = self.database_id() else {
 6342            return Task::ready(());
 6343        };
 6344
 6345        fn serialize_pane_handle(
 6346            pane_handle: &Entity<Pane>,
 6347            window: &mut Window,
 6348            cx: &mut App,
 6349        ) -> SerializedPane {
 6350            let (items, active, pinned_count) = {
 6351                let pane = pane_handle.read(cx);
 6352                let active_item_id = pane.active_item().map(|item| item.item_id());
 6353                (
 6354                    pane.items()
 6355                        .filter_map(|handle| {
 6356                            let handle = handle.to_serializable_item_handle(cx)?;
 6357
 6358                            Some(SerializedItem {
 6359                                kind: Arc::from(handle.serialized_item_kind()),
 6360                                item_id: handle.item_id().as_u64(),
 6361                                active: Some(handle.item_id()) == active_item_id,
 6362                                preview: pane.is_active_preview_item(handle.item_id()),
 6363                            })
 6364                        })
 6365                        .collect::<Vec<_>>(),
 6366                    pane.has_focus(window, cx),
 6367                    pane.pinned_count(),
 6368                )
 6369            };
 6370
 6371            SerializedPane::new(items, active, pinned_count)
 6372        }
 6373
 6374        fn build_serialized_pane_group(
 6375            pane_group: &Member,
 6376            window: &mut Window,
 6377            cx: &mut App,
 6378        ) -> SerializedPaneGroup {
 6379            match pane_group {
 6380                Member::Axis(PaneAxis {
 6381                    axis,
 6382                    members,
 6383                    flexes,
 6384                    bounding_boxes: _,
 6385                }) => SerializedPaneGroup::Group {
 6386                    axis: SerializedAxis(*axis),
 6387                    children: members
 6388                        .iter()
 6389                        .map(|member| build_serialized_pane_group(member, window, cx))
 6390                        .collect::<Vec<_>>(),
 6391                    flexes: Some(flexes.lock().clone()),
 6392                },
 6393                Member::Pane(pane_handle) => {
 6394                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 6395                }
 6396            }
 6397        }
 6398
 6399        fn build_serialized_docks(
 6400            this: &Workspace,
 6401            window: &mut Window,
 6402            cx: &mut App,
 6403        ) -> DockStructure {
 6404            this.capture_dock_state(window, cx)
 6405        }
 6406
 6407        match self.workspace_location(cx) {
 6408            WorkspaceLocation::Location(location, paths) => {
 6409                let breakpoints = self.project.update(cx, |project, cx| {
 6410                    project
 6411                        .breakpoint_store()
 6412                        .read(cx)
 6413                        .all_source_breakpoints(cx)
 6414                });
 6415                let user_toolchains = self
 6416                    .project
 6417                    .read(cx)
 6418                    .user_toolchains(cx)
 6419                    .unwrap_or_default();
 6420
 6421                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 6422                let docks = build_serialized_docks(self, window, cx);
 6423                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 6424
 6425                let serialized_workspace = SerializedWorkspace {
 6426                    id: database_id,
 6427                    location,
 6428                    paths,
 6429                    center_group,
 6430                    window_bounds,
 6431                    display: Default::default(),
 6432                    docks,
 6433                    centered_layout: self.centered_layout,
 6434                    session_id: self.session_id.clone(),
 6435                    breakpoints,
 6436                    window_id: Some(window.window_handle().window_id().as_u64()),
 6437                    user_toolchains,
 6438                };
 6439
 6440                let db = WorkspaceDb::global(cx);
 6441                window.spawn(cx, async move |_| {
 6442                    db.save_workspace(serialized_workspace).await;
 6443                })
 6444            }
 6445            WorkspaceLocation::DetachFromSession => {
 6446                let window_bounds = SerializedWindowBounds(window.window_bounds());
 6447                let display = window.display(cx).and_then(|d| d.uuid().ok());
 6448                // Save dock state for empty local workspaces
 6449                let docks = build_serialized_docks(self, window, cx);
 6450                let db = WorkspaceDb::global(cx);
 6451                let kvp = db::kvp::KeyValueStore::global(cx);
 6452                window.spawn(cx, async move |_| {
 6453                    db.set_window_open_status(
 6454                        database_id,
 6455                        window_bounds,
 6456                        display.unwrap_or_default(),
 6457                    )
 6458                    .await
 6459                    .log_err();
 6460                    db.set_session_id(database_id, None).await.log_err();
 6461                    persistence::write_default_dock_state(&kvp, docks)
 6462                        .await
 6463                        .log_err();
 6464                })
 6465            }
 6466            WorkspaceLocation::None => {
 6467                // Save dock state for empty non-local workspaces
 6468                let docks = build_serialized_docks(self, window, cx);
 6469                let kvp = db::kvp::KeyValueStore::global(cx);
 6470                window.spawn(cx, async move |_| {
 6471                    persistence::write_default_dock_state(&kvp, docks)
 6472                        .await
 6473                        .log_err();
 6474                })
 6475            }
 6476        }
 6477    }
 6478
 6479    fn has_any_items_open(&self, cx: &App) -> bool {
 6480        self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
 6481    }
 6482
 6483    fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
 6484        let paths = PathList::new(&self.root_paths(cx));
 6485        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 6486            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 6487        } else if self.project.read(cx).is_local() {
 6488            if !paths.is_empty() || self.has_any_items_open(cx) {
 6489                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 6490            } else {
 6491                WorkspaceLocation::DetachFromSession
 6492            }
 6493        } else {
 6494            WorkspaceLocation::None
 6495        }
 6496    }
 6497
 6498    fn update_history(&self, cx: &mut App) {
 6499        let Some(id) = self.database_id() else {
 6500            return;
 6501        };
 6502        if !self.project.read(cx).is_local() {
 6503            return;
 6504        }
 6505        if let Some(manager) = HistoryManager::global(cx) {
 6506            let paths = PathList::new(&self.root_paths(cx));
 6507            manager.update(cx, |this, cx| {
 6508                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 6509            });
 6510        }
 6511    }
 6512
 6513    async fn serialize_items(
 6514        this: &WeakEntity<Self>,
 6515        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 6516        cx: &mut AsyncWindowContext,
 6517    ) -> Result<()> {
 6518        const CHUNK_SIZE: usize = 200;
 6519
 6520        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 6521
 6522        while let Some(items_received) = serializable_items.next().await {
 6523            let unique_items =
 6524                items_received
 6525                    .into_iter()
 6526                    .fold(HashMap::default(), |mut acc, item| {
 6527                        acc.entry(item.item_id()).or_insert(item);
 6528                        acc
 6529                    });
 6530
 6531            // We use into_iter() here so that the references to the items are moved into
 6532            // the tasks and not kept alive while we're sleeping.
 6533            for (_, item) in unique_items.into_iter() {
 6534                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 6535                    item.serialize(workspace, false, window, cx)
 6536                }) {
 6537                    cx.background_spawn(async move { task.await.log_err() })
 6538                        .detach();
 6539                }
 6540            }
 6541
 6542            cx.background_executor()
 6543                .timer(SERIALIZATION_THROTTLE_TIME)
 6544                .await;
 6545        }
 6546
 6547        Ok(())
 6548    }
 6549
 6550    pub(crate) fn enqueue_item_serialization(
 6551        &mut self,
 6552        item: Box<dyn SerializableItemHandle>,
 6553    ) -> Result<()> {
 6554        self.serializable_items_tx
 6555            .unbounded_send(item)
 6556            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 6557    }
 6558
 6559    pub(crate) fn load_workspace(
 6560        serialized_workspace: SerializedWorkspace,
 6561        paths_to_open: Vec<Option<ProjectPath>>,
 6562        window: &mut Window,
 6563        cx: &mut Context<Workspace>,
 6564    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 6565        cx.spawn_in(window, async move |workspace, cx| {
 6566            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 6567
 6568            let mut center_group = None;
 6569            let mut center_items = None;
 6570
 6571            // Traverse the splits tree and add to things
 6572            if let Some((group, active_pane, items)) = serialized_workspace
 6573                .center_group
 6574                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 6575                .await
 6576            {
 6577                center_items = Some(items);
 6578                center_group = Some((group, active_pane))
 6579            }
 6580
 6581            let mut items_by_project_path = HashMap::default();
 6582            let mut item_ids_by_kind = HashMap::default();
 6583            let mut all_deserialized_items = Vec::default();
 6584            cx.update(|_, cx| {
 6585                for item in center_items.unwrap_or_default().into_iter().flatten() {
 6586                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 6587                        item_ids_by_kind
 6588                            .entry(serializable_item_handle.serialized_item_kind())
 6589                            .or_insert(Vec::new())
 6590                            .push(item.item_id().as_u64() as ItemId);
 6591                    }
 6592
 6593                    if let Some(project_path) = item.project_path(cx) {
 6594                        items_by_project_path.insert(project_path, item.clone());
 6595                    }
 6596                    all_deserialized_items.push(item);
 6597                }
 6598            })?;
 6599
 6600            let opened_items = paths_to_open
 6601                .into_iter()
 6602                .map(|path_to_open| {
 6603                    path_to_open
 6604                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 6605                })
 6606                .collect::<Vec<_>>();
 6607
 6608            // Remove old panes from workspace panes list
 6609            workspace.update_in(cx, |workspace, window, cx| {
 6610                if let Some((center_group, active_pane)) = center_group {
 6611                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 6612
 6613                    // Swap workspace center group
 6614                    workspace.center = PaneGroup::with_root(center_group);
 6615                    workspace.center.set_is_center(true);
 6616                    workspace.center.mark_positions(cx);
 6617
 6618                    if let Some(active_pane) = active_pane {
 6619                        workspace.set_active_pane(&active_pane, window, cx);
 6620                        cx.focus_self(window);
 6621                    } else {
 6622                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 6623                    }
 6624                }
 6625
 6626                let docks = serialized_workspace.docks;
 6627
 6628                for (dock, serialized_dock) in [
 6629                    (&mut workspace.right_dock, docks.right),
 6630                    (&mut workspace.left_dock, docks.left),
 6631                    (&mut workspace.bottom_dock, docks.bottom),
 6632                ]
 6633                .iter_mut()
 6634                {
 6635                    dock.update(cx, |dock, cx| {
 6636                        dock.serialized_dock = Some(serialized_dock.clone());
 6637                        dock.restore_state(window, cx);
 6638                    });
 6639                }
 6640
 6641                cx.notify();
 6642            })?;
 6643
 6644            let _ = project
 6645                .update(cx, |project, cx| {
 6646                    project
 6647                        .breakpoint_store()
 6648                        .update(cx, |breakpoint_store, cx| {
 6649                            breakpoint_store
 6650                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 6651                        })
 6652                })
 6653                .await;
 6654
 6655            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 6656            // after loading the items, we might have different items and in order to avoid
 6657            // the database filling up, we delete items that haven't been loaded now.
 6658            //
 6659            // The items that have been loaded, have been saved after they've been added to the workspace.
 6660            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 6661                item_ids_by_kind
 6662                    .into_iter()
 6663                    .map(|(item_kind, loaded_items)| {
 6664                        SerializableItemRegistry::cleanup(
 6665                            item_kind,
 6666                            serialized_workspace.id,
 6667                            loaded_items,
 6668                            window,
 6669                            cx,
 6670                        )
 6671                        .log_err()
 6672                    })
 6673                    .collect::<Vec<_>>()
 6674            })?;
 6675
 6676            futures::future::join_all(clean_up_tasks).await;
 6677
 6678            workspace
 6679                .update_in(cx, |workspace, window, cx| {
 6680                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 6681                    workspace.serialize_workspace_internal(window, cx).detach();
 6682
 6683                    // Ensure that we mark the window as edited if we did load dirty items
 6684                    workspace.update_window_edited(window, cx);
 6685                })
 6686                .ok();
 6687
 6688            Ok(opened_items)
 6689        })
 6690    }
 6691
 6692    pub fn key_context(&self, cx: &App) -> KeyContext {
 6693        let mut context = KeyContext::new_with_defaults();
 6694        context.add("Workspace");
 6695        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6696        if let Some(status) = self
 6697            .debugger_provider
 6698            .as_ref()
 6699            .and_then(|provider| provider.active_thread_state(cx))
 6700        {
 6701            match status {
 6702                ThreadStatus::Running | ThreadStatus::Stepping => {
 6703                    context.add("debugger_running");
 6704                }
 6705                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6706                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6707            }
 6708        }
 6709
 6710        if self.left_dock.read(cx).is_open() {
 6711            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6712                context.set("left_dock", active_panel.panel_key());
 6713            }
 6714        }
 6715
 6716        if self.right_dock.read(cx).is_open() {
 6717            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6718                context.set("right_dock", active_panel.panel_key());
 6719            }
 6720        }
 6721
 6722        if self.bottom_dock.read(cx).is_open() {
 6723            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6724                context.set("bottom_dock", active_panel.panel_key());
 6725            }
 6726        }
 6727
 6728        context
 6729    }
 6730
 6731    /// Multiworkspace uses this to add workspace action handling to itself
 6732    pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 6733        self.add_workspace_actions_listeners(div, window, cx)
 6734            .on_action(cx.listener(
 6735                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 6736                    for action in &action_sequence.0 {
 6737                        window.dispatch_action(action.boxed_clone(), cx);
 6738                    }
 6739                },
 6740            ))
 6741            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 6742            .on_action(cx.listener(Self::close_all_items_and_panes))
 6743            .on_action(cx.listener(Self::close_item_in_all_panes))
 6744            .on_action(cx.listener(Self::save_all))
 6745            .on_action(cx.listener(Self::send_keystrokes))
 6746            .on_action(cx.listener(Self::add_folder_to_project))
 6747            .on_action(cx.listener(Self::follow_next_collaborator))
 6748            .on_action(cx.listener(Self::activate_pane_at_index))
 6749            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 6750            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 6751            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 6752            .on_action(cx.listener(Self::toggle_theme_mode))
 6753            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 6754                let pane = workspace.active_pane().clone();
 6755                workspace.unfollow_in_pane(&pane, window, cx);
 6756            }))
 6757            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 6758                workspace
 6759                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 6760                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6761            }))
 6762            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 6763                workspace
 6764                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 6765                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6766            }))
 6767            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 6768                workspace
 6769                    .save_active_item(SaveIntent::SaveAs, window, cx)
 6770                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 6771            }))
 6772            .on_action(
 6773                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 6774                    workspace.activate_previous_pane(window, cx)
 6775                }),
 6776            )
 6777            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 6778                workspace.activate_next_pane(window, cx)
 6779            }))
 6780            .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
 6781                workspace.activate_last_pane(window, cx)
 6782            }))
 6783            .on_action(
 6784                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 6785                    workspace.activate_next_window(cx)
 6786                }),
 6787            )
 6788            .on_action(
 6789                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 6790                    workspace.activate_previous_window(cx)
 6791                }),
 6792            )
 6793            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 6794                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 6795            }))
 6796            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 6797                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 6798            }))
 6799            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 6800                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 6801            }))
 6802            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 6803                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 6804            }))
 6805            .on_action(cx.listener(
 6806                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 6807                    workspace.move_item_to_pane_in_direction(action, window, cx)
 6808                },
 6809            ))
 6810            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 6811                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 6812            }))
 6813            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 6814                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 6815            }))
 6816            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 6817                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 6818            }))
 6819            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 6820                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 6821            }))
 6822            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 6823                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 6824                    SplitDirection::Down,
 6825                    SplitDirection::Up,
 6826                    SplitDirection::Right,
 6827                    SplitDirection::Left,
 6828                ];
 6829                for dir in DIRECTION_PRIORITY {
 6830                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 6831                        workspace.swap_pane_in_direction(dir, cx);
 6832                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 6833                        break;
 6834                    }
 6835                }
 6836            }))
 6837            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 6838                workspace.move_pane_to_border(SplitDirection::Left, cx)
 6839            }))
 6840            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 6841                workspace.move_pane_to_border(SplitDirection::Right, cx)
 6842            }))
 6843            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 6844                workspace.move_pane_to_border(SplitDirection::Up, cx)
 6845            }))
 6846            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 6847                workspace.move_pane_to_border(SplitDirection::Down, cx)
 6848            }))
 6849            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 6850                this.toggle_dock(DockPosition::Left, window, cx);
 6851            }))
 6852            .on_action(cx.listener(
 6853                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 6854                    workspace.toggle_dock(DockPosition::Right, window, cx);
 6855                },
 6856            ))
 6857            .on_action(cx.listener(
 6858                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 6859                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 6860                },
 6861            ))
 6862            .on_action(cx.listener(
 6863                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 6864                    if !workspace.close_active_dock(window, cx) {
 6865                        cx.propagate();
 6866                    }
 6867                },
 6868            ))
 6869            .on_action(
 6870                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 6871                    workspace.close_all_docks(window, cx);
 6872                }),
 6873            )
 6874            .on_action(cx.listener(Self::toggle_all_docks))
 6875            .on_action(cx.listener(
 6876                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 6877                    workspace.clear_all_notifications(cx);
 6878                },
 6879            ))
 6880            .on_action(cx.listener(
 6881                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 6882                    workspace.clear_navigation_history(window, cx);
 6883                },
 6884            ))
 6885            .on_action(cx.listener(
 6886                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 6887                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 6888                        workspace.suppress_notification(&notification_id, cx);
 6889                    }
 6890                },
 6891            ))
 6892            .on_action(cx.listener(
 6893                |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
 6894                    workspace.show_worktree_trust_security_modal(true, window, cx);
 6895                },
 6896            ))
 6897            .on_action(
 6898                cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
 6899                    if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
 6900                        trusted_worktrees.update(cx, |trusted_worktrees, _| {
 6901                            trusted_worktrees.clear_trusted_paths()
 6902                        });
 6903                        let db = WorkspaceDb::global(cx);
 6904                        cx.spawn(async move |_, cx| {
 6905                            if db.clear_trusted_worktrees().await.log_err().is_some() {
 6906                                cx.update(|cx| reload(cx));
 6907                            }
 6908                        })
 6909                        .detach();
 6910                    }
 6911                }),
 6912            )
 6913            .on_action(cx.listener(
 6914                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 6915                    workspace.reopen_closed_item(window, cx).detach();
 6916                },
 6917            ))
 6918            .on_action(cx.listener(
 6919                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 6920                    for dock in workspace.all_docks() {
 6921                        if dock.focus_handle(cx).contains_focused(window, cx) {
 6922                            let panel = dock.read(cx).active_panel().cloned();
 6923                            if let Some(panel) = panel {
 6924                                dock.update(cx, |dock, cx| {
 6925                                    dock.set_panel_size_state(
 6926                                        panel.as_ref(),
 6927                                        dock::PanelSizeState::default(),
 6928                                        cx,
 6929                                    );
 6930                                });
 6931                            }
 6932                            return;
 6933                        }
 6934                    }
 6935                },
 6936            ))
 6937            .on_action(cx.listener(
 6938                |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
 6939                    for dock in workspace.all_docks() {
 6940                        let panel = dock.read(cx).visible_panel().cloned();
 6941                        if let Some(panel) = panel {
 6942                            dock.update(cx, |dock, cx| {
 6943                                dock.set_panel_size_state(
 6944                                    panel.as_ref(),
 6945                                    dock::PanelSizeState::default(),
 6946                                    cx,
 6947                                );
 6948                            });
 6949                        }
 6950                    }
 6951                },
 6952            ))
 6953            .on_action(cx.listener(
 6954                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 6955                    adjust_active_dock_size_by_px(
 6956                        px_with_ui_font_fallback(act.px, cx),
 6957                        workspace,
 6958                        window,
 6959                        cx,
 6960                    );
 6961                },
 6962            ))
 6963            .on_action(cx.listener(
 6964                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 6965                    adjust_active_dock_size_by_px(
 6966                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6967                        workspace,
 6968                        window,
 6969                        cx,
 6970                    );
 6971                },
 6972            ))
 6973            .on_action(cx.listener(
 6974                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 6975                    adjust_open_docks_size_by_px(
 6976                        px_with_ui_font_fallback(act.px, cx),
 6977                        workspace,
 6978                        window,
 6979                        cx,
 6980                    );
 6981                },
 6982            ))
 6983            .on_action(cx.listener(
 6984                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 6985                    adjust_open_docks_size_by_px(
 6986                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6987                        workspace,
 6988                        window,
 6989                        cx,
 6990                    );
 6991                },
 6992            ))
 6993            .on_action(cx.listener(Workspace::toggle_centered_layout))
 6994            .on_action(cx.listener(
 6995                |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
 6996                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6997                        let dock = active_dock.read(cx);
 6998                        if let Some(active_panel) = dock.active_panel() {
 6999                            if active_panel.pane(cx).is_none() {
 7000                                let mut recent_pane: Option<Entity<Pane>> = None;
 7001                                let mut recent_timestamp = 0;
 7002                                for pane_handle in workspace.panes() {
 7003                                    let pane = pane_handle.read(cx);
 7004                                    for entry in pane.activation_history() {
 7005                                        if entry.timestamp > recent_timestamp {
 7006                                            recent_timestamp = entry.timestamp;
 7007                                            recent_pane = Some(pane_handle.clone());
 7008                                        }
 7009                                    }
 7010                                }
 7011
 7012                                if let Some(pane) = recent_pane {
 7013                                    pane.update(cx, |pane, cx| {
 7014                                        let current_index = pane.active_item_index();
 7015                                        let items_len = pane.items_len();
 7016                                        if items_len > 0 {
 7017                                            let next_index = if current_index + 1 < items_len {
 7018                                                current_index + 1
 7019                                            } else {
 7020                                                0
 7021                                            };
 7022                                            pane.activate_item(
 7023                                                next_index, false, false, window, cx,
 7024                                            );
 7025                                        }
 7026                                    });
 7027                                    return;
 7028                                }
 7029                            }
 7030                        }
 7031                    }
 7032                    cx.propagate();
 7033                },
 7034            ))
 7035            .on_action(cx.listener(
 7036                |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
 7037                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7038                        let dock = active_dock.read(cx);
 7039                        if let Some(active_panel) = dock.active_panel() {
 7040                            if active_panel.pane(cx).is_none() {
 7041                                let mut recent_pane: Option<Entity<Pane>> = None;
 7042                                let mut recent_timestamp = 0;
 7043                                for pane_handle in workspace.panes() {
 7044                                    let pane = pane_handle.read(cx);
 7045                                    for entry in pane.activation_history() {
 7046                                        if entry.timestamp > recent_timestamp {
 7047                                            recent_timestamp = entry.timestamp;
 7048                                            recent_pane = Some(pane_handle.clone());
 7049                                        }
 7050                                    }
 7051                                }
 7052
 7053                                if let Some(pane) = recent_pane {
 7054                                    pane.update(cx, |pane, cx| {
 7055                                        let current_index = pane.active_item_index();
 7056                                        let items_len = pane.items_len();
 7057                                        if items_len > 0 {
 7058                                            let prev_index = if current_index > 0 {
 7059                                                current_index - 1
 7060                                            } else {
 7061                                                items_len.saturating_sub(1)
 7062                                            };
 7063                                            pane.activate_item(
 7064                                                prev_index, false, false, window, cx,
 7065                                            );
 7066                                        }
 7067                                    });
 7068                                    return;
 7069                                }
 7070                            }
 7071                        }
 7072                    }
 7073                    cx.propagate();
 7074                },
 7075            ))
 7076            .on_action(cx.listener(
 7077                |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
 7078                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 7079                        let dock = active_dock.read(cx);
 7080                        if let Some(active_panel) = dock.active_panel() {
 7081                            if active_panel.pane(cx).is_none() {
 7082                                let active_pane = workspace.active_pane().clone();
 7083                                active_pane.update(cx, |pane, cx| {
 7084                                    pane.close_active_item(action, window, cx)
 7085                                        .detach_and_log_err(cx);
 7086                                });
 7087                                return;
 7088                            }
 7089                        }
 7090                    }
 7091                    cx.propagate();
 7092                },
 7093            ))
 7094            .on_action(
 7095                cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
 7096                    let pane = workspace.active_pane().clone();
 7097                    if let Some(item) = pane.read(cx).active_item() {
 7098                        item.toggle_read_only(window, cx);
 7099                    }
 7100                }),
 7101            )
 7102            .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
 7103                workspace.focus_center_pane(window, cx);
 7104            }))
 7105            .on_action(cx.listener(Workspace::cancel))
 7106    }
 7107
 7108    #[cfg(any(test, feature = "test-support"))]
 7109    pub fn set_random_database_id(&mut self) {
 7110        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 7111    }
 7112
 7113    #[cfg(any(test, feature = "test-support"))]
 7114    pub(crate) fn test_new(
 7115        project: Entity<Project>,
 7116        window: &mut Window,
 7117        cx: &mut Context<Self>,
 7118    ) -> Self {
 7119        use node_runtime::NodeRuntime;
 7120        use session::Session;
 7121
 7122        let client = project.read(cx).client();
 7123        let user_store = project.read(cx).user_store();
 7124        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 7125        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 7126        window.activate_window();
 7127        let app_state = Arc::new(AppState {
 7128            languages: project.read(cx).languages().clone(),
 7129            workspace_store,
 7130            client,
 7131            user_store,
 7132            fs: project.read(cx).fs().clone(),
 7133            build_window_options: |_, _| Default::default(),
 7134            node_runtime: NodeRuntime::unavailable(),
 7135            session,
 7136        });
 7137        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 7138        workspace
 7139            .active_pane
 7140            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
 7141        workspace
 7142    }
 7143
 7144    pub fn register_action<A: Action>(
 7145        &mut self,
 7146        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 7147    ) -> &mut Self {
 7148        let callback = Arc::new(callback);
 7149
 7150        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 7151            let callback = callback.clone();
 7152            div.on_action(cx.listener(move |workspace, event, window, cx| {
 7153                (callback)(workspace, event, window, cx)
 7154            }))
 7155        }));
 7156        self
 7157    }
 7158    pub fn register_action_renderer(
 7159        &mut self,
 7160        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 7161    ) -> &mut Self {
 7162        self.workspace_actions.push(Box::new(callback));
 7163        self
 7164    }
 7165
 7166    fn add_workspace_actions_listeners(
 7167        &self,
 7168        mut div: Div,
 7169        window: &mut Window,
 7170        cx: &mut Context<Self>,
 7171    ) -> Div {
 7172        for action in self.workspace_actions.iter() {
 7173            div = (action)(div, self, window, cx)
 7174        }
 7175        div
 7176    }
 7177
 7178    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 7179        self.modal_layer.read(cx).has_active_modal()
 7180    }
 7181
 7182    pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
 7183        self.modal_layer
 7184            .read(cx)
 7185            .is_active_modal_command_palette(cx)
 7186    }
 7187
 7188    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 7189        self.modal_layer.read(cx).active_modal()
 7190    }
 7191
 7192    /// Toggles a modal of type `V`. If a modal of the same type is currently active,
 7193    /// it will be hidden. If a different modal is active, it will be replaced with the new one.
 7194    /// If no modal is active, the new modal will be shown.
 7195    ///
 7196    /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
 7197    /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
 7198    /// will not be shown.
 7199    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 7200    where
 7201        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 7202    {
 7203        self.modal_layer.update(cx, |modal_layer, cx| {
 7204            modal_layer.toggle_modal(window, cx, build)
 7205        })
 7206    }
 7207
 7208    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 7209        self.modal_layer
 7210            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 7211    }
 7212
 7213    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 7214        self.toast_layer
 7215            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 7216    }
 7217
 7218    pub fn toggle_centered_layout(
 7219        &mut self,
 7220        _: &ToggleCenteredLayout,
 7221        _: &mut Window,
 7222        cx: &mut Context<Self>,
 7223    ) {
 7224        self.centered_layout = !self.centered_layout;
 7225        if let Some(database_id) = self.database_id() {
 7226            let db = WorkspaceDb::global(cx);
 7227            let centered_layout = self.centered_layout;
 7228            cx.background_spawn(async move {
 7229                db.set_centered_layout(database_id, centered_layout).await
 7230            })
 7231            .detach_and_log_err(cx);
 7232        }
 7233        cx.notify();
 7234    }
 7235
 7236    fn adjust_padding(padding: Option<f32>) -> f32 {
 7237        padding
 7238            .unwrap_or(CenteredPaddingSettings::default().0)
 7239            .clamp(
 7240                CenteredPaddingSettings::MIN_PADDING,
 7241                CenteredPaddingSettings::MAX_PADDING,
 7242            )
 7243    }
 7244
 7245    fn render_dock(
 7246        &self,
 7247        position: DockPosition,
 7248        dock: &Entity<Dock>,
 7249        window: &mut Window,
 7250        cx: &mut App,
 7251    ) -> Option<Div> {
 7252        if self.zoomed_position == Some(position) {
 7253            return None;
 7254        }
 7255
 7256        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 7257            let pane = panel.pane(cx)?;
 7258            let follower_states = &self.follower_states;
 7259            leader_border_for_pane(follower_states, &pane, window, cx)
 7260        });
 7261
 7262        Some(
 7263            div()
 7264                .flex()
 7265                .flex_none()
 7266                .overflow_hidden()
 7267                .child(dock.clone())
 7268                .children(leader_border),
 7269        )
 7270    }
 7271
 7272    pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
 7273        window
 7274            .root::<MultiWorkspace>()
 7275            .flatten()
 7276            .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
 7277    }
 7278
 7279    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 7280        self.zoomed.as_ref()
 7281    }
 7282
 7283    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 7284        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7285            return;
 7286        };
 7287        let windows = cx.windows();
 7288        let next_window =
 7289            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 7290                || {
 7291                    windows
 7292                        .iter()
 7293                        .cycle()
 7294                        .skip_while(|window| window.window_id() != current_window_id)
 7295                        .nth(1)
 7296                },
 7297            );
 7298
 7299        if let Some(window) = next_window {
 7300            window
 7301                .update(cx, |_, window, _| window.activate_window())
 7302                .ok();
 7303        }
 7304    }
 7305
 7306    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 7307        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 7308            return;
 7309        };
 7310        let windows = cx.windows();
 7311        let prev_window =
 7312            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 7313                || {
 7314                    windows
 7315                        .iter()
 7316                        .rev()
 7317                        .cycle()
 7318                        .skip_while(|window| window.window_id() != current_window_id)
 7319                        .nth(1)
 7320                },
 7321            );
 7322
 7323        if let Some(window) = prev_window {
 7324            window
 7325                .update(cx, |_, window, _| window.activate_window())
 7326                .ok();
 7327        }
 7328    }
 7329
 7330    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 7331        if cx.stop_active_drag(window) {
 7332        } else if let Some((notification_id, _)) = self.notifications.pop() {
 7333            dismiss_app_notification(&notification_id, cx);
 7334        } else {
 7335            cx.propagate();
 7336        }
 7337    }
 7338
 7339    fn adjust_dock_size_by_px(
 7340        &mut self,
 7341        panel_size: Pixels,
 7342        dock_pos: DockPosition,
 7343        px: Pixels,
 7344        window: &mut Window,
 7345        cx: &mut Context<Self>,
 7346    ) {
 7347        match dock_pos {
 7348            DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
 7349            DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
 7350            DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
 7351        }
 7352    }
 7353
 7354    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7355        let workspace_width = self.bounds.size.width;
 7356        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7357
 7358        self.right_dock.read_with(cx, |right_dock, cx| {
 7359            let right_dock_size = right_dock
 7360                .stored_active_panel_size(window, cx)
 7361                .unwrap_or(Pixels::ZERO);
 7362            if right_dock_size + size > workspace_width {
 7363                size = workspace_width - right_dock_size
 7364            }
 7365        });
 7366
 7367        let ratio = self.flexible_dock_ratio_for_size(DockPosition::Left, size, window, cx);
 7368        self.left_dock.update(cx, |left_dock, cx| {
 7369            if WorkspaceSettings::get_global(cx)
 7370                .resize_all_panels_in_dock
 7371                .contains(&DockPosition::Left)
 7372            {
 7373                left_dock.resize_all_panels(Some(size), ratio, window, cx);
 7374            } else {
 7375                left_dock.resize_active_panel(Some(size), ratio, window, cx);
 7376            }
 7377        });
 7378    }
 7379
 7380    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7381        let workspace_width = self.bounds.size.width;
 7382        let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
 7383        self.left_dock.read_with(cx, |left_dock, cx| {
 7384            let left_dock_size = left_dock
 7385                .stored_active_panel_size(window, cx)
 7386                .unwrap_or(Pixels::ZERO);
 7387            if left_dock_size + size > workspace_width {
 7388                size = workspace_width - left_dock_size
 7389            }
 7390        });
 7391        let ratio = self.flexible_dock_ratio_for_size(DockPosition::Right, size, window, cx);
 7392        self.right_dock.update(cx, |right_dock, cx| {
 7393            if WorkspaceSettings::get_global(cx)
 7394                .resize_all_panels_in_dock
 7395                .contains(&DockPosition::Right)
 7396            {
 7397                right_dock.resize_all_panels(Some(size), ratio, window, cx);
 7398            } else {
 7399                right_dock.resize_active_panel(Some(size), ratio, window, cx);
 7400            }
 7401        });
 7402    }
 7403
 7404    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 7405        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 7406        self.bottom_dock.update(cx, |bottom_dock, cx| {
 7407            if WorkspaceSettings::get_global(cx)
 7408                .resize_all_panels_in_dock
 7409                .contains(&DockPosition::Bottom)
 7410            {
 7411                bottom_dock.resize_all_panels(Some(size), None, window, cx);
 7412            } else {
 7413                bottom_dock.resize_active_panel(Some(size), None, window, cx);
 7414            }
 7415        });
 7416    }
 7417
 7418    fn toggle_edit_predictions_all_files(
 7419        &mut self,
 7420        _: &ToggleEditPrediction,
 7421        _window: &mut Window,
 7422        cx: &mut Context<Self>,
 7423    ) {
 7424        let fs = self.project().read(cx).fs().clone();
 7425        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 7426        update_settings_file(fs, cx, move |file, _| {
 7427            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 7428        });
 7429    }
 7430
 7431    fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
 7432        let current_mode = ThemeSettings::get_global(cx).theme.mode();
 7433        let next_mode = match current_mode {
 7434            Some(theme::ThemeAppearanceMode::Light) => theme::ThemeAppearanceMode::Dark,
 7435            Some(theme::ThemeAppearanceMode::Dark) => theme::ThemeAppearanceMode::Light,
 7436            Some(theme::ThemeAppearanceMode::System) | None => match cx.theme().appearance() {
 7437                theme::Appearance::Light => theme::ThemeAppearanceMode::Dark,
 7438                theme::Appearance::Dark => theme::ThemeAppearanceMode::Light,
 7439            },
 7440        };
 7441
 7442        let fs = self.project().read(cx).fs().clone();
 7443        settings::update_settings_file(fs, cx, move |settings, _cx| {
 7444            theme::set_mode(settings, next_mode);
 7445        });
 7446    }
 7447
 7448    pub fn show_worktree_trust_security_modal(
 7449        &mut self,
 7450        toggle: bool,
 7451        window: &mut Window,
 7452        cx: &mut Context<Self>,
 7453    ) {
 7454        if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
 7455            if toggle {
 7456                security_modal.update(cx, |security_modal, cx| {
 7457                    security_modal.dismiss(cx);
 7458                })
 7459            } else {
 7460                security_modal.update(cx, |security_modal, cx| {
 7461                    security_modal.refresh_restricted_paths(cx);
 7462                });
 7463            }
 7464        } else {
 7465            let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
 7466                .map(|trusted_worktrees| {
 7467                    trusted_worktrees
 7468                        .read(cx)
 7469                        .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
 7470                })
 7471                .unwrap_or(false);
 7472            if has_restricted_worktrees {
 7473                let project = self.project().read(cx);
 7474                let remote_host = project
 7475                    .remote_connection_options(cx)
 7476                    .map(RemoteHostLocation::from);
 7477                let worktree_store = project.worktree_store().downgrade();
 7478                self.toggle_modal(window, cx, |_, cx| {
 7479                    SecurityModal::new(worktree_store, remote_host, cx)
 7480                });
 7481            }
 7482        }
 7483    }
 7484}
 7485
 7486pub trait AnyActiveCall {
 7487    fn entity(&self) -> AnyEntity;
 7488    fn is_in_room(&self, _: &App) -> bool;
 7489    fn room_id(&self, _: &App) -> Option<u64>;
 7490    fn channel_id(&self, _: &App) -> Option<ChannelId>;
 7491    fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
 7492    fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
 7493    fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
 7494    fn is_sharing_project(&self, _: &App) -> bool;
 7495    fn has_remote_participants(&self, _: &App) -> bool;
 7496    fn local_participant_is_guest(&self, _: &App) -> bool;
 7497    fn client(&self, _: &App) -> Arc<Client>;
 7498    fn share_on_join(&self, _: &App) -> bool;
 7499    fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
 7500    fn room_update_completed(&self, _: &mut App) -> Task<()>;
 7501    fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
 7502    fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
 7503    fn join_project(
 7504        &self,
 7505        _: u64,
 7506        _: Arc<LanguageRegistry>,
 7507        _: Arc<dyn Fs>,
 7508        _: &mut App,
 7509    ) -> Task<Result<Entity<Project>>>;
 7510    fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
 7511    fn subscribe(
 7512        &self,
 7513        _: &mut Window,
 7514        _: &mut Context<Workspace>,
 7515        _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
 7516    ) -> Subscription;
 7517    fn create_shared_screen(
 7518        &self,
 7519        _: PeerId,
 7520        _: &Entity<Pane>,
 7521        _: &mut Window,
 7522        _: &mut App,
 7523    ) -> Option<Entity<SharedScreen>>;
 7524}
 7525
 7526#[derive(Clone)]
 7527pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
 7528impl Global for GlobalAnyActiveCall {}
 7529
 7530impl GlobalAnyActiveCall {
 7531    pub(crate) fn try_global(cx: &App) -> Option<&Self> {
 7532        cx.try_global()
 7533    }
 7534
 7535    pub(crate) fn global(cx: &App) -> &Self {
 7536        cx.global()
 7537    }
 7538}
 7539
 7540pub fn merge_conflict_notification_id() -> NotificationId {
 7541    struct MergeConflictNotification;
 7542    NotificationId::unique::<MergeConflictNotification>()
 7543}
 7544
 7545/// Workspace-local view of a remote participant's location.
 7546#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 7547pub enum ParticipantLocation {
 7548    SharedProject { project_id: u64 },
 7549    UnsharedProject,
 7550    External,
 7551}
 7552
 7553impl ParticipantLocation {
 7554    pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
 7555        match location
 7556            .and_then(|l| l.variant)
 7557            .context("participant location was not provided")?
 7558        {
 7559            proto::participant_location::Variant::SharedProject(project) => {
 7560                Ok(Self::SharedProject {
 7561                    project_id: project.id,
 7562                })
 7563            }
 7564            proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
 7565            proto::participant_location::Variant::External(_) => Ok(Self::External),
 7566        }
 7567    }
 7568}
 7569/// Workspace-local view of a remote collaborator's state.
 7570/// This is the subset of `call::RemoteParticipant` that workspace needs.
 7571#[derive(Clone)]
 7572pub struct RemoteCollaborator {
 7573    pub user: Arc<User>,
 7574    pub peer_id: PeerId,
 7575    pub location: ParticipantLocation,
 7576    pub participant_index: ParticipantIndex,
 7577}
 7578
 7579pub enum ActiveCallEvent {
 7580    ParticipantLocationChanged { participant_id: PeerId },
 7581    RemoteVideoTracksChanged { participant_id: PeerId },
 7582}
 7583
 7584fn leader_border_for_pane(
 7585    follower_states: &HashMap<CollaboratorId, FollowerState>,
 7586    pane: &Entity<Pane>,
 7587    _: &Window,
 7588    cx: &App,
 7589) -> Option<Div> {
 7590    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 7591        if state.pane() == pane {
 7592            Some((*leader_id, state))
 7593        } else {
 7594            None
 7595        }
 7596    })?;
 7597
 7598    let mut leader_color = match leader_id {
 7599        CollaboratorId::PeerId(leader_peer_id) => {
 7600            let leader = GlobalAnyActiveCall::try_global(cx)?
 7601                .0
 7602                .remote_participant_for_peer_id(leader_peer_id, cx)?;
 7603
 7604            cx.theme()
 7605                .players()
 7606                .color_for_participant(leader.participant_index.0)
 7607                .cursor
 7608        }
 7609        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 7610    };
 7611    leader_color.fade_out(0.3);
 7612    Some(
 7613        div()
 7614            .absolute()
 7615            .size_full()
 7616            .left_0()
 7617            .top_0()
 7618            .border_2()
 7619            .border_color(leader_color),
 7620    )
 7621}
 7622
 7623fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 7624    ZED_WINDOW_POSITION
 7625        .zip(*ZED_WINDOW_SIZE)
 7626        .map(|(position, size)| Bounds {
 7627            origin: position,
 7628            size,
 7629        })
 7630}
 7631
 7632fn open_items(
 7633    serialized_workspace: Option<SerializedWorkspace>,
 7634    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 7635    window: &mut Window,
 7636    cx: &mut Context<Workspace>,
 7637) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 7638    let restored_items = serialized_workspace.map(|serialized_workspace| {
 7639        Workspace::load_workspace(
 7640            serialized_workspace,
 7641            project_paths_to_open
 7642                .iter()
 7643                .map(|(_, project_path)| project_path)
 7644                .cloned()
 7645                .collect(),
 7646            window,
 7647            cx,
 7648        )
 7649    });
 7650
 7651    cx.spawn_in(window, async move |workspace, cx| {
 7652        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 7653
 7654        if let Some(restored_items) = restored_items {
 7655            let restored_items = restored_items.await?;
 7656
 7657            let restored_project_paths = restored_items
 7658                .iter()
 7659                .filter_map(|item| {
 7660                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 7661                        .ok()
 7662                        .flatten()
 7663                })
 7664                .collect::<HashSet<_>>();
 7665
 7666            for restored_item in restored_items {
 7667                opened_items.push(restored_item.map(Ok));
 7668            }
 7669
 7670            project_paths_to_open
 7671                .iter_mut()
 7672                .for_each(|(_, project_path)| {
 7673                    if let Some(project_path_to_open) = project_path
 7674                        && restored_project_paths.contains(project_path_to_open)
 7675                    {
 7676                        *project_path = None;
 7677                    }
 7678                });
 7679        } else {
 7680            for _ in 0..project_paths_to_open.len() {
 7681                opened_items.push(None);
 7682            }
 7683        }
 7684        assert!(opened_items.len() == project_paths_to_open.len());
 7685
 7686        let tasks =
 7687            project_paths_to_open
 7688                .into_iter()
 7689                .enumerate()
 7690                .map(|(ix, (abs_path, project_path))| {
 7691                    let workspace = workspace.clone();
 7692                    cx.spawn(async move |cx| {
 7693                        let file_project_path = project_path?;
 7694                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 7695                            workspace.project().update(cx, |project, cx| {
 7696                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 7697                            })
 7698                        });
 7699
 7700                        // We only want to open file paths here. If one of the items
 7701                        // here is a directory, it was already opened further above
 7702                        // with a `find_or_create_worktree`.
 7703                        if let Ok(task) = abs_path_task
 7704                            && task.await.is_none_or(|p| p.is_file())
 7705                        {
 7706                            return Some((
 7707                                ix,
 7708                                workspace
 7709                                    .update_in(cx, |workspace, window, cx| {
 7710                                        workspace.open_path(
 7711                                            file_project_path,
 7712                                            None,
 7713                                            true,
 7714                                            window,
 7715                                            cx,
 7716                                        )
 7717                                    })
 7718                                    .log_err()?
 7719                                    .await,
 7720                            ));
 7721                        }
 7722                        None
 7723                    })
 7724                });
 7725
 7726        let tasks = tasks.collect::<Vec<_>>();
 7727
 7728        let tasks = futures::future::join_all(tasks);
 7729        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 7730            opened_items[ix] = Some(path_open_result);
 7731        }
 7732
 7733        Ok(opened_items)
 7734    })
 7735}
 7736
 7737#[derive(Clone)]
 7738enum ActivateInDirectionTarget {
 7739    Pane(Entity<Pane>),
 7740    Dock(Entity<Dock>),
 7741    Sidebar(FocusHandle),
 7742}
 7743
 7744fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
 7745    window
 7746        .update(cx, |multi_workspace, _, cx| {
 7747            let workspace = multi_workspace.workspace().clone();
 7748            workspace.update(cx, |workspace, cx| {
 7749                if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 7750                    struct DatabaseFailedNotification;
 7751
 7752                    workspace.show_notification(
 7753                        NotificationId::unique::<DatabaseFailedNotification>(),
 7754                        cx,
 7755                        |cx| {
 7756                            cx.new(|cx| {
 7757                                MessageNotification::new("Failed to load the database file.", cx)
 7758                                    .primary_message("File an Issue")
 7759                                    .primary_icon(IconName::Plus)
 7760                                    .primary_on_click(|window, cx| {
 7761                                        window.dispatch_action(Box::new(FileBugReport), cx)
 7762                                    })
 7763                            })
 7764                        },
 7765                    );
 7766                }
 7767            });
 7768        })
 7769        .log_err();
 7770}
 7771
 7772fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 7773    if val == 0 {
 7774        ThemeSettings::get_global(cx).ui_font_size(cx)
 7775    } else {
 7776        px(val as f32)
 7777    }
 7778}
 7779
 7780fn adjust_active_dock_size_by_px(
 7781    px: Pixels,
 7782    workspace: &mut Workspace,
 7783    window: &mut Window,
 7784    cx: &mut Context<Workspace>,
 7785) {
 7786    let Some(active_dock) = workspace
 7787        .all_docks()
 7788        .into_iter()
 7789        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 7790    else {
 7791        return;
 7792    };
 7793    let dock = active_dock.read(cx);
 7794    let Some(panel_size) = dock
 7795        .active_panel()
 7796        .map(|panel| workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx))
 7797    else {
 7798        return;
 7799    };
 7800    let dock_pos = dock.position();
 7801    workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
 7802}
 7803
 7804fn adjust_open_docks_size_by_px(
 7805    px: Pixels,
 7806    workspace: &mut Workspace,
 7807    window: &mut Window,
 7808    cx: &mut Context<Workspace>,
 7809) {
 7810    let docks = workspace
 7811        .all_docks()
 7812        .into_iter()
 7813        .filter_map(|dock_entity| {
 7814            let dock = dock_entity.read(cx);
 7815            if dock.is_open() {
 7816                let panel_size = dock.active_panel().map(|panel| {
 7817                    workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx)
 7818                })?;
 7819                let dock_pos = dock.position();
 7820                Some((panel_size, dock_pos, px))
 7821            } else {
 7822                None
 7823            }
 7824        })
 7825        .collect::<Vec<_>>();
 7826
 7827    docks
 7828        .into_iter()
 7829        .for_each(|(panel_size, dock_pos, offset)| {
 7830            workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
 7831        });
 7832}
 7833
 7834impl Focusable for Workspace {
 7835    fn focus_handle(&self, cx: &App) -> FocusHandle {
 7836        self.active_pane.focus_handle(cx)
 7837    }
 7838}
 7839
 7840#[derive(Clone)]
 7841struct DraggedDock(DockPosition);
 7842
 7843impl Render for DraggedDock {
 7844    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 7845        gpui::Empty
 7846    }
 7847}
 7848
 7849impl Render for Workspace {
 7850    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 7851        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 7852        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 7853            log::info!("Rendered first frame");
 7854        }
 7855
 7856        let centered_layout = self.centered_layout
 7857            && self.center.panes().len() == 1
 7858            && self.active_item(cx).is_some();
 7859        let render_padding = |size| {
 7860            (size > 0.0).then(|| {
 7861                div()
 7862                    .h_full()
 7863                    .w(relative(size))
 7864                    .bg(cx.theme().colors().editor_background)
 7865                    .border_color(cx.theme().colors().pane_group_border)
 7866            })
 7867        };
 7868        let paddings = if centered_layout {
 7869            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 7870            (
 7871                render_padding(Self::adjust_padding(
 7872                    settings.left_padding.map(|padding| padding.0),
 7873                )),
 7874                render_padding(Self::adjust_padding(
 7875                    settings.right_padding.map(|padding| padding.0),
 7876                )),
 7877            )
 7878        } else {
 7879            (None, None)
 7880        };
 7881        let ui_font = theme::setup_ui_font(window, cx);
 7882
 7883        let theme = cx.theme().clone();
 7884        let colors = theme.colors();
 7885        let notification_entities = self
 7886            .notifications
 7887            .iter()
 7888            .map(|(_, notification)| notification.entity_id())
 7889            .collect::<Vec<_>>();
 7890        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 7891
 7892        div()
 7893            .relative()
 7894            .size_full()
 7895            .flex()
 7896            .flex_col()
 7897            .font(ui_font)
 7898            .gap_0()
 7899                .justify_start()
 7900                .items_start()
 7901                .text_color(colors.text)
 7902                .overflow_hidden()
 7903                .children(self.titlebar_item.clone())
 7904                .on_modifiers_changed(move |_, _, cx| {
 7905                    for &id in &notification_entities {
 7906                        cx.notify(id);
 7907                    }
 7908                })
 7909                .child(
 7910                    div()
 7911                        .size_full()
 7912                        .relative()
 7913                        .flex_1()
 7914                        .flex()
 7915                        .flex_col()
 7916                        .child(
 7917                            div()
 7918                                .id("workspace")
 7919                                .bg(colors.background)
 7920                                .relative()
 7921                                .flex_1()
 7922                                .w_full()
 7923                                .flex()
 7924                                .flex_col()
 7925                                .overflow_hidden()
 7926                                .border_t_1()
 7927                                .border_b_1()
 7928                                .border_color(colors.border)
 7929                                .child({
 7930                                    let this = cx.entity();
 7931                                    canvas(
 7932                                        move |bounds, window, cx| {
 7933                                            this.update(cx, |this, cx| {
 7934                                                let bounds_changed = this.bounds != bounds;
 7935                                                this.bounds = bounds;
 7936
 7937                                                if bounds_changed {
 7938                                                    this.left_dock.update(cx, |dock, cx| {
 7939                                                        dock.clamp_panel_size(
 7940                                                            bounds.size.width,
 7941                                                            window,
 7942                                                            cx,
 7943                                                        )
 7944                                                    });
 7945
 7946                                                    this.right_dock.update(cx, |dock, cx| {
 7947                                                        dock.clamp_panel_size(
 7948                                                            bounds.size.width,
 7949                                                            window,
 7950                                                            cx,
 7951                                                        )
 7952                                                    });
 7953
 7954                                                    this.bottom_dock.update(cx, |dock, cx| {
 7955                                                        dock.clamp_panel_size(
 7956                                                            bounds.size.height,
 7957                                                            window,
 7958                                                            cx,
 7959                                                        )
 7960                                                    });
 7961                                                }
 7962                                            })
 7963                                        },
 7964                                        |_, _, _, _| {},
 7965                                    )
 7966                                    .absolute()
 7967                                    .size_full()
 7968                                })
 7969                                .when(self.zoomed.is_none(), |this| {
 7970                                    this.on_drag_move(cx.listener(
 7971                                        move |workspace,
 7972                                              e: &DragMoveEvent<DraggedDock>,
 7973                                              window,
 7974                                              cx| {
 7975                                            if workspace.previous_dock_drag_coordinates
 7976                                                != Some(e.event.position)
 7977                                            {
 7978                                                workspace.previous_dock_drag_coordinates =
 7979                                                    Some(e.event.position);
 7980
 7981                                                match e.drag(cx).0 {
 7982                                                    DockPosition::Left => {
 7983                                                        workspace.resize_left_dock(
 7984                                                            e.event.position.x
 7985                                                                - workspace.bounds.left(),
 7986                                                            window,
 7987                                                            cx,
 7988                                                        );
 7989                                                    }
 7990                                                    DockPosition::Right => {
 7991                                                        workspace.resize_right_dock(
 7992                                                            workspace.bounds.right()
 7993                                                                - e.event.position.x,
 7994                                                            window,
 7995                                                            cx,
 7996                                                        );
 7997                                                    }
 7998                                                    DockPosition::Bottom => {
 7999                                                        workspace.resize_bottom_dock(
 8000                                                            workspace.bounds.bottom()
 8001                                                                - e.event.position.y,
 8002                                                            window,
 8003                                                            cx,
 8004                                                        );
 8005                                                    }
 8006                                                };
 8007                                                workspace.serialize_workspace(window, cx);
 8008                                            }
 8009                                        },
 8010                                    ))
 8011
 8012                                })
 8013                                .child({
 8014                                    match bottom_dock_layout {
 8015                                        BottomDockLayout::Full => div()
 8016                                            .flex()
 8017                                            .flex_col()
 8018                                            .h_full()
 8019                                            .child(
 8020                                                div()
 8021                                                    .flex()
 8022                                                    .flex_row()
 8023                                                    .flex_1()
 8024                                                    .overflow_hidden()
 8025                                                    .children(self.render_dock(
 8026                                                        DockPosition::Left,
 8027                                                        &self.left_dock,
 8028                                                        window,
 8029                                                        cx,
 8030                                                    ))
 8031
 8032                                                    .child(
 8033                                                        div()
 8034                                                            .flex()
 8035                                                            .flex_col()
 8036                                                            .flex_1()
 8037                                                            .overflow_hidden()
 8038                                                            .child(
 8039                                                                h_flex()
 8040                                                                    .flex_1()
 8041                                                                    .when_some(
 8042                                                                        paddings.0,
 8043                                                                        |this, p| {
 8044                                                                            this.child(
 8045                                                                                p.border_r_1(),
 8046                                                                            )
 8047                                                                        },
 8048                                                                    )
 8049                                                                    .child(self.center.render(
 8050                                                                        self.zoomed.as_ref(),
 8051                                                                        &PaneRenderContext {
 8052                                                                            follower_states:
 8053                                                                                &self.follower_states,
 8054                                                                            active_call: self.active_call(),
 8055                                                                            active_pane: &self.active_pane,
 8056                                                                            app_state: &self.app_state,
 8057                                                                            project: &self.project,
 8058                                                                            workspace: &self.weak_self,
 8059                                                                        },
 8060                                                                        window,
 8061                                                                        cx,
 8062                                                                    ))
 8063                                                                    .when_some(
 8064                                                                        paddings.1,
 8065                                                                        |this, p| {
 8066                                                                            this.child(
 8067                                                                                p.border_l_1(),
 8068                                                                            )
 8069                                                                        },
 8070                                                                    ),
 8071                                                            ),
 8072                                                    )
 8073
 8074                                                    .children(self.render_dock(
 8075                                                        DockPosition::Right,
 8076                                                        &self.right_dock,
 8077                                                        window,
 8078                                                        cx,
 8079                                                    )),
 8080                                            )
 8081                                            .child(div().w_full().children(self.render_dock(
 8082                                                DockPosition::Bottom,
 8083                                                &self.bottom_dock,
 8084                                                window,
 8085                                                cx
 8086                                            ))),
 8087
 8088                                        BottomDockLayout::LeftAligned => div()
 8089                                            .flex()
 8090                                            .flex_row()
 8091                                            .h_full()
 8092                                            .child(
 8093                                                div()
 8094                                                    .flex()
 8095                                                    .flex_col()
 8096                                                    .flex_1()
 8097                                                    .h_full()
 8098                                                    .child(
 8099                                                        div()
 8100                                                            .flex()
 8101                                                            .flex_row()
 8102                                                            .flex_1()
 8103                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 8104
 8105                                                            .child(
 8106                                                                div()
 8107                                                                    .flex()
 8108                                                                    .flex_col()
 8109                                                                    .flex_1()
 8110                                                                    .overflow_hidden()
 8111                                                                    .child(
 8112                                                                        h_flex()
 8113                                                                            .flex_1()
 8114                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8115                                                                            .child(self.center.render(
 8116                                                                                self.zoomed.as_ref(),
 8117                                                                                &PaneRenderContext {
 8118                                                                                    follower_states:
 8119                                                                                        &self.follower_states,
 8120                                                                                    active_call: self.active_call(),
 8121                                                                                    active_pane: &self.active_pane,
 8122                                                                                    app_state: &self.app_state,
 8123                                                                                    project: &self.project,
 8124                                                                                    workspace: &self.weak_self,
 8125                                                                                },
 8126                                                                                window,
 8127                                                                                cx,
 8128                                                                            ))
 8129                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8130                                                                    )
 8131                                                            )
 8132
 8133                                                    )
 8134                                                    .child(
 8135                                                        div()
 8136                                                            .w_full()
 8137                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8138                                                    ),
 8139                                            )
 8140                                            .children(self.render_dock(
 8141                                                DockPosition::Right,
 8142                                                &self.right_dock,
 8143                                                window,
 8144                                                cx,
 8145                                            )),
 8146                                        BottomDockLayout::RightAligned => div()
 8147                                            .flex()
 8148                                            .flex_row()
 8149                                            .h_full()
 8150                                            .children(self.render_dock(
 8151                                                DockPosition::Left,
 8152                                                &self.left_dock,
 8153                                                window,
 8154                                                cx,
 8155                                            ))
 8156
 8157                                            .child(
 8158                                                div()
 8159                                                    .flex()
 8160                                                    .flex_col()
 8161                                                    .flex_1()
 8162                                                    .h_full()
 8163                                                    .child(
 8164                                                        div()
 8165                                                            .flex()
 8166                                                            .flex_row()
 8167                                                            .flex_1()
 8168                                                            .child(
 8169                                                                div()
 8170                                                                    .flex()
 8171                                                                    .flex_col()
 8172                                                                    .flex_1()
 8173                                                                    .overflow_hidden()
 8174                                                                    .child(
 8175                                                                        h_flex()
 8176                                                                            .flex_1()
 8177                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 8178                                                                            .child(self.center.render(
 8179                                                                                self.zoomed.as_ref(),
 8180                                                                                &PaneRenderContext {
 8181                                                                                    follower_states:
 8182                                                                                        &self.follower_states,
 8183                                                                                    active_call: self.active_call(),
 8184                                                                                    active_pane: &self.active_pane,
 8185                                                                                    app_state: &self.app_state,
 8186                                                                                    project: &self.project,
 8187                                                                                    workspace: &self.weak_self,
 8188                                                                                },
 8189                                                                                window,
 8190                                                                                cx,
 8191                                                                            ))
 8192                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 8193                                                                    )
 8194                                                            )
 8195
 8196                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 8197                                                    )
 8198                                                    .child(
 8199                                                        div()
 8200                                                            .w_full()
 8201                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 8202                                                    ),
 8203                                            ),
 8204                                        BottomDockLayout::Contained => div()
 8205                                            .flex()
 8206                                            .flex_row()
 8207                                            .h_full()
 8208                                            .children(self.render_dock(
 8209                                                DockPosition::Left,
 8210                                                &self.left_dock,
 8211                                                window,
 8212                                                cx,
 8213                                            ))
 8214
 8215                                            .child(
 8216                                                div()
 8217                                                    .flex()
 8218                                                    .flex_col()
 8219                                                    .flex_1()
 8220                                                    .overflow_hidden()
 8221                                                    .child(
 8222                                                        h_flex()
 8223                                                            .flex_1()
 8224                                                            .when_some(paddings.0, |this, p| {
 8225                                                                this.child(p.border_r_1())
 8226                                                            })
 8227                                                            .child(self.center.render(
 8228                                                                self.zoomed.as_ref(),
 8229                                                                &PaneRenderContext {
 8230                                                                    follower_states:
 8231                                                                        &self.follower_states,
 8232                                                                    active_call: self.active_call(),
 8233                                                                    active_pane: &self.active_pane,
 8234                                                                    app_state: &self.app_state,
 8235                                                                    project: &self.project,
 8236                                                                    workspace: &self.weak_self,
 8237                                                                },
 8238                                                                window,
 8239                                                                cx,
 8240                                                            ))
 8241                                                            .when_some(paddings.1, |this, p| {
 8242                                                                this.child(p.border_l_1())
 8243                                                            }),
 8244                                                    )
 8245                                                    .children(self.render_dock(
 8246                                                        DockPosition::Bottom,
 8247                                                        &self.bottom_dock,
 8248                                                        window,
 8249                                                        cx,
 8250                                                    )),
 8251                                            )
 8252
 8253                                            .children(self.render_dock(
 8254                                                DockPosition::Right,
 8255                                                &self.right_dock,
 8256                                                window,
 8257                                                cx,
 8258                                            )),
 8259                                    }
 8260                                })
 8261                                .children(self.zoomed.as_ref().and_then(|view| {
 8262                                    let zoomed_view = view.upgrade()?;
 8263                                    let div = div()
 8264                                        .occlude()
 8265                                        .absolute()
 8266                                        .overflow_hidden()
 8267                                        .border_color(colors.border)
 8268                                        .bg(colors.background)
 8269                                        .child(zoomed_view)
 8270                                        .inset_0()
 8271                                        .shadow_lg();
 8272
 8273                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 8274                                       return Some(div);
 8275                                    }
 8276
 8277                                    Some(match self.zoomed_position {
 8278                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 8279                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 8280                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 8281                                        None => {
 8282                                            div.top_2().bottom_2().left_2().right_2().border_1()
 8283                                        }
 8284                                    })
 8285                                }))
 8286                                .children(self.render_notifications(window, cx)),
 8287                        )
 8288                        .when(self.status_bar_visible(cx), |parent| {
 8289                            parent.child(self.status_bar.clone())
 8290                        })
 8291                        .child(self.toast_layer.clone()),
 8292                )
 8293    }
 8294}
 8295
 8296impl WorkspaceStore {
 8297    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 8298        Self {
 8299            workspaces: Default::default(),
 8300            _subscriptions: vec![
 8301                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 8302                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 8303            ],
 8304            client,
 8305        }
 8306    }
 8307
 8308    pub fn update_followers(
 8309        &self,
 8310        project_id: Option<u64>,
 8311        update: proto::update_followers::Variant,
 8312        cx: &App,
 8313    ) -> Option<()> {
 8314        let active_call = GlobalAnyActiveCall::try_global(cx)?;
 8315        let room_id = active_call.0.room_id(cx)?;
 8316        self.client
 8317            .send(proto::UpdateFollowers {
 8318                room_id,
 8319                project_id,
 8320                variant: Some(update),
 8321            })
 8322            .log_err()
 8323    }
 8324
 8325    pub async fn handle_follow(
 8326        this: Entity<Self>,
 8327        envelope: TypedEnvelope<proto::Follow>,
 8328        mut cx: AsyncApp,
 8329    ) -> Result<proto::FollowResponse> {
 8330        this.update(&mut cx, |this, cx| {
 8331            let follower = Follower {
 8332                project_id: envelope.payload.project_id,
 8333                peer_id: envelope.original_sender_id()?,
 8334            };
 8335
 8336            let mut response = proto::FollowResponse::default();
 8337
 8338            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8339                let Some(workspace) = weak_workspace.upgrade() else {
 8340                    return false;
 8341                };
 8342                window_handle
 8343                    .update(cx, |_, window, cx| {
 8344                        workspace.update(cx, |workspace, cx| {
 8345                            let handler_response =
 8346                                workspace.handle_follow(follower.project_id, window, cx);
 8347                            if let Some(active_view) = handler_response.active_view
 8348                                && workspace.project.read(cx).remote_id() == follower.project_id
 8349                            {
 8350                                response.active_view = Some(active_view)
 8351                            }
 8352                        });
 8353                    })
 8354                    .is_ok()
 8355            });
 8356
 8357            Ok(response)
 8358        })
 8359    }
 8360
 8361    async fn handle_update_followers(
 8362        this: Entity<Self>,
 8363        envelope: TypedEnvelope<proto::UpdateFollowers>,
 8364        mut cx: AsyncApp,
 8365    ) -> Result<()> {
 8366        let leader_id = envelope.original_sender_id()?;
 8367        let update = envelope.payload;
 8368
 8369        this.update(&mut cx, |this, cx| {
 8370            this.workspaces.retain(|(window_handle, weak_workspace)| {
 8371                let Some(workspace) = weak_workspace.upgrade() else {
 8372                    return false;
 8373                };
 8374                window_handle
 8375                    .update(cx, |_, window, cx| {
 8376                        workspace.update(cx, |workspace, cx| {
 8377                            let project_id = workspace.project.read(cx).remote_id();
 8378                            if update.project_id != project_id && update.project_id.is_some() {
 8379                                return;
 8380                            }
 8381                            workspace.handle_update_followers(
 8382                                leader_id,
 8383                                update.clone(),
 8384                                window,
 8385                                cx,
 8386                            );
 8387                        });
 8388                    })
 8389                    .is_ok()
 8390            });
 8391            Ok(())
 8392        })
 8393    }
 8394
 8395    pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
 8396        self.workspaces.iter().map(|(_, weak)| weak)
 8397    }
 8398
 8399    pub fn workspaces_with_windows(
 8400        &self,
 8401    ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
 8402        self.workspaces.iter().map(|(window, weak)| (*window, weak))
 8403    }
 8404}
 8405
 8406impl ViewId {
 8407    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 8408        Ok(Self {
 8409            creator: message
 8410                .creator
 8411                .map(CollaboratorId::PeerId)
 8412                .context("creator is missing")?,
 8413            id: message.id,
 8414        })
 8415    }
 8416
 8417    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 8418        if let CollaboratorId::PeerId(peer_id) = self.creator {
 8419            Some(proto::ViewId {
 8420                creator: Some(peer_id),
 8421                id: self.id,
 8422            })
 8423        } else {
 8424            None
 8425        }
 8426    }
 8427}
 8428
 8429impl FollowerState {
 8430    fn pane(&self) -> &Entity<Pane> {
 8431        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 8432    }
 8433}
 8434
 8435pub trait WorkspaceHandle {
 8436    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 8437}
 8438
 8439impl WorkspaceHandle for Entity<Workspace> {
 8440    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 8441        self.read(cx)
 8442            .worktrees(cx)
 8443            .flat_map(|worktree| {
 8444                let worktree_id = worktree.read(cx).id();
 8445                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 8446                    worktree_id,
 8447                    path: f.path.clone(),
 8448                })
 8449            })
 8450            .collect::<Vec<_>>()
 8451    }
 8452}
 8453
 8454pub async fn last_opened_workspace_location(
 8455    db: &WorkspaceDb,
 8456    fs: &dyn fs::Fs,
 8457) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
 8458    db.last_workspace(fs)
 8459        .await
 8460        .log_err()
 8461        .flatten()
 8462        .map(|(id, location, paths, _timestamp)| (id, location, paths))
 8463}
 8464
 8465pub async fn last_session_workspace_locations(
 8466    db: &WorkspaceDb,
 8467    last_session_id: &str,
 8468    last_session_window_stack: Option<Vec<WindowId>>,
 8469    fs: &dyn fs::Fs,
 8470) -> Option<Vec<SessionWorkspace>> {
 8471    db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
 8472        .await
 8473        .log_err()
 8474}
 8475
 8476pub struct MultiWorkspaceRestoreResult {
 8477    pub window_handle: WindowHandle<MultiWorkspace>,
 8478    pub errors: Vec<anyhow::Error>,
 8479}
 8480
 8481pub async fn restore_multiworkspace(
 8482    multi_workspace: SerializedMultiWorkspace,
 8483    app_state: Arc<AppState>,
 8484    cx: &mut AsyncApp,
 8485) -> anyhow::Result<MultiWorkspaceRestoreResult> {
 8486    let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
 8487    let mut group_iter = workspaces.into_iter();
 8488    let first = group_iter
 8489        .next()
 8490        .context("window group must not be empty")?;
 8491
 8492    let window_handle = if first.paths.is_empty() {
 8493        cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
 8494            .await?
 8495    } else {
 8496        let OpenResult { window, .. } = cx
 8497            .update(|cx| {
 8498                Workspace::new_local(
 8499                    first.paths.paths().to_vec(),
 8500                    app_state.clone(),
 8501                    None,
 8502                    None,
 8503                    None,
 8504                    true,
 8505                    cx,
 8506                )
 8507            })
 8508            .await?;
 8509        window
 8510    };
 8511
 8512    let mut errors = Vec::new();
 8513
 8514    for session_workspace in group_iter {
 8515        let error = if session_workspace.paths.is_empty() {
 8516            cx.update(|cx| {
 8517                open_workspace_by_id(
 8518                    session_workspace.workspace_id,
 8519                    app_state.clone(),
 8520                    Some(window_handle),
 8521                    cx,
 8522                )
 8523            })
 8524            .await
 8525            .err()
 8526        } else {
 8527            cx.update(|cx| {
 8528                Workspace::new_local(
 8529                    session_workspace.paths.paths().to_vec(),
 8530                    app_state.clone(),
 8531                    Some(window_handle),
 8532                    None,
 8533                    None,
 8534                    false,
 8535                    cx,
 8536                )
 8537            })
 8538            .await
 8539            .err()
 8540        };
 8541
 8542        if let Some(error) = error {
 8543            errors.push(error);
 8544        }
 8545    }
 8546
 8547    if let Some(target_id) = state.active_workspace_id {
 8548        window_handle
 8549            .update(cx, |multi_workspace, window, cx| {
 8550                let target_index = multi_workspace
 8551                    .workspaces()
 8552                    .iter()
 8553                    .position(|ws| ws.read(cx).database_id() == Some(target_id));
 8554                if let Some(index) = target_index {
 8555                    multi_workspace.activate_index(index, window, cx);
 8556                } else if !multi_workspace.workspaces().is_empty() {
 8557                    multi_workspace.activate_index(0, window, cx);
 8558                }
 8559            })
 8560            .ok();
 8561    } else {
 8562        window_handle
 8563            .update(cx, |multi_workspace, window, cx| {
 8564                if !multi_workspace.workspaces().is_empty() {
 8565                    multi_workspace.activate_index(0, window, cx);
 8566                }
 8567            })
 8568            .ok();
 8569    }
 8570
 8571    if state.sidebar_open {
 8572        window_handle
 8573            .update(cx, |multi_workspace, _, cx| {
 8574                multi_workspace.open_sidebar(cx);
 8575            })
 8576            .ok();
 8577    }
 8578
 8579    window_handle
 8580        .update(cx, |_, window, _cx| {
 8581            window.activate_window();
 8582        })
 8583        .ok();
 8584
 8585    Ok(MultiWorkspaceRestoreResult {
 8586        window_handle,
 8587        errors,
 8588    })
 8589}
 8590
 8591actions!(
 8592    collab,
 8593    [
 8594        /// Opens the channel notes for the current call.
 8595        ///
 8596        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 8597        /// channel in the collab panel.
 8598        ///
 8599        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 8600        /// can be copied via "Copy link to section" in the context menu of the channel notes
 8601        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 8602        OpenChannelNotes,
 8603        /// Mutes your microphone.
 8604        Mute,
 8605        /// Deafens yourself (mute both microphone and speakers).
 8606        Deafen,
 8607        /// Leaves the current call.
 8608        LeaveCall,
 8609        /// Shares the current project with collaborators.
 8610        ShareProject,
 8611        /// Shares your screen with collaborators.
 8612        ScreenShare,
 8613        /// Copies the current room name and session id for debugging purposes.
 8614        CopyRoomId,
 8615    ]
 8616);
 8617
 8618/// Opens the channel notes for a specific channel by its ID.
 8619#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
 8620#[action(namespace = collab)]
 8621#[serde(deny_unknown_fields)]
 8622pub struct OpenChannelNotesById {
 8623    pub channel_id: u64,
 8624}
 8625
 8626actions!(
 8627    zed,
 8628    [
 8629        /// Opens the Zed log file.
 8630        OpenLog,
 8631        /// Reveals the Zed log file in the system file manager.
 8632        RevealLogInFileManager
 8633    ]
 8634);
 8635
 8636async fn join_channel_internal(
 8637    channel_id: ChannelId,
 8638    app_state: &Arc<AppState>,
 8639    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8640    requesting_workspace: Option<WeakEntity<Workspace>>,
 8641    active_call: &dyn AnyActiveCall,
 8642    cx: &mut AsyncApp,
 8643) -> Result<bool> {
 8644    let (should_prompt, already_in_channel) = cx.update(|cx| {
 8645        if !active_call.is_in_room(cx) {
 8646            return (false, false);
 8647        }
 8648
 8649        let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
 8650        let should_prompt = active_call.is_sharing_project(cx)
 8651            && active_call.has_remote_participants(cx)
 8652            && !already_in_channel;
 8653        (should_prompt, already_in_channel)
 8654    });
 8655
 8656    if already_in_channel {
 8657        let task = cx.update(|cx| {
 8658            if let Some((project, host)) = active_call.most_active_project(cx) {
 8659                Some(join_in_room_project(project, host, app_state.clone(), cx))
 8660            } else {
 8661                None
 8662            }
 8663        });
 8664        if let Some(task) = task {
 8665            task.await?;
 8666        }
 8667        return anyhow::Ok(true);
 8668    }
 8669
 8670    if should_prompt {
 8671        if let Some(multi_workspace) = requesting_window {
 8672            let answer = multi_workspace
 8673                .update(cx, |_, window, cx| {
 8674                    window.prompt(
 8675                        PromptLevel::Warning,
 8676                        "Do you want to switch channels?",
 8677                        Some("Leaving this call will unshare your current project."),
 8678                        &["Yes, Join Channel", "Cancel"],
 8679                        cx,
 8680                    )
 8681                })?
 8682                .await;
 8683
 8684            if answer == Ok(1) {
 8685                return Ok(false);
 8686            }
 8687        } else {
 8688            return Ok(false);
 8689        }
 8690    }
 8691
 8692    let client = cx.update(|cx| active_call.client(cx));
 8693
 8694    let mut client_status = client.status();
 8695
 8696    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 8697    'outer: loop {
 8698        let Some(status) = client_status.recv().await else {
 8699            anyhow::bail!("error connecting");
 8700        };
 8701
 8702        match status {
 8703            Status::Connecting
 8704            | Status::Authenticating
 8705            | Status::Authenticated
 8706            | Status::Reconnecting
 8707            | Status::Reauthenticating
 8708            | Status::Reauthenticated => continue,
 8709            Status::Connected { .. } => break 'outer,
 8710            Status::SignedOut | Status::AuthenticationError => {
 8711                return Err(ErrorCode::SignedOut.into());
 8712            }
 8713            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 8714            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 8715                return Err(ErrorCode::Disconnected.into());
 8716            }
 8717        }
 8718    }
 8719
 8720    let joined = cx
 8721        .update(|cx| active_call.join_channel(channel_id, cx))
 8722        .await?;
 8723
 8724    if !joined {
 8725        return anyhow::Ok(true);
 8726    }
 8727
 8728    cx.update(|cx| active_call.room_update_completed(cx)).await;
 8729
 8730    let task = cx.update(|cx| {
 8731        if let Some((project, host)) = active_call.most_active_project(cx) {
 8732            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 8733        }
 8734
 8735        // If you are the first to join a channel, see if you should share your project.
 8736        if !active_call.has_remote_participants(cx)
 8737            && !active_call.local_participant_is_guest(cx)
 8738            && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
 8739        {
 8740            let project = workspace.update(cx, |workspace, cx| {
 8741                let project = workspace.project.read(cx);
 8742
 8743                if !active_call.share_on_join(cx) {
 8744                    return None;
 8745                }
 8746
 8747                if (project.is_local() || project.is_via_remote_server())
 8748                    && project.visible_worktrees(cx).any(|tree| {
 8749                        tree.read(cx)
 8750                            .root_entry()
 8751                            .is_some_and(|entry| entry.is_dir())
 8752                    })
 8753                {
 8754                    Some(workspace.project.clone())
 8755                } else {
 8756                    None
 8757                }
 8758            });
 8759            if let Some(project) = project {
 8760                let share_task = active_call.share_project(project, cx);
 8761                return Some(cx.spawn(async move |_cx| -> Result<()> {
 8762                    share_task.await?;
 8763                    Ok(())
 8764                }));
 8765            }
 8766        }
 8767
 8768        None
 8769    });
 8770    if let Some(task) = task {
 8771        task.await?;
 8772        return anyhow::Ok(true);
 8773    }
 8774    anyhow::Ok(false)
 8775}
 8776
 8777pub fn join_channel(
 8778    channel_id: ChannelId,
 8779    app_state: Arc<AppState>,
 8780    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 8781    requesting_workspace: Option<WeakEntity<Workspace>>,
 8782    cx: &mut App,
 8783) -> Task<Result<()>> {
 8784    let active_call = GlobalAnyActiveCall::global(cx).clone();
 8785    cx.spawn(async move |cx| {
 8786        let result = join_channel_internal(
 8787            channel_id,
 8788            &app_state,
 8789            requesting_window,
 8790            requesting_workspace,
 8791            &*active_call.0,
 8792            cx,
 8793        )
 8794        .await;
 8795
 8796        // join channel succeeded, and opened a window
 8797        if matches!(result, Ok(true)) {
 8798            return anyhow::Ok(());
 8799        }
 8800
 8801        // find an existing workspace to focus and show call controls
 8802        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 8803        if active_window.is_none() {
 8804            // no open workspaces, make one to show the error in (blergh)
 8805            let OpenResult {
 8806                window: window_handle,
 8807                ..
 8808            } = cx
 8809                .update(|cx| {
 8810                    Workspace::new_local(
 8811                        vec![],
 8812                        app_state.clone(),
 8813                        requesting_window,
 8814                        None,
 8815                        None,
 8816                        true,
 8817                        cx,
 8818                    )
 8819                })
 8820                .await?;
 8821
 8822            window_handle
 8823                .update(cx, |_, window, _cx| {
 8824                    window.activate_window();
 8825                })
 8826                .ok();
 8827
 8828            if result.is_ok() {
 8829                cx.update(|cx| {
 8830                    cx.dispatch_action(&OpenChannelNotes);
 8831                });
 8832            }
 8833
 8834            active_window = Some(window_handle);
 8835        }
 8836
 8837        if let Err(err) = result {
 8838            log::error!("failed to join channel: {}", err);
 8839            if let Some(active_window) = active_window {
 8840                active_window
 8841                    .update(cx, |_, window, cx| {
 8842                        let detail: SharedString = match err.error_code() {
 8843                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 8844                            ErrorCode::UpgradeRequired => concat!(
 8845                                "Your are running an unsupported version of Zed. ",
 8846                                "Please update to continue."
 8847                            )
 8848                            .into(),
 8849                            ErrorCode::NoSuchChannel => concat!(
 8850                                "No matching channel was found. ",
 8851                                "Please check the link and try again."
 8852                            )
 8853                            .into(),
 8854                            ErrorCode::Forbidden => concat!(
 8855                                "This channel is private, and you do not have access. ",
 8856                                "Please ask someone to add you and try again."
 8857                            )
 8858                            .into(),
 8859                            ErrorCode::Disconnected => {
 8860                                "Please check your internet connection and try again.".into()
 8861                            }
 8862                            _ => format!("{}\n\nPlease try again.", err).into(),
 8863                        };
 8864                        window.prompt(
 8865                            PromptLevel::Critical,
 8866                            "Failed to join channel",
 8867                            Some(&detail),
 8868                            &["Ok"],
 8869                            cx,
 8870                        )
 8871                    })?
 8872                    .await
 8873                    .ok();
 8874            }
 8875        }
 8876
 8877        // return ok, we showed the error to the user.
 8878        anyhow::Ok(())
 8879    })
 8880}
 8881
 8882pub async fn get_any_active_multi_workspace(
 8883    app_state: Arc<AppState>,
 8884    mut cx: AsyncApp,
 8885) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
 8886    // find an existing workspace to focus and show call controls
 8887    let active_window = activate_any_workspace_window(&mut cx);
 8888    if active_window.is_none() {
 8889        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
 8890            .await?;
 8891    }
 8892    activate_any_workspace_window(&mut cx).context("could not open zed")
 8893}
 8894
 8895fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
 8896    cx.update(|cx| {
 8897        if let Some(workspace_window) = cx
 8898            .active_window()
 8899            .and_then(|window| window.downcast::<MultiWorkspace>())
 8900        {
 8901            return Some(workspace_window);
 8902        }
 8903
 8904        for window in cx.windows() {
 8905            if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
 8906                workspace_window
 8907                    .update(cx, |_, window, _| window.activate_window())
 8908                    .ok();
 8909                return Some(workspace_window);
 8910            }
 8911        }
 8912        None
 8913    })
 8914}
 8915
 8916pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
 8917    workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
 8918}
 8919
 8920pub fn workspace_windows_for_location(
 8921    serialized_location: &SerializedWorkspaceLocation,
 8922    cx: &App,
 8923) -> Vec<WindowHandle<MultiWorkspace>> {
 8924    cx.windows()
 8925        .into_iter()
 8926        .filter_map(|window| window.downcast::<MultiWorkspace>())
 8927        .filter(|multi_workspace| {
 8928            let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
 8929                (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
 8930                    (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
 8931                }
 8932                (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
 8933                    // The WSL username is not consistently populated in the workspace location, so ignore it for now.
 8934                    a.distro_name == b.distro_name
 8935                }
 8936                (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
 8937                    a.container_id == b.container_id
 8938                }
 8939                #[cfg(any(test, feature = "test-support"))]
 8940                (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
 8941                    a.id == b.id
 8942                }
 8943                _ => false,
 8944            };
 8945
 8946            multi_workspace.read(cx).is_ok_and(|multi_workspace| {
 8947                multi_workspace.workspaces().iter().any(|workspace| {
 8948                    match workspace.read(cx).workspace_location(cx) {
 8949                        WorkspaceLocation::Location(location, _) => {
 8950                            match (&location, serialized_location) {
 8951                                (
 8952                                    SerializedWorkspaceLocation::Local,
 8953                                    SerializedWorkspaceLocation::Local,
 8954                                ) => true,
 8955                                (
 8956                                    SerializedWorkspaceLocation::Remote(a),
 8957                                    SerializedWorkspaceLocation::Remote(b),
 8958                                ) => same_host(a, b),
 8959                                _ => false,
 8960                            }
 8961                        }
 8962                        _ => false,
 8963                    }
 8964                })
 8965            })
 8966        })
 8967        .collect()
 8968}
 8969
 8970pub async fn find_existing_workspace(
 8971    abs_paths: &[PathBuf],
 8972    open_options: &OpenOptions,
 8973    location: &SerializedWorkspaceLocation,
 8974    cx: &mut AsyncApp,
 8975) -> (
 8976    Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
 8977    OpenVisible,
 8978) {
 8979    let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
 8980    let mut open_visible = OpenVisible::All;
 8981    let mut best_match = None;
 8982
 8983    if open_options.open_new_workspace != Some(true) {
 8984        cx.update(|cx| {
 8985            for window in workspace_windows_for_location(location, cx) {
 8986                if let Ok(multi_workspace) = window.read(cx) {
 8987                    for workspace in multi_workspace.workspaces() {
 8988                        let project = workspace.read(cx).project.read(cx);
 8989                        let m = project.visibility_for_paths(
 8990                            abs_paths,
 8991                            open_options.open_new_workspace == None,
 8992                            cx,
 8993                        );
 8994                        if m > best_match {
 8995                            existing = Some((window, workspace.clone()));
 8996                            best_match = m;
 8997                        } else if best_match.is_none()
 8998                            && open_options.open_new_workspace == Some(false)
 8999                        {
 9000                            existing = Some((window, workspace.clone()))
 9001                        }
 9002                    }
 9003                }
 9004            }
 9005        });
 9006
 9007        let all_paths_are_files = existing
 9008            .as_ref()
 9009            .and_then(|(_, target_workspace)| {
 9010                cx.update(|cx| {
 9011                    let workspace = target_workspace.read(cx);
 9012                    let project = workspace.project.read(cx);
 9013                    let path_style = workspace.path_style(cx);
 9014                    Some(!abs_paths.iter().any(|path| {
 9015                        let path = util::paths::SanitizedPath::new(path);
 9016                        project.worktrees(cx).any(|worktree| {
 9017                            let worktree = worktree.read(cx);
 9018                            let abs_path = worktree.abs_path();
 9019                            path_style
 9020                                .strip_prefix(path.as_ref(), abs_path.as_ref())
 9021                                .and_then(|rel| worktree.entry_for_path(&rel))
 9022                                .is_some_and(|e| e.is_dir())
 9023                        })
 9024                    }))
 9025                })
 9026            })
 9027            .unwrap_or(false);
 9028
 9029        if open_options.open_new_workspace.is_none()
 9030            && existing.is_some()
 9031            && open_options.wait
 9032            && all_paths_are_files
 9033        {
 9034            cx.update(|cx| {
 9035                let windows = workspace_windows_for_location(location, cx);
 9036                let window = cx
 9037                    .active_window()
 9038                    .and_then(|window| window.downcast::<MultiWorkspace>())
 9039                    .filter(|window| windows.contains(window))
 9040                    .or_else(|| windows.into_iter().next());
 9041                if let Some(window) = window {
 9042                    if let Ok(multi_workspace) = window.read(cx) {
 9043                        let active_workspace = multi_workspace.workspace().clone();
 9044                        existing = Some((window, active_workspace));
 9045                        open_visible = OpenVisible::None;
 9046                    }
 9047                }
 9048            });
 9049        }
 9050    }
 9051    (existing, open_visible)
 9052}
 9053
 9054#[derive(Default, Clone)]
 9055pub struct OpenOptions {
 9056    pub visible: Option<OpenVisible>,
 9057    pub focus: Option<bool>,
 9058    pub open_new_workspace: Option<bool>,
 9059    pub wait: bool,
 9060    pub replace_window: Option<WindowHandle<MultiWorkspace>>,
 9061    pub env: Option<HashMap<String, String>>,
 9062}
 9063
 9064/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
 9065/// or [`Workspace::open_workspace_for_paths`].
 9066pub struct OpenResult {
 9067    pub window: WindowHandle<MultiWorkspace>,
 9068    pub workspace: Entity<Workspace>,
 9069    pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 9070}
 9071
 9072/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
 9073pub fn open_workspace_by_id(
 9074    workspace_id: WorkspaceId,
 9075    app_state: Arc<AppState>,
 9076    requesting_window: Option<WindowHandle<MultiWorkspace>>,
 9077    cx: &mut App,
 9078) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
 9079    let project_handle = Project::local(
 9080        app_state.client.clone(),
 9081        app_state.node_runtime.clone(),
 9082        app_state.user_store.clone(),
 9083        app_state.languages.clone(),
 9084        app_state.fs.clone(),
 9085        None,
 9086        project::LocalProjectFlags {
 9087            init_worktree_trust: true,
 9088            ..project::LocalProjectFlags::default()
 9089        },
 9090        cx,
 9091    );
 9092
 9093    let db = WorkspaceDb::global(cx);
 9094    let kvp = db::kvp::KeyValueStore::global(cx);
 9095    cx.spawn(async move |cx| {
 9096        let serialized_workspace = db
 9097            .workspace_for_id(workspace_id)
 9098            .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
 9099
 9100        let centered_layout = serialized_workspace.centered_layout;
 9101
 9102        let (window, workspace) = if let Some(window) = requesting_window {
 9103            let workspace = window.update(cx, |multi_workspace, window, cx| {
 9104                let workspace = cx.new(|cx| {
 9105                    let mut workspace = Workspace::new(
 9106                        Some(workspace_id),
 9107                        project_handle.clone(),
 9108                        app_state.clone(),
 9109                        window,
 9110                        cx,
 9111                    );
 9112                    workspace.centered_layout = centered_layout;
 9113                    workspace
 9114                });
 9115                multi_workspace.add_workspace(workspace.clone(), cx);
 9116                workspace
 9117            })?;
 9118            (window, workspace)
 9119        } else {
 9120            let window_bounds_override = window_bounds_env_override();
 9121
 9122            let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 9123                (Some(WindowBounds::Windowed(bounds)), None)
 9124            } else if let Some(display) = serialized_workspace.display
 9125                && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
 9126            {
 9127                (Some(bounds.0), Some(display))
 9128            } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
 9129                (Some(bounds), Some(display))
 9130            } else {
 9131                (None, None)
 9132            };
 9133
 9134            let options = cx.update(|cx| {
 9135                let mut options = (app_state.build_window_options)(display, cx);
 9136                options.window_bounds = window_bounds;
 9137                options
 9138            });
 9139
 9140            let window = cx.open_window(options, {
 9141                let app_state = app_state.clone();
 9142                let project_handle = project_handle.clone();
 9143                move |window, cx| {
 9144                    let workspace = cx.new(|cx| {
 9145                        let mut workspace = Workspace::new(
 9146                            Some(workspace_id),
 9147                            project_handle,
 9148                            app_state,
 9149                            window,
 9150                            cx,
 9151                        );
 9152                        workspace.centered_layout = centered_layout;
 9153                        workspace
 9154                    });
 9155                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9156                }
 9157            })?;
 9158
 9159            let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
 9160                multi_workspace.workspace().clone()
 9161            })?;
 9162
 9163            (window, workspace)
 9164        };
 9165
 9166        notify_if_database_failed(window, cx);
 9167
 9168        // Restore items from the serialized workspace
 9169        window
 9170            .update(cx, |_, window, cx| {
 9171                workspace.update(cx, |_workspace, cx| {
 9172                    open_items(Some(serialized_workspace), vec![], window, cx)
 9173                })
 9174            })?
 9175            .await?;
 9176
 9177        window.update(cx, |_, window, cx| {
 9178            workspace.update(cx, |workspace, cx| {
 9179                workspace.serialize_workspace(window, cx);
 9180            });
 9181        })?;
 9182
 9183        Ok(window)
 9184    })
 9185}
 9186
 9187#[allow(clippy::type_complexity)]
 9188pub fn open_paths(
 9189    abs_paths: &[PathBuf],
 9190    app_state: Arc<AppState>,
 9191    open_options: OpenOptions,
 9192    cx: &mut App,
 9193) -> Task<anyhow::Result<OpenResult>> {
 9194    let abs_paths = abs_paths.to_vec();
 9195    #[cfg(target_os = "windows")]
 9196    let wsl_path = abs_paths
 9197        .iter()
 9198        .find_map(|p| util::paths::WslPath::from_path(p));
 9199
 9200    cx.spawn(async move |cx| {
 9201        let (mut existing, mut open_visible) = find_existing_workspace(
 9202            &abs_paths,
 9203            &open_options,
 9204            &SerializedWorkspaceLocation::Local,
 9205            cx,
 9206        )
 9207        .await;
 9208
 9209        // Fallback: if no workspace contains the paths and all paths are files,
 9210        // prefer an existing local workspace window (active window first).
 9211        if open_options.open_new_workspace.is_none() && existing.is_none() {
 9212            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 9213            let all_metadatas = futures::future::join_all(all_paths)
 9214                .await
 9215                .into_iter()
 9216                .filter_map(|result| result.ok().flatten())
 9217                .collect::<Vec<_>>();
 9218
 9219            if all_metadatas.iter().all(|file| !file.is_dir) {
 9220                cx.update(|cx| {
 9221                    let windows = workspace_windows_for_location(
 9222                        &SerializedWorkspaceLocation::Local,
 9223                        cx,
 9224                    );
 9225                    let window = cx
 9226                        .active_window()
 9227                        .and_then(|window| window.downcast::<MultiWorkspace>())
 9228                        .filter(|window| windows.contains(window))
 9229                        .or_else(|| windows.into_iter().next());
 9230                    if let Some(window) = window {
 9231                        if let Ok(multi_workspace) = window.read(cx) {
 9232                            let active_workspace = multi_workspace.workspace().clone();
 9233                            existing = Some((window, active_workspace));
 9234                            open_visible = OpenVisible::None;
 9235                        }
 9236                    }
 9237                });
 9238            }
 9239        }
 9240
 9241        let result = if let Some((existing, target_workspace)) = existing {
 9242            let open_task = existing
 9243                .update(cx, |multi_workspace, window, cx| {
 9244                    window.activate_window();
 9245                    multi_workspace.activate(target_workspace.clone(), cx);
 9246                    target_workspace.update(cx, |workspace, cx| {
 9247                        workspace.open_paths(
 9248                            abs_paths,
 9249                            OpenOptions {
 9250                                visible: Some(open_visible),
 9251                                ..Default::default()
 9252                            },
 9253                            None,
 9254                            window,
 9255                            cx,
 9256                        )
 9257                    })
 9258                })?
 9259                .await;
 9260
 9261            _ = existing.update(cx, |multi_workspace, _, cx| {
 9262                let workspace = multi_workspace.workspace().clone();
 9263                workspace.update(cx, |workspace, cx| {
 9264                    for item in open_task.iter().flatten() {
 9265                        if let Err(e) = item {
 9266                            workspace.show_error(&e, cx);
 9267                        }
 9268                    }
 9269                });
 9270            });
 9271
 9272            Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
 9273        } else {
 9274            let result = cx
 9275                .update(move |cx| {
 9276                    Workspace::new_local(
 9277                        abs_paths,
 9278                        app_state.clone(),
 9279                        open_options.replace_window,
 9280                        open_options.env,
 9281                        None,
 9282                        true,
 9283                        cx,
 9284                    )
 9285                })
 9286                .await;
 9287
 9288            if let Ok(ref result) = result {
 9289                result.window
 9290                    .update(cx, |_, window, _cx| {
 9291                        window.activate_window();
 9292                    })
 9293                    .log_err();
 9294            }
 9295
 9296            result
 9297        };
 9298
 9299        #[cfg(target_os = "windows")]
 9300        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 9301            && let Ok(ref result) = result
 9302        {
 9303            result.window
 9304                .update(cx, move |multi_workspace, _window, cx| {
 9305                    struct OpenInWsl;
 9306                    let workspace = multi_workspace.workspace().clone();
 9307                    workspace.update(cx, |workspace, cx| {
 9308                        workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 9309                            let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 9310                            let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 9311                            cx.new(move |cx| {
 9312                                MessageNotification::new(msg, cx)
 9313                                    .primary_message("Open in WSL")
 9314                                    .primary_icon(IconName::FolderOpen)
 9315                                    .primary_on_click(move |window, cx| {
 9316                                        window.dispatch_action(Box::new(remote::OpenWslPath {
 9317                                                distro: remote::WslConnectionOptions {
 9318                                                        distro_name: distro.clone(),
 9319                                                    user: None,
 9320                                                },
 9321                                                paths: vec![path.clone().into()],
 9322                                            }), cx)
 9323                                    })
 9324                            })
 9325                        });
 9326                    });
 9327                })
 9328                .unwrap();
 9329        };
 9330        result
 9331    })
 9332}
 9333
 9334pub fn open_new(
 9335    open_options: OpenOptions,
 9336    app_state: Arc<AppState>,
 9337    cx: &mut App,
 9338    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 9339) -> Task<anyhow::Result<()>> {
 9340    let task = Workspace::new_local(
 9341        Vec::new(),
 9342        app_state,
 9343        open_options.replace_window,
 9344        open_options.env,
 9345        Some(Box::new(init)),
 9346        true,
 9347        cx,
 9348    );
 9349    cx.spawn(async move |cx| {
 9350        let OpenResult { window, .. } = task.await?;
 9351        window
 9352            .update(cx, |_, window, _cx| {
 9353                window.activate_window();
 9354            })
 9355            .ok();
 9356        Ok(())
 9357    })
 9358}
 9359
 9360pub fn create_and_open_local_file(
 9361    path: &'static Path,
 9362    window: &mut Window,
 9363    cx: &mut Context<Workspace>,
 9364    default_content: impl 'static + Send + FnOnce() -> Rope,
 9365) -> Task<Result<Box<dyn ItemHandle>>> {
 9366    cx.spawn_in(window, async move |workspace, cx| {
 9367        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 9368        if !fs.is_file(path).await {
 9369            fs.create_file(path, Default::default()).await?;
 9370            fs.save(path, &default_content(), Default::default())
 9371                .await?;
 9372        }
 9373
 9374        workspace
 9375            .update_in(cx, |workspace, window, cx| {
 9376                workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
 9377                    let path = workspace
 9378                        .project
 9379                        .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
 9380                    cx.spawn_in(window, async move |workspace, cx| {
 9381                        let path = path.await?;
 9382
 9383                        let path = fs.canonicalize(&path).await.unwrap_or(path);
 9384
 9385                        let mut items = workspace
 9386                            .update_in(cx, |workspace, window, cx| {
 9387                                workspace.open_paths(
 9388                                    vec![path.to_path_buf()],
 9389                                    OpenOptions {
 9390                                        visible: Some(OpenVisible::None),
 9391                                        ..Default::default()
 9392                                    },
 9393                                    None,
 9394                                    window,
 9395                                    cx,
 9396                                )
 9397                            })?
 9398                            .await;
 9399                        let item = items.pop().flatten();
 9400                        item.with_context(|| format!("path {path:?} is not a file"))?
 9401                    })
 9402                })
 9403            })?
 9404            .await?
 9405            .await
 9406    })
 9407}
 9408
 9409pub fn open_remote_project_with_new_connection(
 9410    window: WindowHandle<MultiWorkspace>,
 9411    remote_connection: Arc<dyn RemoteConnection>,
 9412    cancel_rx: oneshot::Receiver<()>,
 9413    delegate: Arc<dyn RemoteClientDelegate>,
 9414    app_state: Arc<AppState>,
 9415    paths: Vec<PathBuf>,
 9416    cx: &mut App,
 9417) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9418    cx.spawn(async move |cx| {
 9419        let (workspace_id, serialized_workspace) =
 9420            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 9421                .await?;
 9422
 9423        let session = match cx
 9424            .update(|cx| {
 9425                remote::RemoteClient::new(
 9426                    ConnectionIdentifier::Workspace(workspace_id.0),
 9427                    remote_connection,
 9428                    cancel_rx,
 9429                    delegate,
 9430                    cx,
 9431                )
 9432            })
 9433            .await?
 9434        {
 9435            Some(result) => result,
 9436            None => return Ok(Vec::new()),
 9437        };
 9438
 9439        let project = cx.update(|cx| {
 9440            project::Project::remote(
 9441                session,
 9442                app_state.client.clone(),
 9443                app_state.node_runtime.clone(),
 9444                app_state.user_store.clone(),
 9445                app_state.languages.clone(),
 9446                app_state.fs.clone(),
 9447                true,
 9448                cx,
 9449            )
 9450        });
 9451
 9452        open_remote_project_inner(
 9453            project,
 9454            paths,
 9455            workspace_id,
 9456            serialized_workspace,
 9457            app_state,
 9458            window,
 9459            cx,
 9460        )
 9461        .await
 9462    })
 9463}
 9464
 9465pub fn open_remote_project_with_existing_connection(
 9466    connection_options: RemoteConnectionOptions,
 9467    project: Entity<Project>,
 9468    paths: Vec<PathBuf>,
 9469    app_state: Arc<AppState>,
 9470    window: WindowHandle<MultiWorkspace>,
 9471    cx: &mut AsyncApp,
 9472) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 9473    cx.spawn(async move |cx| {
 9474        let (workspace_id, serialized_workspace) =
 9475            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 9476
 9477        open_remote_project_inner(
 9478            project,
 9479            paths,
 9480            workspace_id,
 9481            serialized_workspace,
 9482            app_state,
 9483            window,
 9484            cx,
 9485        )
 9486        .await
 9487    })
 9488}
 9489
 9490async fn open_remote_project_inner(
 9491    project: Entity<Project>,
 9492    paths: Vec<PathBuf>,
 9493    workspace_id: WorkspaceId,
 9494    serialized_workspace: Option<SerializedWorkspace>,
 9495    app_state: Arc<AppState>,
 9496    window: WindowHandle<MultiWorkspace>,
 9497    cx: &mut AsyncApp,
 9498) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 9499    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9500    let toolchains = db.toolchains(workspace_id).await?;
 9501    for (toolchain, worktree_path, path) in toolchains {
 9502        project
 9503            .update(cx, |this, cx| {
 9504                let Some(worktree_id) =
 9505                    this.find_worktree(&worktree_path, cx)
 9506                        .and_then(|(worktree, rel_path)| {
 9507                            if rel_path.is_empty() {
 9508                                Some(worktree.read(cx).id())
 9509                            } else {
 9510                                None
 9511                            }
 9512                        })
 9513                else {
 9514                    return Task::ready(None);
 9515                };
 9516
 9517                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 9518            })
 9519            .await;
 9520    }
 9521    let mut project_paths_to_open = vec![];
 9522    let mut project_path_errors = vec![];
 9523
 9524    for path in paths {
 9525        let result = cx
 9526            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
 9527            .await;
 9528        match result {
 9529            Ok((_, project_path)) => {
 9530                project_paths_to_open.push((path.clone(), Some(project_path)));
 9531            }
 9532            Err(error) => {
 9533                project_path_errors.push(error);
 9534            }
 9535        };
 9536    }
 9537
 9538    if project_paths_to_open.is_empty() {
 9539        return Err(project_path_errors.pop().context("no paths given")?);
 9540    }
 9541
 9542    let workspace = window.update(cx, |multi_workspace, window, cx| {
 9543        telemetry::event!("SSH Project Opened");
 9544
 9545        let new_workspace = cx.new(|cx| {
 9546            let mut workspace =
 9547                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 9548            workspace.update_history(cx);
 9549
 9550            if let Some(ref serialized) = serialized_workspace {
 9551                workspace.centered_layout = serialized.centered_layout;
 9552            }
 9553
 9554            workspace
 9555        });
 9556
 9557        multi_workspace.activate(new_workspace.clone(), cx);
 9558        new_workspace
 9559    })?;
 9560
 9561    let items = window
 9562        .update(cx, |_, window, cx| {
 9563            window.activate_window();
 9564            workspace.update(cx, |_workspace, cx| {
 9565                open_items(serialized_workspace, project_paths_to_open, window, cx)
 9566            })
 9567        })?
 9568        .await?;
 9569
 9570    workspace.update(cx, |workspace, cx| {
 9571        for error in project_path_errors {
 9572            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 9573                if let Some(path) = error.error_tag("path") {
 9574                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 9575                }
 9576            } else {
 9577                workspace.show_error(&error, cx)
 9578            }
 9579        }
 9580    });
 9581
 9582    Ok(items.into_iter().map(|item| item?.ok()).collect())
 9583}
 9584
 9585fn deserialize_remote_project(
 9586    connection_options: RemoteConnectionOptions,
 9587    paths: Vec<PathBuf>,
 9588    cx: &AsyncApp,
 9589) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 9590    let db = cx.update(|cx| WorkspaceDb::global(cx));
 9591    cx.background_spawn(async move {
 9592        let remote_connection_id = db
 9593            .get_or_create_remote_connection(connection_options)
 9594            .await?;
 9595
 9596        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
 9597
 9598        let workspace_id = if let Some(workspace_id) =
 9599            serialized_workspace.as_ref().map(|workspace| workspace.id)
 9600        {
 9601            workspace_id
 9602        } else {
 9603            db.next_id().await?
 9604        };
 9605
 9606        Ok((workspace_id, serialized_workspace))
 9607    })
 9608}
 9609
 9610pub fn join_in_room_project(
 9611    project_id: u64,
 9612    follow_user_id: u64,
 9613    app_state: Arc<AppState>,
 9614    cx: &mut App,
 9615) -> Task<Result<()>> {
 9616    let windows = cx.windows();
 9617    cx.spawn(async move |cx| {
 9618        let existing_window_and_workspace: Option<(
 9619            WindowHandle<MultiWorkspace>,
 9620            Entity<Workspace>,
 9621        )> = windows.into_iter().find_map(|window_handle| {
 9622            window_handle
 9623                .downcast::<MultiWorkspace>()
 9624                .and_then(|window_handle| {
 9625                    window_handle
 9626                        .update(cx, |multi_workspace, _window, cx| {
 9627                            for workspace in multi_workspace.workspaces() {
 9628                                if workspace.read(cx).project().read(cx).remote_id()
 9629                                    == Some(project_id)
 9630                                {
 9631                                    return Some((window_handle, workspace.clone()));
 9632                                }
 9633                            }
 9634                            None
 9635                        })
 9636                        .unwrap_or(None)
 9637                })
 9638        });
 9639
 9640        let multi_workspace_window = if let Some((existing_window, target_workspace)) =
 9641            existing_window_and_workspace
 9642        {
 9643            existing_window
 9644                .update(cx, |multi_workspace, _, cx| {
 9645                    multi_workspace.activate(target_workspace, cx);
 9646                })
 9647                .ok();
 9648            existing_window
 9649        } else {
 9650            let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
 9651            let project = cx
 9652                .update(|cx| {
 9653                    active_call.0.join_project(
 9654                        project_id,
 9655                        app_state.languages.clone(),
 9656                        app_state.fs.clone(),
 9657                        cx,
 9658                    )
 9659                })
 9660                .await?;
 9661
 9662            let window_bounds_override = window_bounds_env_override();
 9663            cx.update(|cx| {
 9664                let mut options = (app_state.build_window_options)(None, cx);
 9665                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 9666                cx.open_window(options, |window, cx| {
 9667                    let workspace = cx.new(|cx| {
 9668                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 9669                    });
 9670                    cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
 9671                })
 9672            })?
 9673        };
 9674
 9675        multi_workspace_window.update(cx, |multi_workspace, window, cx| {
 9676            cx.activate(true);
 9677            window.activate_window();
 9678
 9679            // We set the active workspace above, so this is the correct workspace.
 9680            let workspace = multi_workspace.workspace().clone();
 9681            workspace.update(cx, |workspace, cx| {
 9682                let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
 9683                    .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
 9684                    .or_else(|| {
 9685                        // If we couldn't follow the given user, follow the host instead.
 9686                        let collaborator = workspace
 9687                            .project()
 9688                            .read(cx)
 9689                            .collaborators()
 9690                            .values()
 9691                            .find(|collaborator| collaborator.is_host)?;
 9692                        Some(collaborator.peer_id)
 9693                    });
 9694
 9695                if let Some(follow_peer_id) = follow_peer_id {
 9696                    workspace.follow(follow_peer_id, window, cx);
 9697                }
 9698            });
 9699        })?;
 9700
 9701        anyhow::Ok(())
 9702    })
 9703}
 9704
 9705pub fn reload(cx: &mut App) {
 9706    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 9707    let mut workspace_windows = cx
 9708        .windows()
 9709        .into_iter()
 9710        .filter_map(|window| window.downcast::<MultiWorkspace>())
 9711        .collect::<Vec<_>>();
 9712
 9713    // If multiple windows have unsaved changes, and need a save prompt,
 9714    // prompt in the active window before switching to a different window.
 9715    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 9716
 9717    let mut prompt = None;
 9718    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 9719        prompt = window
 9720            .update(cx, |_, window, cx| {
 9721                window.prompt(
 9722                    PromptLevel::Info,
 9723                    "Are you sure you want to restart?",
 9724                    None,
 9725                    &["Restart", "Cancel"],
 9726                    cx,
 9727                )
 9728            })
 9729            .ok();
 9730    }
 9731
 9732    cx.spawn(async move |cx| {
 9733        if let Some(prompt) = prompt {
 9734            let answer = prompt.await?;
 9735            if answer != 0 {
 9736                return anyhow::Ok(());
 9737            }
 9738        }
 9739
 9740        // If the user cancels any save prompt, then keep the app open.
 9741        for window in workspace_windows {
 9742            if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
 9743                let workspace = multi_workspace.workspace().clone();
 9744                workspace.update(cx, |workspace, cx| {
 9745                    workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 9746                })
 9747            }) && !should_close.await?
 9748            {
 9749                return anyhow::Ok(());
 9750            }
 9751        }
 9752        cx.update(|cx| cx.restart());
 9753        anyhow::Ok(())
 9754    })
 9755    .detach_and_log_err(cx);
 9756}
 9757
 9758fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 9759    let mut parts = value.split(',');
 9760    let x: usize = parts.next()?.parse().ok()?;
 9761    let y: usize = parts.next()?.parse().ok()?;
 9762    Some(point(px(x as f32), px(y as f32)))
 9763}
 9764
 9765fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 9766    let mut parts = value.split(',');
 9767    let width: usize = parts.next()?.parse().ok()?;
 9768    let height: usize = parts.next()?.parse().ok()?;
 9769    Some(size(px(width as f32), px(height as f32)))
 9770}
 9771
 9772/// Add client-side decorations (rounded corners, shadows, resize handling) when
 9773/// appropriate.
 9774///
 9775/// The `border_radius_tiling` parameter allows overriding which corners get
 9776/// rounded, independently of the actual window tiling state. This is used
 9777/// specifically for the workspace switcher sidebar: when the sidebar is open,
 9778/// we want square corners on the left (so the sidebar appears flush with the
 9779/// window edge) but we still need the shadow padding for proper visual
 9780/// appearance. Unlike actual window tiling, this only affects border radius -
 9781/// not padding or shadows.
 9782pub fn client_side_decorations(
 9783    element: impl IntoElement,
 9784    window: &mut Window,
 9785    cx: &mut App,
 9786    border_radius_tiling: Tiling,
 9787) -> Stateful<Div> {
 9788    const BORDER_SIZE: Pixels = px(1.0);
 9789    let decorations = window.window_decorations();
 9790    let tiling = match decorations {
 9791        Decorations::Server => Tiling::default(),
 9792        Decorations::Client { tiling } => tiling,
 9793    };
 9794
 9795    match decorations {
 9796        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 9797        Decorations::Server => window.set_client_inset(px(0.0)),
 9798    }
 9799
 9800    struct GlobalResizeEdge(ResizeEdge);
 9801    impl Global for GlobalResizeEdge {}
 9802
 9803    div()
 9804        .id("window-backdrop")
 9805        .bg(transparent_black())
 9806        .map(|div| match decorations {
 9807            Decorations::Server => div,
 9808            Decorations::Client { .. } => div
 9809                .when(
 9810                    !(tiling.top
 9811                        || tiling.right
 9812                        || border_radius_tiling.top
 9813                        || border_radius_tiling.right),
 9814                    |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9815                )
 9816                .when(
 9817                    !(tiling.top
 9818                        || tiling.left
 9819                        || border_radius_tiling.top
 9820                        || border_radius_tiling.left),
 9821                    |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9822                )
 9823                .when(
 9824                    !(tiling.bottom
 9825                        || tiling.right
 9826                        || border_radius_tiling.bottom
 9827                        || border_radius_tiling.right),
 9828                    |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9829                )
 9830                .when(
 9831                    !(tiling.bottom
 9832                        || tiling.left
 9833                        || border_radius_tiling.bottom
 9834                        || border_radius_tiling.left),
 9835                    |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9836                )
 9837                .when(!tiling.top, |div| {
 9838                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9839                })
 9840                .when(!tiling.bottom, |div| {
 9841                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9842                })
 9843                .when(!tiling.left, |div| {
 9844                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9845                })
 9846                .when(!tiling.right, |div| {
 9847                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 9848                })
 9849                .on_mouse_move(move |e, window, cx| {
 9850                    let size = window.window_bounds().get_bounds().size;
 9851                    let pos = e.position;
 9852
 9853                    let new_edge =
 9854                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 9855
 9856                    let edge = cx.try_global::<GlobalResizeEdge>();
 9857                    if new_edge != edge.map(|edge| edge.0) {
 9858                        window
 9859                            .window_handle()
 9860                            .update(cx, |workspace, _, cx| {
 9861                                cx.notify(workspace.entity_id());
 9862                            })
 9863                            .ok();
 9864                    }
 9865                })
 9866                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 9867                    let size = window.window_bounds().get_bounds().size;
 9868                    let pos = e.position;
 9869
 9870                    let edge = match resize_edge(
 9871                        pos,
 9872                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 9873                        size,
 9874                        tiling,
 9875                    ) {
 9876                        Some(value) => value,
 9877                        None => return,
 9878                    };
 9879
 9880                    window.start_window_resize(edge);
 9881                }),
 9882        })
 9883        .size_full()
 9884        .child(
 9885            div()
 9886                .cursor(CursorStyle::Arrow)
 9887                .map(|div| match decorations {
 9888                    Decorations::Server => div,
 9889                    Decorations::Client { .. } => div
 9890                        .border_color(cx.theme().colors().border)
 9891                        .when(
 9892                            !(tiling.top
 9893                                || tiling.right
 9894                                || border_radius_tiling.top
 9895                                || border_radius_tiling.right),
 9896                            |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9897                        )
 9898                        .when(
 9899                            !(tiling.top
 9900                                || tiling.left
 9901                                || border_radius_tiling.top
 9902                                || border_radius_tiling.left),
 9903                            |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9904                        )
 9905                        .when(
 9906                            !(tiling.bottom
 9907                                || tiling.right
 9908                                || border_radius_tiling.bottom
 9909                                || border_radius_tiling.right),
 9910                            |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9911                        )
 9912                        .when(
 9913                            !(tiling.bottom
 9914                                || tiling.left
 9915                                || border_radius_tiling.bottom
 9916                                || border_radius_tiling.left),
 9917                            |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
 9918                        )
 9919                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 9920                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 9921                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 9922                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 9923                        .when(!tiling.is_tiled(), |div| {
 9924                            div.shadow(vec![gpui::BoxShadow {
 9925                                color: Hsla {
 9926                                    h: 0.,
 9927                                    s: 0.,
 9928                                    l: 0.,
 9929                                    a: 0.4,
 9930                                },
 9931                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 9932                                spread_radius: px(0.),
 9933                                offset: point(px(0.0), px(0.0)),
 9934                            }])
 9935                        }),
 9936                })
 9937                .on_mouse_move(|_e, _, cx| {
 9938                    cx.stop_propagation();
 9939                })
 9940                .size_full()
 9941                .child(element),
 9942        )
 9943        .map(|div| match decorations {
 9944            Decorations::Server => div,
 9945            Decorations::Client { tiling, .. } => div.child(
 9946                canvas(
 9947                    |_bounds, window, _| {
 9948                        window.insert_hitbox(
 9949                            Bounds::new(
 9950                                point(px(0.0), px(0.0)),
 9951                                window.window_bounds().get_bounds().size,
 9952                            ),
 9953                            HitboxBehavior::Normal,
 9954                        )
 9955                    },
 9956                    move |_bounds, hitbox, window, cx| {
 9957                        let mouse = window.mouse_position();
 9958                        let size = window.window_bounds().get_bounds().size;
 9959                        let Some(edge) =
 9960                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 9961                        else {
 9962                            return;
 9963                        };
 9964                        cx.set_global(GlobalResizeEdge(edge));
 9965                        window.set_cursor_style(
 9966                            match edge {
 9967                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 9968                                ResizeEdge::Left | ResizeEdge::Right => {
 9969                                    CursorStyle::ResizeLeftRight
 9970                                }
 9971                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 9972                                    CursorStyle::ResizeUpLeftDownRight
 9973                                }
 9974                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 9975                                    CursorStyle::ResizeUpRightDownLeft
 9976                                }
 9977                            },
 9978                            &hitbox,
 9979                        );
 9980                    },
 9981                )
 9982                .size_full()
 9983                .absolute(),
 9984            ),
 9985        })
 9986}
 9987
 9988fn resize_edge(
 9989    pos: Point<Pixels>,
 9990    shadow_size: Pixels,
 9991    window_size: Size<Pixels>,
 9992    tiling: Tiling,
 9993) -> Option<ResizeEdge> {
 9994    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 9995    if bounds.contains(&pos) {
 9996        return None;
 9997    }
 9998
 9999    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10000    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10001    if !tiling.top && top_left_bounds.contains(&pos) {
10002        return Some(ResizeEdge::TopLeft);
10003    }
10004
10005    let top_right_bounds = Bounds::new(
10006        Point::new(window_size.width - corner_size.width, px(0.)),
10007        corner_size,
10008    );
10009    if !tiling.top && top_right_bounds.contains(&pos) {
10010        return Some(ResizeEdge::TopRight);
10011    }
10012
10013    let bottom_left_bounds = Bounds::new(
10014        Point::new(px(0.), window_size.height - corner_size.height),
10015        corner_size,
10016    );
10017    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10018        return Some(ResizeEdge::BottomLeft);
10019    }
10020
10021    let bottom_right_bounds = Bounds::new(
10022        Point::new(
10023            window_size.width - corner_size.width,
10024            window_size.height - corner_size.height,
10025        ),
10026        corner_size,
10027    );
10028    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10029        return Some(ResizeEdge::BottomRight);
10030    }
10031
10032    if !tiling.top && pos.y < shadow_size {
10033        Some(ResizeEdge::Top)
10034    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10035        Some(ResizeEdge::Bottom)
10036    } else if !tiling.left && pos.x < shadow_size {
10037        Some(ResizeEdge::Left)
10038    } else if !tiling.right && pos.x > window_size.width - shadow_size {
10039        Some(ResizeEdge::Right)
10040    } else {
10041        None
10042    }
10043}
10044
10045fn join_pane_into_active(
10046    active_pane: &Entity<Pane>,
10047    pane: &Entity<Pane>,
10048    window: &mut Window,
10049    cx: &mut App,
10050) {
10051    if pane == active_pane {
10052    } else if pane.read(cx).items_len() == 0 {
10053        pane.update(cx, |_, cx| {
10054            cx.emit(pane::Event::Remove {
10055                focus_on_pane: None,
10056            });
10057        })
10058    } else {
10059        move_all_items(pane, active_pane, window, cx);
10060    }
10061}
10062
10063fn move_all_items(
10064    from_pane: &Entity<Pane>,
10065    to_pane: &Entity<Pane>,
10066    window: &mut Window,
10067    cx: &mut App,
10068) {
10069    let destination_is_different = from_pane != to_pane;
10070    let mut moved_items = 0;
10071    for (item_ix, item_handle) in from_pane
10072        .read(cx)
10073        .items()
10074        .enumerate()
10075        .map(|(ix, item)| (ix, item.clone()))
10076        .collect::<Vec<_>>()
10077    {
10078        let ix = item_ix - moved_items;
10079        if destination_is_different {
10080            // Close item from previous pane
10081            from_pane.update(cx, |source, cx| {
10082                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10083            });
10084            moved_items += 1;
10085        }
10086
10087        // This automatically removes duplicate items in the pane
10088        to_pane.update(cx, |destination, cx| {
10089            destination.add_item(item_handle, true, true, None, window, cx);
10090            window.focus(&destination.focus_handle(cx), cx)
10091        });
10092    }
10093}
10094
10095pub fn move_item(
10096    source: &Entity<Pane>,
10097    destination: &Entity<Pane>,
10098    item_id_to_move: EntityId,
10099    destination_index: usize,
10100    activate: bool,
10101    window: &mut Window,
10102    cx: &mut App,
10103) {
10104    let Some((item_ix, item_handle)) = source
10105        .read(cx)
10106        .items()
10107        .enumerate()
10108        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10109        .map(|(ix, item)| (ix, item.clone()))
10110    else {
10111        // Tab was closed during drag
10112        return;
10113    };
10114
10115    if source != destination {
10116        // Close item from previous pane
10117        source.update(cx, |source, cx| {
10118            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10119        });
10120    }
10121
10122    // This automatically removes duplicate items in the pane
10123    destination.update(cx, |destination, cx| {
10124        destination.add_item_inner(
10125            item_handle,
10126            activate,
10127            activate,
10128            activate,
10129            Some(destination_index),
10130            window,
10131            cx,
10132        );
10133        if activate {
10134            window.focus(&destination.focus_handle(cx), cx)
10135        }
10136    });
10137}
10138
10139pub fn move_active_item(
10140    source: &Entity<Pane>,
10141    destination: &Entity<Pane>,
10142    focus_destination: bool,
10143    close_if_empty: bool,
10144    window: &mut Window,
10145    cx: &mut App,
10146) {
10147    if source == destination {
10148        return;
10149    }
10150    let Some(active_item) = source.read(cx).active_item() else {
10151        return;
10152    };
10153    source.update(cx, |source_pane, cx| {
10154        let item_id = active_item.item_id();
10155        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10156        destination.update(cx, |target_pane, cx| {
10157            target_pane.add_item(
10158                active_item,
10159                focus_destination,
10160                focus_destination,
10161                Some(target_pane.items_len()),
10162                window,
10163                cx,
10164            );
10165        });
10166    });
10167}
10168
10169pub fn clone_active_item(
10170    workspace_id: Option<WorkspaceId>,
10171    source: &Entity<Pane>,
10172    destination: &Entity<Pane>,
10173    focus_destination: bool,
10174    window: &mut Window,
10175    cx: &mut App,
10176) {
10177    if source == destination {
10178        return;
10179    }
10180    let Some(active_item) = source.read(cx).active_item() else {
10181        return;
10182    };
10183    if !active_item.can_split(cx) {
10184        return;
10185    }
10186    let destination = destination.downgrade();
10187    let task = active_item.clone_on_split(workspace_id, window, cx);
10188    window
10189        .spawn(cx, async move |cx| {
10190            let Some(clone) = task.await else {
10191                return;
10192            };
10193            destination
10194                .update_in(cx, |target_pane, window, cx| {
10195                    target_pane.add_item(
10196                        clone,
10197                        focus_destination,
10198                        focus_destination,
10199                        Some(target_pane.items_len()),
10200                        window,
10201                        cx,
10202                    );
10203                })
10204                .log_err();
10205        })
10206        .detach();
10207}
10208
10209#[derive(Debug)]
10210pub struct WorkspacePosition {
10211    pub window_bounds: Option<WindowBounds>,
10212    pub display: Option<Uuid>,
10213    pub centered_layout: bool,
10214}
10215
10216pub fn remote_workspace_position_from_db(
10217    connection_options: RemoteConnectionOptions,
10218    paths_to_open: &[PathBuf],
10219    cx: &App,
10220) -> Task<Result<WorkspacePosition>> {
10221    let paths = paths_to_open.to_vec();
10222    let db = WorkspaceDb::global(cx);
10223    let kvp = db::kvp::KeyValueStore::global(cx);
10224
10225    cx.background_spawn(async move {
10226        let remote_connection_id = db
10227            .get_or_create_remote_connection(connection_options)
10228            .await
10229            .context("fetching serialized ssh project")?;
10230        let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10231
10232        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10233            (Some(WindowBounds::Windowed(bounds)), None)
10234        } else {
10235            let restorable_bounds = serialized_workspace
10236                .as_ref()
10237                .and_then(|workspace| {
10238                    Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10239                })
10240                .or_else(|| persistence::read_default_window_bounds(&kvp));
10241
10242            if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10243                (Some(serialized_bounds), Some(serialized_display))
10244            } else {
10245                (None, None)
10246            }
10247        };
10248
10249        let centered_layout = serialized_workspace
10250            .as_ref()
10251            .map(|w| w.centered_layout)
10252            .unwrap_or(false);
10253
10254        Ok(WorkspacePosition {
10255            window_bounds,
10256            display,
10257            centered_layout,
10258        })
10259    })
10260}
10261
10262pub fn with_active_or_new_workspace(
10263    cx: &mut App,
10264    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10265) {
10266    match cx
10267        .active_window()
10268        .and_then(|w| w.downcast::<MultiWorkspace>())
10269    {
10270        Some(multi_workspace) => {
10271            cx.defer(move |cx| {
10272                multi_workspace
10273                    .update(cx, |multi_workspace, window, cx| {
10274                        let workspace = multi_workspace.workspace().clone();
10275                        workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10276                    })
10277                    .log_err();
10278            });
10279        }
10280        None => {
10281            let app_state = AppState::global(cx);
10282            if let Some(app_state) = app_state.upgrade() {
10283                open_new(
10284                    OpenOptions::default(),
10285                    app_state,
10286                    cx,
10287                    move |workspace, window, cx| f(workspace, window, cx),
10288                )
10289                .detach_and_log_err(cx);
10290            }
10291        }
10292    }
10293}
10294
10295/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10296/// key. This migration path only runs once per panel per workspace.
10297fn load_legacy_panel_size(
10298    panel_key: &str,
10299    dock_position: DockPosition,
10300    workspace: &Workspace,
10301    cx: &mut App,
10302) -> Option<Pixels> {
10303    #[derive(Deserialize)]
10304    struct LegacyPanelState {
10305        #[serde(default)]
10306        width: Option<Pixels>,
10307        #[serde(default)]
10308        height: Option<Pixels>,
10309    }
10310
10311    let workspace_id = workspace
10312        .database_id()
10313        .map(|id| i64::from(id).to_string())
10314        .or_else(|| workspace.session_id())?;
10315
10316    let legacy_key = match panel_key {
10317        "ProjectPanel" => {
10318            format!("{}-{:?}", "ProjectPanel", workspace_id)
10319        }
10320        "OutlinePanel" => {
10321            format!("{}-{:?}", "OutlinePanel", workspace_id)
10322        }
10323        "GitPanel" => {
10324            format!("{}-{:?}", "GitPanel", workspace_id)
10325        }
10326        "TerminalPanel" => {
10327            format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10328        }
10329        _ => return None,
10330    };
10331
10332    let kvp = db::kvp::KeyValueStore::global(cx);
10333    let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10334    let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10335    let size = match dock_position {
10336        DockPosition::Bottom => state.height,
10337        DockPosition::Left | DockPosition::Right => state.width,
10338    }?;
10339
10340    cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10341        .detach_and_log_err(cx);
10342
10343    Some(size)
10344}
10345
10346#[cfg(test)]
10347mod tests {
10348    use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10349
10350    use super::*;
10351    use crate::{
10352        dock::{PanelEvent, test::TestPanel},
10353        item::{
10354            ItemBufferKind, ItemEvent,
10355            test::{TestItem, TestProjectItem},
10356        },
10357    };
10358    use fs::FakeFs;
10359    use gpui::{
10360        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10361        UpdateGlobal, VisualTestContext, px,
10362    };
10363    use project::{Project, ProjectEntryId};
10364    use serde_json::json;
10365    use settings::SettingsStore;
10366    use util::path;
10367    use util::rel_path::rel_path;
10368
10369    #[gpui::test]
10370    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10371        init_test(cx);
10372
10373        let fs = FakeFs::new(cx.executor());
10374        let project = Project::test(fs, [], cx).await;
10375        let (workspace, cx) =
10376            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10377
10378        // Adding an item with no ambiguity renders the tab without detail.
10379        let item1 = cx.new(|cx| {
10380            let mut item = TestItem::new(cx);
10381            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10382            item
10383        });
10384        workspace.update_in(cx, |workspace, window, cx| {
10385            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10386        });
10387        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10388
10389        // Adding an item that creates ambiguity increases the level of detail on
10390        // both tabs.
10391        let item2 = cx.new_window_entity(|_window, cx| {
10392            let mut item = TestItem::new(cx);
10393            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10394            item
10395        });
10396        workspace.update_in(cx, |workspace, window, cx| {
10397            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10398        });
10399        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10400        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10401
10402        // Adding an item that creates ambiguity increases the level of detail only
10403        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10404        // we stop at the highest detail available.
10405        let item3 = cx.new(|cx| {
10406            let mut item = TestItem::new(cx);
10407            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10408            item
10409        });
10410        workspace.update_in(cx, |workspace, window, cx| {
10411            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10412        });
10413        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10414        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10415        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10416    }
10417
10418    #[gpui::test]
10419    async fn test_tracking_active_path(cx: &mut TestAppContext) {
10420        init_test(cx);
10421
10422        let fs = FakeFs::new(cx.executor());
10423        fs.insert_tree(
10424            "/root1",
10425            json!({
10426                "one.txt": "",
10427                "two.txt": "",
10428            }),
10429        )
10430        .await;
10431        fs.insert_tree(
10432            "/root2",
10433            json!({
10434                "three.txt": "",
10435            }),
10436        )
10437        .await;
10438
10439        let project = Project::test(fs, ["root1".as_ref()], cx).await;
10440        let (workspace, cx) =
10441            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10442        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10443        let worktree_id = project.update(cx, |project, cx| {
10444            project.worktrees(cx).next().unwrap().read(cx).id()
10445        });
10446
10447        let item1 = cx.new(|cx| {
10448            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10449        });
10450        let item2 = cx.new(|cx| {
10451            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10452        });
10453
10454        // Add an item to an empty pane
10455        workspace.update_in(cx, |workspace, window, cx| {
10456            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10457        });
10458        project.update(cx, |project, cx| {
10459            assert_eq!(
10460                project.active_entry(),
10461                project
10462                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10463                    .map(|e| e.id)
10464            );
10465        });
10466        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10467
10468        // Add a second item to a non-empty pane
10469        workspace.update_in(cx, |workspace, window, cx| {
10470            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10471        });
10472        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10473        project.update(cx, |project, cx| {
10474            assert_eq!(
10475                project.active_entry(),
10476                project
10477                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10478                    .map(|e| e.id)
10479            );
10480        });
10481
10482        // Close the active item
10483        pane.update_in(cx, |pane, window, cx| {
10484            pane.close_active_item(&Default::default(), window, cx)
10485        })
10486        .await
10487        .unwrap();
10488        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10489        project.update(cx, |project, cx| {
10490            assert_eq!(
10491                project.active_entry(),
10492                project
10493                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10494                    .map(|e| e.id)
10495            );
10496        });
10497
10498        // Add a project folder
10499        project
10500            .update(cx, |project, cx| {
10501                project.find_or_create_worktree("root2", true, cx)
10502            })
10503            .await
10504            .unwrap();
10505        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10506
10507        // Remove a project folder
10508        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10509        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10510    }
10511
10512    #[gpui::test]
10513    async fn test_close_window(cx: &mut TestAppContext) {
10514        init_test(cx);
10515
10516        let fs = FakeFs::new(cx.executor());
10517        fs.insert_tree("/root", json!({ "one": "" })).await;
10518
10519        let project = Project::test(fs, ["root".as_ref()], cx).await;
10520        let (workspace, cx) =
10521            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10522
10523        // When there are no dirty items, there's nothing to do.
10524        let item1 = cx.new(TestItem::new);
10525        workspace.update_in(cx, |w, window, cx| {
10526            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10527        });
10528        let task = workspace.update_in(cx, |w, window, cx| {
10529            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10530        });
10531        assert!(task.await.unwrap());
10532
10533        // When there are dirty untitled items, prompt to save each one. If the user
10534        // cancels any prompt, then abort.
10535        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10536        let item3 = cx.new(|cx| {
10537            TestItem::new(cx)
10538                .with_dirty(true)
10539                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10540        });
10541        workspace.update_in(cx, |w, window, cx| {
10542            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10543            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10544        });
10545        let task = workspace.update_in(cx, |w, window, cx| {
10546            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10547        });
10548        cx.executor().run_until_parked();
10549        cx.simulate_prompt_answer("Cancel"); // cancel save all
10550        cx.executor().run_until_parked();
10551        assert!(!cx.has_pending_prompt());
10552        assert!(!task.await.unwrap());
10553    }
10554
10555    #[gpui::test]
10556    async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10557        init_test(cx);
10558
10559        let fs = FakeFs::new(cx.executor());
10560        fs.insert_tree("/root", json!({ "one": "" })).await;
10561
10562        let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10563        let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10564        let multi_workspace_handle =
10565            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10566        cx.run_until_parked();
10567
10568        let workspace_a = multi_workspace_handle
10569            .read_with(cx, |mw, _| mw.workspace().clone())
10570            .unwrap();
10571
10572        let workspace_b = multi_workspace_handle
10573            .update(cx, |mw, window, cx| {
10574                mw.test_add_workspace(project_b, window, cx)
10575            })
10576            .unwrap();
10577
10578        // Activate workspace A
10579        multi_workspace_handle
10580            .update(cx, |mw, window, cx| {
10581                mw.activate_index(0, window, cx);
10582            })
10583            .unwrap();
10584
10585        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10586
10587        // Workspace A has a clean item
10588        let item_a = cx.new(TestItem::new);
10589        workspace_a.update_in(cx, |w, window, cx| {
10590            w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10591        });
10592
10593        // Workspace B has a dirty item
10594        let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10595        workspace_b.update_in(cx, |w, window, cx| {
10596            w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10597        });
10598
10599        // Verify workspace A is active
10600        multi_workspace_handle
10601            .read_with(cx, |mw, _| {
10602                assert_eq!(mw.active_workspace_index(), 0);
10603            })
10604            .unwrap();
10605
10606        // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10607        multi_workspace_handle
10608            .update(cx, |mw, window, cx| {
10609                mw.close_window(&CloseWindow, window, cx);
10610            })
10611            .unwrap();
10612        cx.run_until_parked();
10613
10614        // Workspace B should now be active since it has dirty items that need attention
10615        multi_workspace_handle
10616            .read_with(cx, |mw, _| {
10617                assert_eq!(
10618                    mw.active_workspace_index(),
10619                    1,
10620                    "workspace B should be activated when it prompts"
10621                );
10622            })
10623            .unwrap();
10624
10625        // User cancels the save prompt from workspace B
10626        cx.simulate_prompt_answer("Cancel");
10627        cx.run_until_parked();
10628
10629        // Window should still exist because workspace B's close was cancelled
10630        assert!(
10631            multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10632            "window should still exist after cancelling one workspace's close"
10633        );
10634    }
10635
10636    #[gpui::test]
10637    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10638        init_test(cx);
10639
10640        // Register TestItem as a serializable item
10641        cx.update(|cx| {
10642            register_serializable_item::<TestItem>(cx);
10643        });
10644
10645        let fs = FakeFs::new(cx.executor());
10646        fs.insert_tree("/root", json!({ "one": "" })).await;
10647
10648        let project = Project::test(fs, ["root".as_ref()], cx).await;
10649        let (workspace, cx) =
10650            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10651
10652        // When there are dirty untitled items, but they can serialize, then there is no prompt.
10653        let item1 = cx.new(|cx| {
10654            TestItem::new(cx)
10655                .with_dirty(true)
10656                .with_serialize(|| Some(Task::ready(Ok(()))))
10657        });
10658        let item2 = cx.new(|cx| {
10659            TestItem::new(cx)
10660                .with_dirty(true)
10661                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10662                .with_serialize(|| Some(Task::ready(Ok(()))))
10663        });
10664        workspace.update_in(cx, |w, window, cx| {
10665            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10666            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10667        });
10668        let task = workspace.update_in(cx, |w, window, cx| {
10669            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10670        });
10671        assert!(task.await.unwrap());
10672    }
10673
10674    #[gpui::test]
10675    async fn test_close_pane_items(cx: &mut TestAppContext) {
10676        init_test(cx);
10677
10678        let fs = FakeFs::new(cx.executor());
10679
10680        let project = Project::test(fs, None, cx).await;
10681        let (workspace, cx) =
10682            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10683
10684        let item1 = cx.new(|cx| {
10685            TestItem::new(cx)
10686                .with_dirty(true)
10687                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10688        });
10689        let item2 = cx.new(|cx| {
10690            TestItem::new(cx)
10691                .with_dirty(true)
10692                .with_conflict(true)
10693                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10694        });
10695        let item3 = cx.new(|cx| {
10696            TestItem::new(cx)
10697                .with_dirty(true)
10698                .with_conflict(true)
10699                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10700        });
10701        let item4 = cx.new(|cx| {
10702            TestItem::new(cx).with_dirty(true).with_project_items(&[{
10703                let project_item = TestProjectItem::new_untitled(cx);
10704                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10705                project_item
10706            }])
10707        });
10708        let pane = workspace.update_in(cx, |workspace, window, cx| {
10709            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10710            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10711            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10712            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10713            workspace.active_pane().clone()
10714        });
10715
10716        let close_items = pane.update_in(cx, |pane, window, cx| {
10717            pane.activate_item(1, true, true, window, cx);
10718            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10719            let item1_id = item1.item_id();
10720            let item3_id = item3.item_id();
10721            let item4_id = item4.item_id();
10722            pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10723                [item1_id, item3_id, item4_id].contains(&id)
10724            })
10725        });
10726        cx.executor().run_until_parked();
10727
10728        assert!(cx.has_pending_prompt());
10729        cx.simulate_prompt_answer("Save all");
10730
10731        cx.executor().run_until_parked();
10732
10733        // Item 1 is saved. There's a prompt to save item 3.
10734        pane.update(cx, |pane, cx| {
10735            assert_eq!(item1.read(cx).save_count, 1);
10736            assert_eq!(item1.read(cx).save_as_count, 0);
10737            assert_eq!(item1.read(cx).reload_count, 0);
10738            assert_eq!(pane.items_len(), 3);
10739            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10740        });
10741        assert!(cx.has_pending_prompt());
10742
10743        // Cancel saving item 3.
10744        cx.simulate_prompt_answer("Discard");
10745        cx.executor().run_until_parked();
10746
10747        // Item 3 is reloaded. There's a prompt to save item 4.
10748        pane.update(cx, |pane, cx| {
10749            assert_eq!(item3.read(cx).save_count, 0);
10750            assert_eq!(item3.read(cx).save_as_count, 0);
10751            assert_eq!(item3.read(cx).reload_count, 1);
10752            assert_eq!(pane.items_len(), 2);
10753            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10754        });
10755
10756        // There's a prompt for a path for item 4.
10757        cx.simulate_new_path_selection(|_| Some(Default::default()));
10758        close_items.await.unwrap();
10759
10760        // The requested items are closed.
10761        pane.update(cx, |pane, cx| {
10762            assert_eq!(item4.read(cx).save_count, 0);
10763            assert_eq!(item4.read(cx).save_as_count, 1);
10764            assert_eq!(item4.read(cx).reload_count, 0);
10765            assert_eq!(pane.items_len(), 1);
10766            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10767        });
10768    }
10769
10770    #[gpui::test]
10771    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10772        init_test(cx);
10773
10774        let fs = FakeFs::new(cx.executor());
10775        let project = Project::test(fs, [], cx).await;
10776        let (workspace, cx) =
10777            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10778
10779        // Create several workspace items with single project entries, and two
10780        // workspace items with multiple project entries.
10781        let single_entry_items = (0..=4)
10782            .map(|project_entry_id| {
10783                cx.new(|cx| {
10784                    TestItem::new(cx)
10785                        .with_dirty(true)
10786                        .with_project_items(&[dirty_project_item(
10787                            project_entry_id,
10788                            &format!("{project_entry_id}.txt"),
10789                            cx,
10790                        )])
10791                })
10792            })
10793            .collect::<Vec<_>>();
10794        let item_2_3 = cx.new(|cx| {
10795            TestItem::new(cx)
10796                .with_dirty(true)
10797                .with_buffer_kind(ItemBufferKind::Multibuffer)
10798                .with_project_items(&[
10799                    single_entry_items[2].read(cx).project_items[0].clone(),
10800                    single_entry_items[3].read(cx).project_items[0].clone(),
10801                ])
10802        });
10803        let item_3_4 = cx.new(|cx| {
10804            TestItem::new(cx)
10805                .with_dirty(true)
10806                .with_buffer_kind(ItemBufferKind::Multibuffer)
10807                .with_project_items(&[
10808                    single_entry_items[3].read(cx).project_items[0].clone(),
10809                    single_entry_items[4].read(cx).project_items[0].clone(),
10810                ])
10811        });
10812
10813        // Create two panes that contain the following project entries:
10814        //   left pane:
10815        //     multi-entry items:   (2, 3)
10816        //     single-entry items:  0, 2, 3, 4
10817        //   right pane:
10818        //     single-entry items:  4, 1
10819        //     multi-entry items:   (3, 4)
10820        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10821            let left_pane = workspace.active_pane().clone();
10822            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10823            workspace.add_item_to_active_pane(
10824                single_entry_items[0].boxed_clone(),
10825                None,
10826                true,
10827                window,
10828                cx,
10829            );
10830            workspace.add_item_to_active_pane(
10831                single_entry_items[2].boxed_clone(),
10832                None,
10833                true,
10834                window,
10835                cx,
10836            );
10837            workspace.add_item_to_active_pane(
10838                single_entry_items[3].boxed_clone(),
10839                None,
10840                true,
10841                window,
10842                cx,
10843            );
10844            workspace.add_item_to_active_pane(
10845                single_entry_items[4].boxed_clone(),
10846                None,
10847                true,
10848                window,
10849                cx,
10850            );
10851
10852            let right_pane =
10853                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10854
10855            let boxed_clone = single_entry_items[1].boxed_clone();
10856            let right_pane = window.spawn(cx, async move |cx| {
10857                right_pane.await.inspect(|right_pane| {
10858                    right_pane
10859                        .update_in(cx, |pane, window, cx| {
10860                            pane.add_item(boxed_clone, true, true, None, window, cx);
10861                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10862                        })
10863                        .unwrap();
10864                })
10865            });
10866
10867            (left_pane, right_pane)
10868        });
10869        let right_pane = right_pane.await.unwrap();
10870        cx.focus(&right_pane);
10871
10872        let close = right_pane.update_in(cx, |pane, window, cx| {
10873            pane.close_all_items(&CloseAllItems::default(), window, cx)
10874                .unwrap()
10875        });
10876        cx.executor().run_until_parked();
10877
10878        let msg = cx.pending_prompt().unwrap().0;
10879        assert!(msg.contains("1.txt"));
10880        assert!(!msg.contains("2.txt"));
10881        assert!(!msg.contains("3.txt"));
10882        assert!(!msg.contains("4.txt"));
10883
10884        // With best-effort close, cancelling item 1 keeps it open but items 4
10885        // and (3,4) still close since their entries exist in left pane.
10886        cx.simulate_prompt_answer("Cancel");
10887        close.await;
10888
10889        right_pane.read_with(cx, |pane, _| {
10890            assert_eq!(pane.items_len(), 1);
10891        });
10892
10893        // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10894        left_pane
10895            .update_in(cx, |left_pane, window, cx| {
10896                left_pane.close_item_by_id(
10897                    single_entry_items[3].entity_id(),
10898                    SaveIntent::Skip,
10899                    window,
10900                    cx,
10901                )
10902            })
10903            .await
10904            .unwrap();
10905
10906        let close = left_pane.update_in(cx, |pane, window, cx| {
10907            pane.close_all_items(&CloseAllItems::default(), window, cx)
10908                .unwrap()
10909        });
10910        cx.executor().run_until_parked();
10911
10912        let details = cx.pending_prompt().unwrap().1;
10913        assert!(details.contains("0.txt"));
10914        assert!(details.contains("3.txt"));
10915        assert!(details.contains("4.txt"));
10916        // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10917        // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10918        // assert!(!details.contains("2.txt"));
10919
10920        cx.simulate_prompt_answer("Save all");
10921        cx.executor().run_until_parked();
10922        close.await;
10923
10924        left_pane.read_with(cx, |pane, _| {
10925            assert_eq!(pane.items_len(), 0);
10926        });
10927    }
10928
10929    #[gpui::test]
10930    async fn test_autosave(cx: &mut gpui::TestAppContext) {
10931        init_test(cx);
10932
10933        let fs = FakeFs::new(cx.executor());
10934        let project = Project::test(fs, [], cx).await;
10935        let (workspace, cx) =
10936            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10937        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10938
10939        let item = cx.new(|cx| {
10940            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10941        });
10942        let item_id = item.entity_id();
10943        workspace.update_in(cx, |workspace, window, cx| {
10944            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10945        });
10946
10947        // Autosave on window change.
10948        item.update(cx, |item, cx| {
10949            SettingsStore::update_global(cx, |settings, cx| {
10950                settings.update_user_settings(cx, |settings| {
10951                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10952                })
10953            });
10954            item.is_dirty = true;
10955        });
10956
10957        // Deactivating the window saves the file.
10958        cx.deactivate_window();
10959        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10960
10961        // Re-activating the window doesn't save the file.
10962        cx.update(|window, _| window.activate_window());
10963        cx.executor().run_until_parked();
10964        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10965
10966        // Autosave on focus change.
10967        item.update_in(cx, |item, window, cx| {
10968            cx.focus_self(window);
10969            SettingsStore::update_global(cx, |settings, cx| {
10970                settings.update_user_settings(cx, |settings| {
10971                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10972                })
10973            });
10974            item.is_dirty = true;
10975        });
10976        // Blurring the item saves the file.
10977        item.update_in(cx, |_, window, _| window.blur());
10978        cx.executor().run_until_parked();
10979        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10980
10981        // Deactivating the window still saves the file.
10982        item.update_in(cx, |item, window, cx| {
10983            cx.focus_self(window);
10984            item.is_dirty = true;
10985        });
10986        cx.deactivate_window();
10987        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10988
10989        // Autosave after delay.
10990        item.update(cx, |item, cx| {
10991            SettingsStore::update_global(cx, |settings, cx| {
10992                settings.update_user_settings(cx, |settings| {
10993                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10994                        milliseconds: 500.into(),
10995                    });
10996                })
10997            });
10998            item.is_dirty = true;
10999            cx.emit(ItemEvent::Edit);
11000        });
11001
11002        // Delay hasn't fully expired, so the file is still dirty and unsaved.
11003        cx.executor().advance_clock(Duration::from_millis(250));
11004        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11005
11006        // After delay expires, the file is saved.
11007        cx.executor().advance_clock(Duration::from_millis(250));
11008        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11009
11010        // Autosave after delay, should save earlier than delay if tab is closed
11011        item.update(cx, |item, cx| {
11012            item.is_dirty = true;
11013            cx.emit(ItemEvent::Edit);
11014        });
11015        cx.executor().advance_clock(Duration::from_millis(250));
11016        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11017
11018        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11019        pane.update_in(cx, |pane, window, cx| {
11020            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11021        })
11022        .await
11023        .unwrap();
11024        assert!(!cx.has_pending_prompt());
11025        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11026
11027        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11028        workspace.update_in(cx, |workspace, window, cx| {
11029            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11030        });
11031        item.update_in(cx, |item, _window, cx| {
11032            item.is_dirty = true;
11033            for project_item in &mut item.project_items {
11034                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11035            }
11036        });
11037        cx.run_until_parked();
11038        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11039
11040        // Autosave on focus change, ensuring closing the tab counts as such.
11041        item.update(cx, |item, cx| {
11042            SettingsStore::update_global(cx, |settings, cx| {
11043                settings.update_user_settings(cx, |settings| {
11044                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11045                })
11046            });
11047            item.is_dirty = true;
11048            for project_item in &mut item.project_items {
11049                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11050            }
11051        });
11052
11053        pane.update_in(cx, |pane, window, cx| {
11054            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11055        })
11056        .await
11057        .unwrap();
11058        assert!(!cx.has_pending_prompt());
11059        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11060
11061        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11062        workspace.update_in(cx, |workspace, window, cx| {
11063            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11064        });
11065        item.update_in(cx, |item, window, cx| {
11066            item.project_items[0].update(cx, |item, _| {
11067                item.entry_id = None;
11068            });
11069            item.is_dirty = true;
11070            window.blur();
11071        });
11072        cx.run_until_parked();
11073        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11074
11075        // Ensure autosave is prevented for deleted files also when closing the buffer.
11076        let _close_items = pane.update_in(cx, |pane, window, cx| {
11077            pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11078        });
11079        cx.run_until_parked();
11080        assert!(cx.has_pending_prompt());
11081        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11082    }
11083
11084    #[gpui::test]
11085    async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11086        init_test(cx);
11087
11088        let fs = FakeFs::new(cx.executor());
11089        let project = Project::test(fs, [], cx).await;
11090        let (workspace, cx) =
11091            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11092
11093        // Create a multibuffer-like item with two child focus handles,
11094        // simulating individual buffer editors within a multibuffer.
11095        let item = cx.new(|cx| {
11096            TestItem::new(cx)
11097                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11098                .with_child_focus_handles(2, cx)
11099        });
11100        workspace.update_in(cx, |workspace, window, cx| {
11101            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11102        });
11103
11104        // Set autosave to OnFocusChange and focus the first child handle,
11105        // simulating the user's cursor being inside one of the multibuffer's excerpts.
11106        item.update_in(cx, |item, window, cx| {
11107            SettingsStore::update_global(cx, |settings, cx| {
11108                settings.update_user_settings(cx, |settings| {
11109                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11110                })
11111            });
11112            item.is_dirty = true;
11113            window.focus(&item.child_focus_handles[0], cx);
11114        });
11115        cx.executor().run_until_parked();
11116        item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11117
11118        // Moving focus from one child to another within the same item should
11119        // NOT trigger autosave — focus is still within the item's focus hierarchy.
11120        item.update_in(cx, |item, window, cx| {
11121            window.focus(&item.child_focus_handles[1], cx);
11122        });
11123        cx.executor().run_until_parked();
11124        item.read_with(cx, |item, _| {
11125            assert_eq!(
11126                item.save_count, 0,
11127                "Switching focus between children within the same item should not autosave"
11128            );
11129        });
11130
11131        // Blurring the item saves the file. This is the core regression scenario:
11132        // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11133        // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11134        // the leaf is always a child focus handle, so `on_blur` never detected
11135        // focus leaving the item.
11136        item.update_in(cx, |_, window, _| window.blur());
11137        cx.executor().run_until_parked();
11138        item.read_with(cx, |item, _| {
11139            assert_eq!(
11140                item.save_count, 1,
11141                "Blurring should trigger autosave when focus was on a child of the item"
11142            );
11143        });
11144
11145        // Deactivating the window should also trigger autosave when a child of
11146        // the multibuffer item currently owns focus.
11147        item.update_in(cx, |item, window, cx| {
11148            item.is_dirty = true;
11149            window.focus(&item.child_focus_handles[0], cx);
11150        });
11151        cx.executor().run_until_parked();
11152        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11153
11154        cx.deactivate_window();
11155        item.read_with(cx, |item, _| {
11156            assert_eq!(
11157                item.save_count, 2,
11158                "Deactivating window should trigger autosave when focus was on a child"
11159            );
11160        });
11161    }
11162
11163    #[gpui::test]
11164    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11165        init_test(cx);
11166
11167        let fs = FakeFs::new(cx.executor());
11168
11169        let project = Project::test(fs, [], cx).await;
11170        let (workspace, cx) =
11171            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11172
11173        let item = cx.new(|cx| {
11174            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11175        });
11176        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11177        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11178        let toolbar_notify_count = Rc::new(RefCell::new(0));
11179
11180        workspace.update_in(cx, |workspace, window, cx| {
11181            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11182            let toolbar_notification_count = toolbar_notify_count.clone();
11183            cx.observe_in(&toolbar, window, move |_, _, _, _| {
11184                *toolbar_notification_count.borrow_mut() += 1
11185            })
11186            .detach();
11187        });
11188
11189        pane.read_with(cx, |pane, _| {
11190            assert!(!pane.can_navigate_backward());
11191            assert!(!pane.can_navigate_forward());
11192        });
11193
11194        item.update_in(cx, |item, _, cx| {
11195            item.set_state("one".to_string(), cx);
11196        });
11197
11198        // Toolbar must be notified to re-render the navigation buttons
11199        assert_eq!(*toolbar_notify_count.borrow(), 1);
11200
11201        pane.read_with(cx, |pane, _| {
11202            assert!(pane.can_navigate_backward());
11203            assert!(!pane.can_navigate_forward());
11204        });
11205
11206        workspace
11207            .update_in(cx, |workspace, window, cx| {
11208                workspace.go_back(pane.downgrade(), window, cx)
11209            })
11210            .await
11211            .unwrap();
11212
11213        assert_eq!(*toolbar_notify_count.borrow(), 2);
11214        pane.read_with(cx, |pane, _| {
11215            assert!(!pane.can_navigate_backward());
11216            assert!(pane.can_navigate_forward());
11217        });
11218    }
11219
11220    /// Tests that the navigation history deduplicates entries for the same item.
11221    ///
11222    /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11223    /// the navigation history deduplicates by keeping only the most recent visit to each item,
11224    /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11225    /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11226    /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11227    ///
11228    /// This behavior prevents the navigation history from growing unnecessarily large and provides
11229    /// a better user experience by eliminating redundant navigation steps when jumping between files.
11230    #[gpui::test]
11231    async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11232        init_test(cx);
11233
11234        let fs = FakeFs::new(cx.executor());
11235        let project = Project::test(fs, [], cx).await;
11236        let (workspace, cx) =
11237            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11238
11239        let item_a = cx.new(|cx| {
11240            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11241        });
11242        let item_b = cx.new(|cx| {
11243            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11244        });
11245        let item_c = cx.new(|cx| {
11246            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11247        });
11248
11249        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11250
11251        workspace.update_in(cx, |workspace, window, cx| {
11252            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11253            workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11254            workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11255        });
11256
11257        workspace.update_in(cx, |workspace, window, cx| {
11258            workspace.activate_item(&item_a, false, false, window, cx);
11259        });
11260        cx.run_until_parked();
11261
11262        workspace.update_in(cx, |workspace, window, cx| {
11263            workspace.activate_item(&item_b, false, false, window, cx);
11264        });
11265        cx.run_until_parked();
11266
11267        workspace.update_in(cx, |workspace, window, cx| {
11268            workspace.activate_item(&item_a, false, false, window, cx);
11269        });
11270        cx.run_until_parked();
11271
11272        workspace.update_in(cx, |workspace, window, cx| {
11273            workspace.activate_item(&item_b, false, false, window, cx);
11274        });
11275        cx.run_until_parked();
11276
11277        workspace.update_in(cx, |workspace, window, cx| {
11278            workspace.activate_item(&item_a, false, false, window, cx);
11279        });
11280        cx.run_until_parked();
11281
11282        workspace.update_in(cx, |workspace, window, cx| {
11283            workspace.activate_item(&item_b, false, false, window, cx);
11284        });
11285        cx.run_until_parked();
11286
11287        workspace.update_in(cx, |workspace, window, cx| {
11288            workspace.activate_item(&item_c, false, false, window, cx);
11289        });
11290        cx.run_until_parked();
11291
11292        let backward_count = pane.read_with(cx, |pane, cx| {
11293            let mut count = 0;
11294            pane.nav_history().for_each_entry(cx, &mut |_, _| {
11295                count += 1;
11296            });
11297            count
11298        });
11299        assert!(
11300            backward_count <= 4,
11301            "Should have at most 4 entries, got {}",
11302            backward_count
11303        );
11304
11305        workspace
11306            .update_in(cx, |workspace, window, cx| {
11307                workspace.go_back(pane.downgrade(), window, cx)
11308            })
11309            .await
11310            .unwrap();
11311
11312        let active_item = workspace.read_with(cx, |workspace, cx| {
11313            workspace.active_item(cx).unwrap().item_id()
11314        });
11315        assert_eq!(
11316            active_item,
11317            item_b.entity_id(),
11318            "After first go_back, should be at item B"
11319        );
11320
11321        workspace
11322            .update_in(cx, |workspace, window, cx| {
11323                workspace.go_back(pane.downgrade(), window, cx)
11324            })
11325            .await
11326            .unwrap();
11327
11328        let active_item = workspace.read_with(cx, |workspace, cx| {
11329            workspace.active_item(cx).unwrap().item_id()
11330        });
11331        assert_eq!(
11332            active_item,
11333            item_a.entity_id(),
11334            "After second go_back, should be at item A"
11335        );
11336
11337        pane.read_with(cx, |pane, _| {
11338            assert!(pane.can_navigate_forward(), "Should be able to go forward");
11339        });
11340    }
11341
11342    #[gpui::test]
11343    async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11344        init_test(cx);
11345        let fs = FakeFs::new(cx.executor());
11346        let project = Project::test(fs, [], cx).await;
11347        let (multi_workspace, cx) =
11348            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11349        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11350
11351        workspace.update_in(cx, |workspace, window, cx| {
11352            let first_item = cx.new(|cx| {
11353                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11354            });
11355            workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11356            workspace.split_pane(
11357                workspace.active_pane().clone(),
11358                SplitDirection::Right,
11359                window,
11360                cx,
11361            );
11362            workspace.split_pane(
11363                workspace.active_pane().clone(),
11364                SplitDirection::Right,
11365                window,
11366                cx,
11367            );
11368        });
11369
11370        let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11371            let panes = workspace.center.panes();
11372            assert!(panes.len() >= 2);
11373            (
11374                panes.first().expect("at least one pane").entity_id(),
11375                panes.last().expect("at least one pane").entity_id(),
11376            )
11377        });
11378
11379        workspace.update_in(cx, |workspace, window, cx| {
11380            workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11381        });
11382        workspace.update(cx, |workspace, _| {
11383            assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11384            assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11385        });
11386
11387        cx.dispatch_action(ActivateLastPane);
11388
11389        workspace.update(cx, |workspace, _| {
11390            assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11391        });
11392    }
11393
11394    #[gpui::test]
11395    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11396        init_test(cx);
11397        let fs = FakeFs::new(cx.executor());
11398
11399        let project = Project::test(fs, [], cx).await;
11400        let (workspace, cx) =
11401            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11402
11403        let panel = workspace.update_in(cx, |workspace, window, cx| {
11404            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11405            workspace.add_panel(panel.clone(), window, cx);
11406
11407            workspace
11408                .right_dock()
11409                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11410
11411            panel
11412        });
11413
11414        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11415        pane.update_in(cx, |pane, window, cx| {
11416            let item = cx.new(TestItem::new);
11417            pane.add_item(Box::new(item), true, true, None, window, cx);
11418        });
11419
11420        // Transfer focus from center to panel
11421        workspace.update_in(cx, |workspace, window, cx| {
11422            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11423        });
11424
11425        workspace.update_in(cx, |workspace, window, cx| {
11426            assert!(workspace.right_dock().read(cx).is_open());
11427            assert!(!panel.is_zoomed(window, cx));
11428            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11429        });
11430
11431        // Transfer focus from panel to center
11432        workspace.update_in(cx, |workspace, window, cx| {
11433            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11434        });
11435
11436        workspace.update_in(cx, |workspace, window, cx| {
11437            assert!(workspace.right_dock().read(cx).is_open());
11438            assert!(!panel.is_zoomed(window, cx));
11439            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11440            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11441        });
11442
11443        // Close the dock
11444        workspace.update_in(cx, |workspace, window, cx| {
11445            workspace.toggle_dock(DockPosition::Right, window, cx);
11446        });
11447
11448        workspace.update_in(cx, |workspace, window, cx| {
11449            assert!(!workspace.right_dock().read(cx).is_open());
11450            assert!(!panel.is_zoomed(window, cx));
11451            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11452            assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11453        });
11454
11455        // Open the dock
11456        workspace.update_in(cx, |workspace, window, cx| {
11457            workspace.toggle_dock(DockPosition::Right, window, cx);
11458        });
11459
11460        workspace.update_in(cx, |workspace, window, cx| {
11461            assert!(workspace.right_dock().read(cx).is_open());
11462            assert!(!panel.is_zoomed(window, cx));
11463            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11464        });
11465
11466        // Focus and zoom panel
11467        panel.update_in(cx, |panel, window, cx| {
11468            cx.focus_self(window);
11469            panel.set_zoomed(true, window, cx)
11470        });
11471
11472        workspace.update_in(cx, |workspace, window, cx| {
11473            assert!(workspace.right_dock().read(cx).is_open());
11474            assert!(panel.is_zoomed(window, cx));
11475            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11476        });
11477
11478        // Transfer focus to the center closes the dock
11479        workspace.update_in(cx, |workspace, window, cx| {
11480            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11481        });
11482
11483        workspace.update_in(cx, |workspace, window, cx| {
11484            assert!(!workspace.right_dock().read(cx).is_open());
11485            assert!(panel.is_zoomed(window, cx));
11486            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11487        });
11488
11489        // Transferring focus back to the panel keeps it zoomed
11490        workspace.update_in(cx, |workspace, window, cx| {
11491            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11492        });
11493
11494        workspace.update_in(cx, |workspace, window, cx| {
11495            assert!(workspace.right_dock().read(cx).is_open());
11496            assert!(panel.is_zoomed(window, cx));
11497            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11498        });
11499
11500        // Close the dock while it is zoomed
11501        workspace.update_in(cx, |workspace, window, cx| {
11502            workspace.toggle_dock(DockPosition::Right, window, cx)
11503        });
11504
11505        workspace.update_in(cx, |workspace, window, cx| {
11506            assert!(!workspace.right_dock().read(cx).is_open());
11507            assert!(panel.is_zoomed(window, cx));
11508            assert!(workspace.zoomed.is_none());
11509            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11510        });
11511
11512        // Opening the dock, when it's zoomed, retains focus
11513        workspace.update_in(cx, |workspace, window, cx| {
11514            workspace.toggle_dock(DockPosition::Right, window, cx)
11515        });
11516
11517        workspace.update_in(cx, |workspace, window, cx| {
11518            assert!(workspace.right_dock().read(cx).is_open());
11519            assert!(panel.is_zoomed(window, cx));
11520            assert!(workspace.zoomed.is_some());
11521            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11522        });
11523
11524        // Unzoom and close the panel, zoom the active pane.
11525        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11526        workspace.update_in(cx, |workspace, window, cx| {
11527            workspace.toggle_dock(DockPosition::Right, window, cx)
11528        });
11529        pane.update_in(cx, |pane, window, cx| {
11530            pane.toggle_zoom(&Default::default(), window, cx)
11531        });
11532
11533        // Opening a dock unzooms the pane.
11534        workspace.update_in(cx, |workspace, window, cx| {
11535            workspace.toggle_dock(DockPosition::Right, window, cx)
11536        });
11537        workspace.update_in(cx, |workspace, window, cx| {
11538            let pane = pane.read(cx);
11539            assert!(!pane.is_zoomed());
11540            assert!(!pane.focus_handle(cx).is_focused(window));
11541            assert!(workspace.right_dock().read(cx).is_open());
11542            assert!(workspace.zoomed.is_none());
11543        });
11544    }
11545
11546    #[gpui::test]
11547    async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11548        init_test(cx);
11549        let fs = FakeFs::new(cx.executor());
11550
11551        let project = Project::test(fs, [], cx).await;
11552        let (workspace, cx) =
11553            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11554
11555        let panel = workspace.update_in(cx, |workspace, window, cx| {
11556            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11557            workspace.add_panel(panel.clone(), window, cx);
11558            panel
11559        });
11560
11561        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11562        pane.update_in(cx, |pane, window, cx| {
11563            let item = cx.new(TestItem::new);
11564            pane.add_item(Box::new(item), true, true, None, window, cx);
11565        });
11566
11567        // Enable close_panel_on_toggle
11568        cx.update_global(|store: &mut SettingsStore, cx| {
11569            store.update_user_settings(cx, |settings| {
11570                settings.workspace.close_panel_on_toggle = Some(true);
11571            });
11572        });
11573
11574        // Panel starts closed. Toggling should open and focus it.
11575        workspace.update_in(cx, |workspace, window, cx| {
11576            assert!(!workspace.right_dock().read(cx).is_open());
11577            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11578        });
11579
11580        workspace.update_in(cx, |workspace, window, cx| {
11581            assert!(
11582                workspace.right_dock().read(cx).is_open(),
11583                "Dock should be open after toggling from center"
11584            );
11585            assert!(
11586                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11587                "Panel should be focused after toggling from center"
11588            );
11589        });
11590
11591        // Panel is open and focused. Toggling should close the panel and
11592        // return focus to the center.
11593        workspace.update_in(cx, |workspace, window, cx| {
11594            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11595        });
11596
11597        workspace.update_in(cx, |workspace, window, cx| {
11598            assert!(
11599                !workspace.right_dock().read(cx).is_open(),
11600                "Dock should be closed after toggling from focused panel"
11601            );
11602            assert!(
11603                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11604                "Panel should not be focused after toggling from focused panel"
11605            );
11606        });
11607
11608        // Open the dock and focus something else so the panel is open but not
11609        // focused. Toggling should focus the panel (not close it).
11610        workspace.update_in(cx, |workspace, window, cx| {
11611            workspace
11612                .right_dock()
11613                .update(cx, |dock, cx| dock.set_open(true, window, cx));
11614            window.focus(&pane.read(cx).focus_handle(cx), cx);
11615        });
11616
11617        workspace.update_in(cx, |workspace, window, cx| {
11618            assert!(workspace.right_dock().read(cx).is_open());
11619            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11620            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11621        });
11622
11623        workspace.update_in(cx, |workspace, window, cx| {
11624            assert!(
11625                workspace.right_dock().read(cx).is_open(),
11626                "Dock should remain open when toggling focuses an open-but-unfocused panel"
11627            );
11628            assert!(
11629                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11630                "Panel should be focused after toggling an open-but-unfocused panel"
11631            );
11632        });
11633
11634        // Now disable the setting and verify the original behavior: toggling
11635        // from a focused panel moves focus to center but leaves the dock open.
11636        cx.update_global(|store: &mut SettingsStore, cx| {
11637            store.update_user_settings(cx, |settings| {
11638                settings.workspace.close_panel_on_toggle = Some(false);
11639            });
11640        });
11641
11642        workspace.update_in(cx, |workspace, window, cx| {
11643            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11644        });
11645
11646        workspace.update_in(cx, |workspace, window, cx| {
11647            assert!(
11648                workspace.right_dock().read(cx).is_open(),
11649                "Dock should remain open when setting is disabled"
11650            );
11651            assert!(
11652                !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11653                "Panel should not be focused after toggling with setting disabled"
11654            );
11655        });
11656    }
11657
11658    #[gpui::test]
11659    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11660        init_test(cx);
11661        let fs = FakeFs::new(cx.executor());
11662
11663        let project = Project::test(fs, [], cx).await;
11664        let (workspace, cx) =
11665            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11666
11667        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11668            workspace.active_pane().clone()
11669        });
11670
11671        // Add an item to the pane so it can be zoomed
11672        workspace.update_in(cx, |workspace, window, cx| {
11673            let item = cx.new(TestItem::new);
11674            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11675        });
11676
11677        // Initially not zoomed
11678        workspace.update_in(cx, |workspace, _window, cx| {
11679            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11680            assert!(
11681                workspace.zoomed.is_none(),
11682                "Workspace should track no zoomed pane"
11683            );
11684            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11685        });
11686
11687        // Zoom In
11688        pane.update_in(cx, |pane, window, cx| {
11689            pane.zoom_in(&crate::ZoomIn, window, cx);
11690        });
11691
11692        workspace.update_in(cx, |workspace, window, cx| {
11693            assert!(
11694                pane.read(cx).is_zoomed(),
11695                "Pane should be zoomed after ZoomIn"
11696            );
11697            assert!(
11698                workspace.zoomed.is_some(),
11699                "Workspace should track the zoomed pane"
11700            );
11701            assert!(
11702                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11703                "ZoomIn should focus the pane"
11704            );
11705        });
11706
11707        // Zoom In again is a no-op
11708        pane.update_in(cx, |pane, window, cx| {
11709            pane.zoom_in(&crate::ZoomIn, window, cx);
11710        });
11711
11712        workspace.update_in(cx, |workspace, window, cx| {
11713            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11714            assert!(
11715                workspace.zoomed.is_some(),
11716                "Workspace still tracks zoomed pane"
11717            );
11718            assert!(
11719                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11720                "Pane remains focused after repeated ZoomIn"
11721            );
11722        });
11723
11724        // Zoom Out
11725        pane.update_in(cx, |pane, window, cx| {
11726            pane.zoom_out(&crate::ZoomOut, window, cx);
11727        });
11728
11729        workspace.update_in(cx, |workspace, _window, cx| {
11730            assert!(
11731                !pane.read(cx).is_zoomed(),
11732                "Pane should unzoom after ZoomOut"
11733            );
11734            assert!(
11735                workspace.zoomed.is_none(),
11736                "Workspace clears zoom tracking after ZoomOut"
11737            );
11738        });
11739
11740        // Zoom Out again is a no-op
11741        pane.update_in(cx, |pane, window, cx| {
11742            pane.zoom_out(&crate::ZoomOut, window, cx);
11743        });
11744
11745        workspace.update_in(cx, |workspace, _window, cx| {
11746            assert!(
11747                !pane.read(cx).is_zoomed(),
11748                "Second ZoomOut keeps pane unzoomed"
11749            );
11750            assert!(
11751                workspace.zoomed.is_none(),
11752                "Workspace remains without zoomed pane"
11753            );
11754        });
11755    }
11756
11757    #[gpui::test]
11758    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11759        init_test(cx);
11760        let fs = FakeFs::new(cx.executor());
11761
11762        let project = Project::test(fs, [], cx).await;
11763        let (workspace, cx) =
11764            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11765        workspace.update_in(cx, |workspace, window, cx| {
11766            // Open two docks
11767            let left_dock = workspace.dock_at_position(DockPosition::Left);
11768            let right_dock = workspace.dock_at_position(DockPosition::Right);
11769
11770            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11771            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11772
11773            assert!(left_dock.read(cx).is_open());
11774            assert!(right_dock.read(cx).is_open());
11775        });
11776
11777        workspace.update_in(cx, |workspace, window, cx| {
11778            // Toggle all docks - should close both
11779            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11780
11781            let left_dock = workspace.dock_at_position(DockPosition::Left);
11782            let right_dock = workspace.dock_at_position(DockPosition::Right);
11783            assert!(!left_dock.read(cx).is_open());
11784            assert!(!right_dock.read(cx).is_open());
11785        });
11786
11787        workspace.update_in(cx, |workspace, window, cx| {
11788            // Toggle again - should reopen both
11789            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11790
11791            let left_dock = workspace.dock_at_position(DockPosition::Left);
11792            let right_dock = workspace.dock_at_position(DockPosition::Right);
11793            assert!(left_dock.read(cx).is_open());
11794            assert!(right_dock.read(cx).is_open());
11795        });
11796    }
11797
11798    #[gpui::test]
11799    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11800        init_test(cx);
11801        let fs = FakeFs::new(cx.executor());
11802
11803        let project = Project::test(fs, [], cx).await;
11804        let (workspace, cx) =
11805            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11806        workspace.update_in(cx, |workspace, window, cx| {
11807            // Open two docks
11808            let left_dock = workspace.dock_at_position(DockPosition::Left);
11809            let right_dock = workspace.dock_at_position(DockPosition::Right);
11810
11811            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11812            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11813
11814            assert!(left_dock.read(cx).is_open());
11815            assert!(right_dock.read(cx).is_open());
11816        });
11817
11818        workspace.update_in(cx, |workspace, window, cx| {
11819            // Close them manually
11820            workspace.toggle_dock(DockPosition::Left, window, cx);
11821            workspace.toggle_dock(DockPosition::Right, window, cx);
11822
11823            let left_dock = workspace.dock_at_position(DockPosition::Left);
11824            let right_dock = workspace.dock_at_position(DockPosition::Right);
11825            assert!(!left_dock.read(cx).is_open());
11826            assert!(!right_dock.read(cx).is_open());
11827        });
11828
11829        workspace.update_in(cx, |workspace, window, cx| {
11830            // Toggle all docks - only last closed (right dock) should reopen
11831            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11832
11833            let left_dock = workspace.dock_at_position(DockPosition::Left);
11834            let right_dock = workspace.dock_at_position(DockPosition::Right);
11835            assert!(!left_dock.read(cx).is_open());
11836            assert!(right_dock.read(cx).is_open());
11837        });
11838    }
11839
11840    #[gpui::test]
11841    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11842        init_test(cx);
11843        let fs = FakeFs::new(cx.executor());
11844        let project = Project::test(fs, [], cx).await;
11845        let (multi_workspace, cx) =
11846            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11847        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11848
11849        // Open two docks (left and right) with one panel each
11850        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11851            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11852            workspace.add_panel(left_panel.clone(), window, cx);
11853
11854            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11855            workspace.add_panel(right_panel.clone(), window, cx);
11856
11857            workspace.toggle_dock(DockPosition::Left, window, cx);
11858            workspace.toggle_dock(DockPosition::Right, window, cx);
11859
11860            // Verify initial state
11861            assert!(
11862                workspace.left_dock().read(cx).is_open(),
11863                "Left dock should be open"
11864            );
11865            assert_eq!(
11866                workspace
11867                    .left_dock()
11868                    .read(cx)
11869                    .visible_panel()
11870                    .unwrap()
11871                    .panel_id(),
11872                left_panel.panel_id(),
11873                "Left panel should be visible in left dock"
11874            );
11875            assert!(
11876                workspace.right_dock().read(cx).is_open(),
11877                "Right dock should be open"
11878            );
11879            assert_eq!(
11880                workspace
11881                    .right_dock()
11882                    .read(cx)
11883                    .visible_panel()
11884                    .unwrap()
11885                    .panel_id(),
11886                right_panel.panel_id(),
11887                "Right panel should be visible in right dock"
11888            );
11889            assert!(
11890                !workspace.bottom_dock().read(cx).is_open(),
11891                "Bottom dock should be closed"
11892            );
11893
11894            (left_panel, right_panel)
11895        });
11896
11897        // Focus the left panel and move it to the next position (bottom dock)
11898        workspace.update_in(cx, |workspace, window, cx| {
11899            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11900            assert!(
11901                left_panel.read(cx).focus_handle(cx).is_focused(window),
11902                "Left panel should be focused"
11903            );
11904        });
11905
11906        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11907
11908        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11909        workspace.update(cx, |workspace, cx| {
11910            assert!(
11911                !workspace.left_dock().read(cx).is_open(),
11912                "Left dock should be closed"
11913            );
11914            assert!(
11915                workspace.bottom_dock().read(cx).is_open(),
11916                "Bottom dock should now be open"
11917            );
11918            assert_eq!(
11919                left_panel.read(cx).position,
11920                DockPosition::Bottom,
11921                "Left panel should now be in the bottom dock"
11922            );
11923            assert_eq!(
11924                workspace
11925                    .bottom_dock()
11926                    .read(cx)
11927                    .visible_panel()
11928                    .unwrap()
11929                    .panel_id(),
11930                left_panel.panel_id(),
11931                "Left panel should be the visible panel in the bottom dock"
11932            );
11933        });
11934
11935        // Toggle all docks off
11936        workspace.update_in(cx, |workspace, window, cx| {
11937            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11938            assert!(
11939                !workspace.left_dock().read(cx).is_open(),
11940                "Left dock should be closed"
11941            );
11942            assert!(
11943                !workspace.right_dock().read(cx).is_open(),
11944                "Right dock should be closed"
11945            );
11946            assert!(
11947                !workspace.bottom_dock().read(cx).is_open(),
11948                "Bottom dock should be closed"
11949            );
11950        });
11951
11952        // Toggle all docks back on and verify positions are restored
11953        workspace.update_in(cx, |workspace, window, cx| {
11954            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11955            assert!(
11956                !workspace.left_dock().read(cx).is_open(),
11957                "Left dock should remain closed"
11958            );
11959            assert!(
11960                workspace.right_dock().read(cx).is_open(),
11961                "Right dock should remain open"
11962            );
11963            assert!(
11964                workspace.bottom_dock().read(cx).is_open(),
11965                "Bottom dock should remain open"
11966            );
11967            assert_eq!(
11968                left_panel.read(cx).position,
11969                DockPosition::Bottom,
11970                "Left panel should remain in the bottom dock"
11971            );
11972            assert_eq!(
11973                right_panel.read(cx).position,
11974                DockPosition::Right,
11975                "Right panel should remain in the right dock"
11976            );
11977            assert_eq!(
11978                workspace
11979                    .bottom_dock()
11980                    .read(cx)
11981                    .visible_panel()
11982                    .unwrap()
11983                    .panel_id(),
11984                left_panel.panel_id(),
11985                "Left panel should be the visible panel in the right dock"
11986            );
11987        });
11988    }
11989
11990    #[gpui::test]
11991    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11992        init_test(cx);
11993
11994        let fs = FakeFs::new(cx.executor());
11995
11996        let project = Project::test(fs, None, cx).await;
11997        let (workspace, cx) =
11998            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11999
12000        // Let's arrange the panes like this:
12001        //
12002        // +-----------------------+
12003        // |         top           |
12004        // +------+--------+-------+
12005        // | left | center | right |
12006        // +------+--------+-------+
12007        // |        bottom         |
12008        // +-----------------------+
12009
12010        let top_item = cx.new(|cx| {
12011            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12012        });
12013        let bottom_item = cx.new(|cx| {
12014            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12015        });
12016        let left_item = cx.new(|cx| {
12017            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12018        });
12019        let right_item = cx.new(|cx| {
12020            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12021        });
12022        let center_item = cx.new(|cx| {
12023            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12024        });
12025
12026        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12027            let top_pane_id = workspace.active_pane().entity_id();
12028            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12029            workspace.split_pane(
12030                workspace.active_pane().clone(),
12031                SplitDirection::Down,
12032                window,
12033                cx,
12034            );
12035            top_pane_id
12036        });
12037        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12038            let bottom_pane_id = workspace.active_pane().entity_id();
12039            workspace.add_item_to_active_pane(
12040                Box::new(bottom_item.clone()),
12041                None,
12042                false,
12043                window,
12044                cx,
12045            );
12046            workspace.split_pane(
12047                workspace.active_pane().clone(),
12048                SplitDirection::Up,
12049                window,
12050                cx,
12051            );
12052            bottom_pane_id
12053        });
12054        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12055            let left_pane_id = workspace.active_pane().entity_id();
12056            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12057            workspace.split_pane(
12058                workspace.active_pane().clone(),
12059                SplitDirection::Right,
12060                window,
12061                cx,
12062            );
12063            left_pane_id
12064        });
12065        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12066            let right_pane_id = workspace.active_pane().entity_id();
12067            workspace.add_item_to_active_pane(
12068                Box::new(right_item.clone()),
12069                None,
12070                false,
12071                window,
12072                cx,
12073            );
12074            workspace.split_pane(
12075                workspace.active_pane().clone(),
12076                SplitDirection::Left,
12077                window,
12078                cx,
12079            );
12080            right_pane_id
12081        });
12082        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12083            let center_pane_id = workspace.active_pane().entity_id();
12084            workspace.add_item_to_active_pane(
12085                Box::new(center_item.clone()),
12086                None,
12087                false,
12088                window,
12089                cx,
12090            );
12091            center_pane_id
12092        });
12093        cx.executor().run_until_parked();
12094
12095        workspace.update_in(cx, |workspace, window, cx| {
12096            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12097
12098            // Join into next from center pane into right
12099            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12100        });
12101
12102        workspace.update_in(cx, |workspace, window, cx| {
12103            let active_pane = workspace.active_pane();
12104            assert_eq!(right_pane_id, active_pane.entity_id());
12105            assert_eq!(2, active_pane.read(cx).items_len());
12106            let item_ids_in_pane =
12107                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12108            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12109            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12110
12111            // Join into next from right pane into bottom
12112            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12113        });
12114
12115        workspace.update_in(cx, |workspace, window, cx| {
12116            let active_pane = workspace.active_pane();
12117            assert_eq!(bottom_pane_id, active_pane.entity_id());
12118            assert_eq!(3, active_pane.read(cx).items_len());
12119            let item_ids_in_pane =
12120                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12121            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12122            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12123            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12124
12125            // Join into next from bottom pane into left
12126            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12127        });
12128
12129        workspace.update_in(cx, |workspace, window, cx| {
12130            let active_pane = workspace.active_pane();
12131            assert_eq!(left_pane_id, active_pane.entity_id());
12132            assert_eq!(4, active_pane.read(cx).items_len());
12133            let item_ids_in_pane =
12134                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12135            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12136            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12137            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12138            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12139
12140            // Join into next from left pane into top
12141            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12142        });
12143
12144        workspace.update_in(cx, |workspace, window, cx| {
12145            let active_pane = workspace.active_pane();
12146            assert_eq!(top_pane_id, active_pane.entity_id());
12147            assert_eq!(5, active_pane.read(cx).items_len());
12148            let item_ids_in_pane =
12149                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12150            assert!(item_ids_in_pane.contains(&center_item.item_id()));
12151            assert!(item_ids_in_pane.contains(&right_item.item_id()));
12152            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12153            assert!(item_ids_in_pane.contains(&left_item.item_id()));
12154            assert!(item_ids_in_pane.contains(&top_item.item_id()));
12155
12156            // Single pane left: no-op
12157            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12158        });
12159
12160        workspace.update(cx, |workspace, _cx| {
12161            let active_pane = workspace.active_pane();
12162            assert_eq!(top_pane_id, active_pane.entity_id());
12163        });
12164    }
12165
12166    fn add_an_item_to_active_pane(
12167        cx: &mut VisualTestContext,
12168        workspace: &Entity<Workspace>,
12169        item_id: u64,
12170    ) -> Entity<TestItem> {
12171        let item = cx.new(|cx| {
12172            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12173                item_id,
12174                "item{item_id}.txt",
12175                cx,
12176            )])
12177        });
12178        workspace.update_in(cx, |workspace, window, cx| {
12179            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12180        });
12181        item
12182    }
12183
12184    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12185        workspace.update_in(cx, |workspace, window, cx| {
12186            workspace.split_pane(
12187                workspace.active_pane().clone(),
12188                SplitDirection::Right,
12189                window,
12190                cx,
12191            )
12192        })
12193    }
12194
12195    #[gpui::test]
12196    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12197        init_test(cx);
12198        let fs = FakeFs::new(cx.executor());
12199        let project = Project::test(fs, None, cx).await;
12200        let (workspace, cx) =
12201            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12202
12203        add_an_item_to_active_pane(cx, &workspace, 1);
12204        split_pane(cx, &workspace);
12205        add_an_item_to_active_pane(cx, &workspace, 2);
12206        split_pane(cx, &workspace); // empty pane
12207        split_pane(cx, &workspace);
12208        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12209
12210        cx.executor().run_until_parked();
12211
12212        workspace.update(cx, |workspace, cx| {
12213            let num_panes = workspace.panes().len();
12214            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12215            let active_item = workspace
12216                .active_pane()
12217                .read(cx)
12218                .active_item()
12219                .expect("item is in focus");
12220
12221            assert_eq!(num_panes, 4);
12222            assert_eq!(num_items_in_current_pane, 1);
12223            assert_eq!(active_item.item_id(), last_item.item_id());
12224        });
12225
12226        workspace.update_in(cx, |workspace, window, cx| {
12227            workspace.join_all_panes(window, cx);
12228        });
12229
12230        workspace.update(cx, |workspace, cx| {
12231            let num_panes = workspace.panes().len();
12232            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12233            let active_item = workspace
12234                .active_pane()
12235                .read(cx)
12236                .active_item()
12237                .expect("item is in focus");
12238
12239            assert_eq!(num_panes, 1);
12240            assert_eq!(num_items_in_current_pane, 3);
12241            assert_eq!(active_item.item_id(), last_item.item_id());
12242        });
12243    }
12244
12245    #[gpui::test]
12246    async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12247        init_test(cx);
12248        let fs = FakeFs::new(cx.executor());
12249
12250        let project = Project::test(fs, [], cx).await;
12251        let (multi_workspace, cx) =
12252            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12253        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12254
12255        workspace.update(cx, |workspace, _cx| {
12256            workspace.bounds.size.width = px(800.);
12257        });
12258
12259        workspace.update_in(cx, |workspace, window, cx| {
12260            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12261            workspace.add_panel(panel, window, cx);
12262            workspace.toggle_dock(DockPosition::Right, window, cx);
12263        });
12264
12265        let (panel, resized_width, ratio_basis_width) =
12266            workspace.update_in(cx, |workspace, window, cx| {
12267                let item = cx.new(|cx| {
12268                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12269                });
12270                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12271
12272                let dock = workspace.right_dock().read(cx);
12273                let workspace_width = workspace.bounds.size.width;
12274                let initial_width = dock
12275                    .active_panel()
12276                    .map(|panel| {
12277                        workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx)
12278                    })
12279                    .expect("flexible dock should have an initial width");
12280
12281                assert_eq!(initial_width, workspace_width / 2.);
12282
12283                workspace.resize_right_dock(px(300.), window, cx);
12284
12285                let dock = workspace.right_dock().read(cx);
12286                let resized_width = dock
12287                    .active_panel()
12288                    .map(|panel| {
12289                        workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx)
12290                    })
12291                    .expect("flexible dock should keep its resized width");
12292
12293                assert_eq!(resized_width, px(300.));
12294
12295                let panel = workspace
12296                    .right_dock()
12297                    .read(cx)
12298                    .visible_panel()
12299                    .expect("flexible dock should have a visible panel")
12300                    .panel_id();
12301
12302                (panel, resized_width, workspace_width)
12303            });
12304
12305        workspace.update_in(cx, |workspace, window, cx| {
12306            workspace.toggle_dock(DockPosition::Right, window, cx);
12307            workspace.toggle_dock(DockPosition::Right, window, cx);
12308
12309            let dock = workspace.right_dock().read(cx);
12310            let reopened_width = dock
12311                .active_panel()
12312                .map(|panel| workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx))
12313                .expect("flexible dock should restore when reopened");
12314
12315            assert_eq!(reopened_width, resized_width);
12316
12317            let right_dock = workspace.right_dock().read(cx);
12318            let flexible_panel = right_dock
12319                .visible_panel()
12320                .expect("flexible dock should still have a visible panel");
12321            assert_eq!(flexible_panel.panel_id(), panel);
12322            assert_eq!(
12323                right_dock
12324                    .stored_panel_size_state(flexible_panel.as_ref())
12325                    .and_then(|size_state| size_state.flexible_size_ratio),
12326                Some(resized_width.to_f64() as f32 / workspace.bounds.size.width.to_f64() as f32)
12327            );
12328        });
12329
12330        workspace.update_in(cx, |workspace, window, cx| {
12331            workspace.split_pane(
12332                workspace.active_pane().clone(),
12333                SplitDirection::Right,
12334                window,
12335                cx,
12336            );
12337
12338            let dock = workspace.right_dock().read(cx);
12339            let split_width = dock
12340                .active_panel()
12341                .map(|panel| workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx))
12342                .expect("flexible dock should keep its user-resized proportion");
12343
12344            assert_eq!(split_width, px(300.));
12345
12346            workspace.bounds.size.width = px(1600.);
12347
12348            let dock = workspace.right_dock().read(cx);
12349            let resized_window_width = dock
12350                .active_panel()
12351                .map(|panel| workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx))
12352                .expect("flexible dock should preserve proportional size on window resize");
12353
12354            assert_eq!(
12355                resized_window_width,
12356                workspace.bounds.size.width
12357                    * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12358            );
12359        });
12360    }
12361
12362    #[gpui::test]
12363    async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12364        init_test(cx);
12365        let fs = FakeFs::new(cx.executor());
12366
12367        // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12368        {
12369            let project = Project::test(fs.clone(), [], cx).await;
12370            let (multi_workspace, cx) =
12371                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12372            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12373
12374            workspace.update(cx, |workspace, _cx| {
12375                workspace.set_random_database_id();
12376                workspace.bounds.size.width = px(800.);
12377            });
12378
12379            let panel = workspace.update_in(cx, |workspace, window, cx| {
12380                let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12381                workspace.add_panel(panel.clone(), window, cx);
12382                workspace.toggle_dock(DockPosition::Left, window, cx);
12383                panel
12384            });
12385
12386            workspace.update_in(cx, |workspace, window, cx| {
12387                workspace.resize_left_dock(px(350.), window, cx);
12388            });
12389
12390            cx.run_until_parked();
12391
12392            let persisted = workspace.read_with(cx, |workspace, cx| {
12393                workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12394            });
12395            assert_eq!(
12396                persisted.and_then(|s| s.size),
12397                Some(px(350.)),
12398                "fixed-width panel size should be persisted to KVP"
12399            );
12400
12401            // Remove the panel and re-add a fresh instance with the same key.
12402            // The new instance should have its size state restored from KVP.
12403            workspace.update_in(cx, |workspace, window, cx| {
12404                workspace.remove_panel(&panel, window, cx);
12405            });
12406
12407            workspace.update_in(cx, |workspace, window, cx| {
12408                let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12409                workspace.add_panel(new_panel, window, cx);
12410
12411                let left_dock = workspace.left_dock().read(cx);
12412                let size_state = left_dock
12413                    .panel::<TestPanel>()
12414                    .and_then(|p| left_dock.stored_panel_size_state(&p));
12415                assert_eq!(
12416                    size_state.and_then(|s| s.size),
12417                    Some(px(350.)),
12418                    "re-added fixed-width panel should restore persisted size from KVP"
12419                );
12420            });
12421        }
12422
12423        // Flexible panel: both pixel size and ratio are persisted and restored.
12424        {
12425            let project = Project::test(fs.clone(), [], cx).await;
12426            let (multi_workspace, cx) =
12427                cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12428            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12429
12430            workspace.update(cx, |workspace, _cx| {
12431                workspace.set_random_database_id();
12432                workspace.bounds.size.width = px(800.);
12433            });
12434
12435            let panel = workspace.update_in(cx, |workspace, window, cx| {
12436                let item = cx.new(|cx| {
12437                    TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12438                });
12439                workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12440
12441                let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12442                workspace.add_panel(panel.clone(), window, cx);
12443                workspace.toggle_dock(DockPosition::Right, window, cx);
12444                panel
12445            });
12446
12447            workspace.update_in(cx, |workspace, window, cx| {
12448                workspace.resize_right_dock(px(300.), window, cx);
12449            });
12450
12451            cx.run_until_parked();
12452
12453            let persisted = workspace
12454                .read_with(cx, |workspace, cx| {
12455                    workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12456                })
12457                .expect("flexible panel state should be persisted to KVP");
12458            assert_eq!(
12459                persisted.size, None,
12460                "flexible panel should not persist a redundant pixel size"
12461            );
12462            let original_ratio = persisted
12463                .flexible_size_ratio
12464                .expect("flexible panel ratio should be persisted");
12465
12466            // Remove the panel and re-add: both size and ratio should be restored.
12467            workspace.update_in(cx, |workspace, window, cx| {
12468                workspace.remove_panel(&panel, window, cx);
12469            });
12470
12471            workspace.update_in(cx, |workspace, window, cx| {
12472                let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12473                workspace.add_panel(new_panel, window, cx);
12474
12475                let right_dock = workspace.right_dock().read(cx);
12476                let size_state = right_dock
12477                    .panel::<TestPanel>()
12478                    .and_then(|p| right_dock.stored_panel_size_state(&p))
12479                    .expect("re-added flexible panel should have restored size state from KVP");
12480                assert_eq!(
12481                    size_state.size, None,
12482                    "re-added flexible panel should not have a persisted pixel size"
12483                );
12484                assert_eq!(
12485                    size_state.flexible_size_ratio,
12486                    Some(original_ratio),
12487                    "re-added flexible panel should restore persisted ratio"
12488                );
12489            });
12490        }
12491    }
12492
12493    #[gpui::test]
12494    async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12495        init_test(cx);
12496        let fs = FakeFs::new(cx.executor());
12497
12498        let project = Project::test(fs, [], cx).await;
12499        let (multi_workspace, cx) =
12500            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12501        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12502
12503        workspace.update(cx, |workspace, _cx| {
12504            workspace.bounds.size.width = px(900.);
12505        });
12506
12507        // Step 1: Add a tab to the center pane then open a flexible panel in the left
12508        // dock. With one full-width center pane the default ratio is 0.5, so the panel
12509        // and the center pane each take half the workspace width.
12510        workspace.update_in(cx, |workspace, window, cx| {
12511            let item = cx.new(|cx| {
12512                TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12513            });
12514            workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12515
12516            let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12517            workspace.add_panel(panel, window, cx);
12518            workspace.toggle_dock(DockPosition::Left, window, cx);
12519
12520            let left_dock = workspace.left_dock().read(cx);
12521            let left_width = left_dock
12522                .active_panel()
12523                .map(|p| workspace.resolved_dock_panel_size(&left_dock, p.as_ref(), window, cx))
12524                .expect("left dock should have an active panel");
12525
12526            assert_eq!(
12527                left_width,
12528                workspace.bounds.size.width / 2.,
12529                "flexible left panel should split evenly with the center pane"
12530            );
12531        });
12532
12533        // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12534        // change horizontal width fractions, so the flexible panel stays at the same
12535        // width as each half of the split.
12536        workspace.update_in(cx, |workspace, window, cx| {
12537            workspace.split_pane(
12538                workspace.active_pane().clone(),
12539                SplitDirection::Down,
12540                window,
12541                cx,
12542            );
12543
12544            let left_dock = workspace.left_dock().read(cx);
12545            let left_width = left_dock
12546                .active_panel()
12547                .map(|p| workspace.resolved_dock_panel_size(&left_dock, p.as_ref(), window, cx))
12548                .expect("left dock should still have an active panel after vertical split");
12549
12550            assert_eq!(
12551                left_width,
12552                workspace.bounds.size.width / 2.,
12553                "flexible left panel width should match each vertically-split pane"
12554            );
12555        });
12556
12557        // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12558        // size reduces the available width, so the flexible left panel and the center
12559        // panes all shrink proportionally to accommodate it.
12560        workspace.update_in(cx, |workspace, window, cx| {
12561            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12562            workspace.add_panel(panel, window, cx);
12563            workspace.toggle_dock(DockPosition::Right, window, cx);
12564
12565            let right_dock = workspace.right_dock().read(cx);
12566            let right_width = right_dock
12567                .active_panel()
12568                .map(|p| workspace.resolved_dock_panel_size(&right_dock, p.as_ref(), window, cx))
12569                .expect("right dock should have an active panel");
12570
12571            let left_dock = workspace.left_dock().read(cx);
12572            let left_width = left_dock
12573                .active_panel()
12574                .map(|p| workspace.resolved_dock_panel_size(&left_dock, p.as_ref(), window, cx))
12575                .expect("left dock should still have an active panel");
12576
12577            let available_width = workspace.bounds.size.width - right_width;
12578            assert_eq!(
12579                left_width,
12580                available_width / 2.,
12581                "flexible left panel should shrink proportionally as the right dock takes space"
12582            );
12583        });
12584    }
12585
12586    struct TestModal(FocusHandle);
12587
12588    impl TestModal {
12589        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12590            Self(cx.focus_handle())
12591        }
12592    }
12593
12594    impl EventEmitter<DismissEvent> for TestModal {}
12595
12596    impl Focusable for TestModal {
12597        fn focus_handle(&self, _cx: &App) -> FocusHandle {
12598            self.0.clone()
12599        }
12600    }
12601
12602    impl ModalView for TestModal {}
12603
12604    impl Render for TestModal {
12605        fn render(
12606            &mut self,
12607            _window: &mut Window,
12608            _cx: &mut Context<TestModal>,
12609        ) -> impl IntoElement {
12610            div().track_focus(&self.0)
12611        }
12612    }
12613
12614    #[gpui::test]
12615    async fn test_panels(cx: &mut gpui::TestAppContext) {
12616        init_test(cx);
12617        let fs = FakeFs::new(cx.executor());
12618
12619        let project = Project::test(fs, [], cx).await;
12620        let (multi_workspace, cx) =
12621            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12622        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12623
12624        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12625            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12626            workspace.add_panel(panel_1.clone(), window, cx);
12627            workspace.toggle_dock(DockPosition::Left, window, cx);
12628            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12629            workspace.add_panel(panel_2.clone(), window, cx);
12630            workspace.toggle_dock(DockPosition::Right, window, cx);
12631
12632            let left_dock = workspace.left_dock();
12633            assert_eq!(
12634                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12635                panel_1.panel_id()
12636            );
12637            assert_eq!(
12638                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
12639                px(300.)
12640            );
12641
12642            workspace.resize_left_dock(px(1337.), window, cx);
12643            assert_eq!(
12644                workspace
12645                    .right_dock()
12646                    .read(cx)
12647                    .visible_panel()
12648                    .unwrap()
12649                    .panel_id(),
12650                panel_2.panel_id(),
12651            );
12652
12653            (panel_1, panel_2)
12654        });
12655
12656        // Move panel_1 to the right
12657        panel_1.update_in(cx, |panel_1, window, cx| {
12658            panel_1.set_position(DockPosition::Right, window, cx)
12659        });
12660
12661        workspace.update_in(cx, |workspace, window, cx| {
12662            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12663            // Since it was the only panel on the left, the left dock should now be closed.
12664            assert!(!workspace.left_dock().read(cx).is_open());
12665            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12666            let right_dock = workspace.right_dock();
12667            assert_eq!(
12668                right_dock.read(cx).visible_panel().unwrap().panel_id(),
12669                panel_1.panel_id()
12670            );
12671            assert_eq!(
12672                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
12673                px(1337.)
12674            );
12675
12676            // Now we move panel_2 to the left
12677            panel_2.set_position(DockPosition::Left, window, cx);
12678        });
12679
12680        workspace.update(cx, |workspace, cx| {
12681            // Since panel_2 was not visible on the right, we don't open the left dock.
12682            assert!(!workspace.left_dock().read(cx).is_open());
12683            // And the right dock is unaffected in its displaying of panel_1
12684            assert!(workspace.right_dock().read(cx).is_open());
12685            assert_eq!(
12686                workspace
12687                    .right_dock()
12688                    .read(cx)
12689                    .visible_panel()
12690                    .unwrap()
12691                    .panel_id(),
12692                panel_1.panel_id(),
12693            );
12694        });
12695
12696        // Move panel_1 back to the left
12697        panel_1.update_in(cx, |panel_1, window, cx| {
12698            panel_1.set_position(DockPosition::Left, window, cx)
12699        });
12700
12701        workspace.update_in(cx, |workspace, window, cx| {
12702            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12703            let left_dock = workspace.left_dock();
12704            assert!(left_dock.read(cx).is_open());
12705            assert_eq!(
12706                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12707                panel_1.panel_id()
12708            );
12709            assert_eq!(
12710                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
12711                px(1337.)
12712            );
12713            // And the right dock should be closed as it no longer has any panels.
12714            assert!(!workspace.right_dock().read(cx).is_open());
12715
12716            // Now we move panel_1 to the bottom
12717            panel_1.set_position(DockPosition::Bottom, window, cx);
12718        });
12719
12720        workspace.update_in(cx, |workspace, window, cx| {
12721            // Since panel_1 was visible on the left, we close the left dock.
12722            assert!(!workspace.left_dock().read(cx).is_open());
12723            // The bottom dock is sized based on the panel's default size,
12724            // since the panel orientation changed from vertical to horizontal.
12725            let bottom_dock = workspace.bottom_dock();
12726            assert_eq!(
12727                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
12728                px(300.),
12729            );
12730            // Close bottom dock and move panel_1 back to the left.
12731            bottom_dock.update(cx, |bottom_dock, cx| {
12732                bottom_dock.set_open(false, window, cx)
12733            });
12734            panel_1.set_position(DockPosition::Left, window, cx);
12735        });
12736
12737        // Emit activated event on panel 1
12738        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12739
12740        // Now the left dock is open and panel_1 is active and focused.
12741        workspace.update_in(cx, |workspace, window, cx| {
12742            let left_dock = workspace.left_dock();
12743            assert!(left_dock.read(cx).is_open());
12744            assert_eq!(
12745                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12746                panel_1.panel_id(),
12747            );
12748            assert!(panel_1.focus_handle(cx).is_focused(window));
12749        });
12750
12751        // Emit closed event on panel 2, which is not active
12752        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12753
12754        // Wo don't close the left dock, because panel_2 wasn't the active panel
12755        workspace.update(cx, |workspace, cx| {
12756            let left_dock = workspace.left_dock();
12757            assert!(left_dock.read(cx).is_open());
12758            assert_eq!(
12759                left_dock.read(cx).visible_panel().unwrap().panel_id(),
12760                panel_1.panel_id(),
12761            );
12762        });
12763
12764        // Emitting a ZoomIn event shows the panel as zoomed.
12765        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12766        workspace.read_with(cx, |workspace, _| {
12767            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12768            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12769        });
12770
12771        // Move panel to another dock while it is zoomed
12772        panel_1.update_in(cx, |panel, window, cx| {
12773            panel.set_position(DockPosition::Right, window, cx)
12774        });
12775        workspace.read_with(cx, |workspace, _| {
12776            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12777
12778            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12779        });
12780
12781        // This is a helper for getting a:
12782        // - valid focus on an element,
12783        // - that isn't a part of the panes and panels system of the Workspace,
12784        // - and doesn't trigger the 'on_focus_lost' API.
12785        let focus_other_view = {
12786            let workspace = workspace.clone();
12787            move |cx: &mut VisualTestContext| {
12788                workspace.update_in(cx, |workspace, window, cx| {
12789                    if workspace.active_modal::<TestModal>(cx).is_some() {
12790                        workspace.toggle_modal(window, cx, TestModal::new);
12791                        workspace.toggle_modal(window, cx, TestModal::new);
12792                    } else {
12793                        workspace.toggle_modal(window, cx, TestModal::new);
12794                    }
12795                })
12796            }
12797        };
12798
12799        // If focus is transferred to another view that's not a panel or another pane, we still show
12800        // the panel as zoomed.
12801        focus_other_view(cx);
12802        workspace.read_with(cx, |workspace, _| {
12803            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12804            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12805        });
12806
12807        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12808        workspace.update_in(cx, |_workspace, window, cx| {
12809            cx.focus_self(window);
12810        });
12811        workspace.read_with(cx, |workspace, _| {
12812            assert_eq!(workspace.zoomed, None);
12813            assert_eq!(workspace.zoomed_position, None);
12814        });
12815
12816        // If focus is transferred again to another view that's not a panel or a pane, we won't
12817        // show the panel as zoomed because it wasn't zoomed before.
12818        focus_other_view(cx);
12819        workspace.read_with(cx, |workspace, _| {
12820            assert_eq!(workspace.zoomed, None);
12821            assert_eq!(workspace.zoomed_position, None);
12822        });
12823
12824        // When the panel is activated, it is zoomed again.
12825        cx.dispatch_action(ToggleRightDock);
12826        workspace.read_with(cx, |workspace, _| {
12827            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12828            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12829        });
12830
12831        // Emitting a ZoomOut event unzooms the panel.
12832        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12833        workspace.read_with(cx, |workspace, _| {
12834            assert_eq!(workspace.zoomed, None);
12835            assert_eq!(workspace.zoomed_position, None);
12836        });
12837
12838        // Emit closed event on panel 1, which is active
12839        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12840
12841        // Now the left dock is closed, because panel_1 was the active panel
12842        workspace.update(cx, |workspace, cx| {
12843            let right_dock = workspace.right_dock();
12844            assert!(!right_dock.read(cx).is_open());
12845        });
12846    }
12847
12848    #[gpui::test]
12849    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12850        init_test(cx);
12851
12852        let fs = FakeFs::new(cx.background_executor.clone());
12853        let project = Project::test(fs, [], cx).await;
12854        let (workspace, cx) =
12855            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12856        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12857
12858        let dirty_regular_buffer = cx.new(|cx| {
12859            TestItem::new(cx)
12860                .with_dirty(true)
12861                .with_label("1.txt")
12862                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12863        });
12864        let dirty_regular_buffer_2 = cx.new(|cx| {
12865            TestItem::new(cx)
12866                .with_dirty(true)
12867                .with_label("2.txt")
12868                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12869        });
12870        let dirty_multi_buffer_with_both = cx.new(|cx| {
12871            TestItem::new(cx)
12872                .with_dirty(true)
12873                .with_buffer_kind(ItemBufferKind::Multibuffer)
12874                .with_label("Fake Project Search")
12875                .with_project_items(&[
12876                    dirty_regular_buffer.read(cx).project_items[0].clone(),
12877                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12878                ])
12879        });
12880        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12881        workspace.update_in(cx, |workspace, window, cx| {
12882            workspace.add_item(
12883                pane.clone(),
12884                Box::new(dirty_regular_buffer.clone()),
12885                None,
12886                false,
12887                false,
12888                window,
12889                cx,
12890            );
12891            workspace.add_item(
12892                pane.clone(),
12893                Box::new(dirty_regular_buffer_2.clone()),
12894                None,
12895                false,
12896                false,
12897                window,
12898                cx,
12899            );
12900            workspace.add_item(
12901                pane.clone(),
12902                Box::new(dirty_multi_buffer_with_both.clone()),
12903                None,
12904                false,
12905                false,
12906                window,
12907                cx,
12908            );
12909        });
12910
12911        pane.update_in(cx, |pane, window, cx| {
12912            pane.activate_item(2, true, true, window, cx);
12913            assert_eq!(
12914                pane.active_item().unwrap().item_id(),
12915                multi_buffer_with_both_files_id,
12916                "Should select the multi buffer in the pane"
12917            );
12918        });
12919        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12920            pane.close_other_items(
12921                &CloseOtherItems {
12922                    save_intent: Some(SaveIntent::Save),
12923                    close_pinned: true,
12924                },
12925                None,
12926                window,
12927                cx,
12928            )
12929        });
12930        cx.background_executor.run_until_parked();
12931        assert!(!cx.has_pending_prompt());
12932        close_all_but_multi_buffer_task
12933            .await
12934            .expect("Closing all buffers but the multi buffer failed");
12935        pane.update(cx, |pane, cx| {
12936            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12937            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12938            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12939            assert_eq!(pane.items_len(), 1);
12940            assert_eq!(
12941                pane.active_item().unwrap().item_id(),
12942                multi_buffer_with_both_files_id,
12943                "Should have only the multi buffer left in the pane"
12944            );
12945            assert!(
12946                dirty_multi_buffer_with_both.read(cx).is_dirty,
12947                "The multi buffer containing the unsaved buffer should still be dirty"
12948            );
12949        });
12950
12951        dirty_regular_buffer.update(cx, |buffer, cx| {
12952            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12953        });
12954
12955        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12956            pane.close_active_item(
12957                &CloseActiveItem {
12958                    save_intent: Some(SaveIntent::Close),
12959                    close_pinned: false,
12960                },
12961                window,
12962                cx,
12963            )
12964        });
12965        cx.background_executor.run_until_parked();
12966        assert!(
12967            cx.has_pending_prompt(),
12968            "Dirty multi buffer should prompt a save dialog"
12969        );
12970        cx.simulate_prompt_answer("Save");
12971        cx.background_executor.run_until_parked();
12972        close_multi_buffer_task
12973            .await
12974            .expect("Closing the multi buffer failed");
12975        pane.update(cx, |pane, cx| {
12976            assert_eq!(
12977                dirty_multi_buffer_with_both.read(cx).save_count,
12978                1,
12979                "Multi buffer item should get be saved"
12980            );
12981            // Test impl does not save inner items, so we do not assert them
12982            assert_eq!(
12983                pane.items_len(),
12984                0,
12985                "No more items should be left in the pane"
12986            );
12987            assert!(pane.active_item().is_none());
12988        });
12989    }
12990
12991    #[gpui::test]
12992    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12993        cx: &mut TestAppContext,
12994    ) {
12995        init_test(cx);
12996
12997        let fs = FakeFs::new(cx.background_executor.clone());
12998        let project = Project::test(fs, [], cx).await;
12999        let (workspace, cx) =
13000            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13001        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13002
13003        let dirty_regular_buffer = cx.new(|cx| {
13004            TestItem::new(cx)
13005                .with_dirty(true)
13006                .with_label("1.txt")
13007                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13008        });
13009        let dirty_regular_buffer_2 = cx.new(|cx| {
13010            TestItem::new(cx)
13011                .with_dirty(true)
13012                .with_label("2.txt")
13013                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13014        });
13015        let clear_regular_buffer = cx.new(|cx| {
13016            TestItem::new(cx)
13017                .with_label("3.txt")
13018                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13019        });
13020
13021        let dirty_multi_buffer_with_both = cx.new(|cx| {
13022            TestItem::new(cx)
13023                .with_dirty(true)
13024                .with_buffer_kind(ItemBufferKind::Multibuffer)
13025                .with_label("Fake Project Search")
13026                .with_project_items(&[
13027                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13028                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13029                    clear_regular_buffer.read(cx).project_items[0].clone(),
13030                ])
13031        });
13032        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13033        workspace.update_in(cx, |workspace, window, cx| {
13034            workspace.add_item(
13035                pane.clone(),
13036                Box::new(dirty_regular_buffer.clone()),
13037                None,
13038                false,
13039                false,
13040                window,
13041                cx,
13042            );
13043            workspace.add_item(
13044                pane.clone(),
13045                Box::new(dirty_multi_buffer_with_both.clone()),
13046                None,
13047                false,
13048                false,
13049                window,
13050                cx,
13051            );
13052        });
13053
13054        pane.update_in(cx, |pane, window, cx| {
13055            pane.activate_item(1, true, true, window, cx);
13056            assert_eq!(
13057                pane.active_item().unwrap().item_id(),
13058                multi_buffer_with_both_files_id,
13059                "Should select the multi buffer in the pane"
13060            );
13061        });
13062        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13063            pane.close_active_item(
13064                &CloseActiveItem {
13065                    save_intent: None,
13066                    close_pinned: false,
13067                },
13068                window,
13069                cx,
13070            )
13071        });
13072        cx.background_executor.run_until_parked();
13073        assert!(
13074            cx.has_pending_prompt(),
13075            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13076        );
13077    }
13078
13079    /// Tests that when `close_on_file_delete` is enabled, files are automatically
13080    /// closed when they are deleted from disk.
13081    #[gpui::test]
13082    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13083        init_test(cx);
13084
13085        // Enable the close_on_disk_deletion setting
13086        cx.update_global(|store: &mut SettingsStore, cx| {
13087            store.update_user_settings(cx, |settings| {
13088                settings.workspace.close_on_file_delete = Some(true);
13089            });
13090        });
13091
13092        let fs = FakeFs::new(cx.background_executor.clone());
13093        let project = Project::test(fs, [], cx).await;
13094        let (workspace, cx) =
13095            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13096        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13097
13098        // Create a test item that simulates a file
13099        let item = cx.new(|cx| {
13100            TestItem::new(cx)
13101                .with_label("test.txt")
13102                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13103        });
13104
13105        // Add item to workspace
13106        workspace.update_in(cx, |workspace, window, cx| {
13107            workspace.add_item(
13108                pane.clone(),
13109                Box::new(item.clone()),
13110                None,
13111                false,
13112                false,
13113                window,
13114                cx,
13115            );
13116        });
13117
13118        // Verify the item is in the pane
13119        pane.read_with(cx, |pane, _| {
13120            assert_eq!(pane.items().count(), 1);
13121        });
13122
13123        // Simulate file deletion by setting the item's deleted state
13124        item.update(cx, |item, _| {
13125            item.set_has_deleted_file(true);
13126        });
13127
13128        // Emit UpdateTab event to trigger the close behavior
13129        cx.run_until_parked();
13130        item.update(cx, |_, cx| {
13131            cx.emit(ItemEvent::UpdateTab);
13132        });
13133
13134        // Allow the close operation to complete
13135        cx.run_until_parked();
13136
13137        // Verify the item was automatically closed
13138        pane.read_with(cx, |pane, _| {
13139            assert_eq!(
13140                pane.items().count(),
13141                0,
13142                "Item should be automatically closed when file is deleted"
13143            );
13144        });
13145    }
13146
13147    /// Tests that when `close_on_file_delete` is disabled (default), files remain
13148    /// open with a strikethrough when they are deleted from disk.
13149    #[gpui::test]
13150    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13151        init_test(cx);
13152
13153        // Ensure close_on_disk_deletion is disabled (default)
13154        cx.update_global(|store: &mut SettingsStore, cx| {
13155            store.update_user_settings(cx, |settings| {
13156                settings.workspace.close_on_file_delete = Some(false);
13157            });
13158        });
13159
13160        let fs = FakeFs::new(cx.background_executor.clone());
13161        let project = Project::test(fs, [], cx).await;
13162        let (workspace, cx) =
13163            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13164        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13165
13166        // Create a test item that simulates a file
13167        let item = cx.new(|cx| {
13168            TestItem::new(cx)
13169                .with_label("test.txt")
13170                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13171        });
13172
13173        // Add item to workspace
13174        workspace.update_in(cx, |workspace, window, cx| {
13175            workspace.add_item(
13176                pane.clone(),
13177                Box::new(item.clone()),
13178                None,
13179                false,
13180                false,
13181                window,
13182                cx,
13183            );
13184        });
13185
13186        // Verify the item is in the pane
13187        pane.read_with(cx, |pane, _| {
13188            assert_eq!(pane.items().count(), 1);
13189        });
13190
13191        // Simulate file deletion
13192        item.update(cx, |item, _| {
13193            item.set_has_deleted_file(true);
13194        });
13195
13196        // Emit UpdateTab event
13197        cx.run_until_parked();
13198        item.update(cx, |_, cx| {
13199            cx.emit(ItemEvent::UpdateTab);
13200        });
13201
13202        // Allow any potential close operation to complete
13203        cx.run_until_parked();
13204
13205        // Verify the item remains open (with strikethrough)
13206        pane.read_with(cx, |pane, _| {
13207            assert_eq!(
13208                pane.items().count(),
13209                1,
13210                "Item should remain open when close_on_disk_deletion is disabled"
13211            );
13212        });
13213
13214        // Verify the item shows as deleted
13215        item.read_with(cx, |item, _| {
13216            assert!(
13217                item.has_deleted_file,
13218                "Item should be marked as having deleted file"
13219            );
13220        });
13221    }
13222
13223    /// Tests that dirty files are not automatically closed when deleted from disk,
13224    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13225    /// unsaved changes without being prompted.
13226    #[gpui::test]
13227    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13228        init_test(cx);
13229
13230        // Enable the close_on_file_delete setting
13231        cx.update_global(|store: &mut SettingsStore, cx| {
13232            store.update_user_settings(cx, |settings| {
13233                settings.workspace.close_on_file_delete = Some(true);
13234            });
13235        });
13236
13237        let fs = FakeFs::new(cx.background_executor.clone());
13238        let project = Project::test(fs, [], cx).await;
13239        let (workspace, cx) =
13240            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13241        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13242
13243        // Create a dirty test item
13244        let item = cx.new(|cx| {
13245            TestItem::new(cx)
13246                .with_dirty(true)
13247                .with_label("test.txt")
13248                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13249        });
13250
13251        // Add item to workspace
13252        workspace.update_in(cx, |workspace, window, cx| {
13253            workspace.add_item(
13254                pane.clone(),
13255                Box::new(item.clone()),
13256                None,
13257                false,
13258                false,
13259                window,
13260                cx,
13261            );
13262        });
13263
13264        // Simulate file deletion
13265        item.update(cx, |item, _| {
13266            item.set_has_deleted_file(true);
13267        });
13268
13269        // Emit UpdateTab event to trigger the close behavior
13270        cx.run_until_parked();
13271        item.update(cx, |_, cx| {
13272            cx.emit(ItemEvent::UpdateTab);
13273        });
13274
13275        // Allow any potential close operation to complete
13276        cx.run_until_parked();
13277
13278        // Verify the item remains open (dirty files are not auto-closed)
13279        pane.read_with(cx, |pane, _| {
13280            assert_eq!(
13281                pane.items().count(),
13282                1,
13283                "Dirty items should not be automatically closed even when file is deleted"
13284            );
13285        });
13286
13287        // Verify the item is marked as deleted and still dirty
13288        item.read_with(cx, |item, _| {
13289            assert!(
13290                item.has_deleted_file,
13291                "Item should be marked as having deleted file"
13292            );
13293            assert!(item.is_dirty, "Item should still be dirty");
13294        });
13295    }
13296
13297    /// Tests that navigation history is cleaned up when files are auto-closed
13298    /// due to deletion from disk.
13299    #[gpui::test]
13300    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13301        init_test(cx);
13302
13303        // Enable the close_on_file_delete setting
13304        cx.update_global(|store: &mut SettingsStore, cx| {
13305            store.update_user_settings(cx, |settings| {
13306                settings.workspace.close_on_file_delete = Some(true);
13307            });
13308        });
13309
13310        let fs = FakeFs::new(cx.background_executor.clone());
13311        let project = Project::test(fs, [], cx).await;
13312        let (workspace, cx) =
13313            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13314        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13315
13316        // Create test items
13317        let item1 = cx.new(|cx| {
13318            TestItem::new(cx)
13319                .with_label("test1.txt")
13320                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13321        });
13322        let item1_id = item1.item_id();
13323
13324        let item2 = cx.new(|cx| {
13325            TestItem::new(cx)
13326                .with_label("test2.txt")
13327                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13328        });
13329
13330        // Add items to workspace
13331        workspace.update_in(cx, |workspace, window, cx| {
13332            workspace.add_item(
13333                pane.clone(),
13334                Box::new(item1.clone()),
13335                None,
13336                false,
13337                false,
13338                window,
13339                cx,
13340            );
13341            workspace.add_item(
13342                pane.clone(),
13343                Box::new(item2.clone()),
13344                None,
13345                false,
13346                false,
13347                window,
13348                cx,
13349            );
13350        });
13351
13352        // Activate item1 to ensure it gets navigation entries
13353        pane.update_in(cx, |pane, window, cx| {
13354            pane.activate_item(0, true, true, window, cx);
13355        });
13356
13357        // Switch to item2 and back to create navigation history
13358        pane.update_in(cx, |pane, window, cx| {
13359            pane.activate_item(1, true, true, window, cx);
13360        });
13361        cx.run_until_parked();
13362
13363        pane.update_in(cx, |pane, window, cx| {
13364            pane.activate_item(0, true, true, window, cx);
13365        });
13366        cx.run_until_parked();
13367
13368        // Simulate file deletion for item1
13369        item1.update(cx, |item, _| {
13370            item.set_has_deleted_file(true);
13371        });
13372
13373        // Emit UpdateTab event to trigger the close behavior
13374        item1.update(cx, |_, cx| {
13375            cx.emit(ItemEvent::UpdateTab);
13376        });
13377        cx.run_until_parked();
13378
13379        // Verify item1 was closed
13380        pane.read_with(cx, |pane, _| {
13381            assert_eq!(
13382                pane.items().count(),
13383                1,
13384                "Should have 1 item remaining after auto-close"
13385            );
13386        });
13387
13388        // Check navigation history after close
13389        let has_item = pane.read_with(cx, |pane, cx| {
13390            let mut has_item = false;
13391            pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13392                if entry.item.id() == item1_id {
13393                    has_item = true;
13394                }
13395            });
13396            has_item
13397        });
13398
13399        assert!(
13400            !has_item,
13401            "Navigation history should not contain closed item entries"
13402        );
13403    }
13404
13405    #[gpui::test]
13406    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13407        cx: &mut TestAppContext,
13408    ) {
13409        init_test(cx);
13410
13411        let fs = FakeFs::new(cx.background_executor.clone());
13412        let project = Project::test(fs, [], cx).await;
13413        let (workspace, cx) =
13414            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13415        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13416
13417        let dirty_regular_buffer = cx.new(|cx| {
13418            TestItem::new(cx)
13419                .with_dirty(true)
13420                .with_label("1.txt")
13421                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13422        });
13423        let dirty_regular_buffer_2 = cx.new(|cx| {
13424            TestItem::new(cx)
13425                .with_dirty(true)
13426                .with_label("2.txt")
13427                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13428        });
13429        let clear_regular_buffer = cx.new(|cx| {
13430            TestItem::new(cx)
13431                .with_label("3.txt")
13432                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13433        });
13434
13435        let dirty_multi_buffer = cx.new(|cx| {
13436            TestItem::new(cx)
13437                .with_dirty(true)
13438                .with_buffer_kind(ItemBufferKind::Multibuffer)
13439                .with_label("Fake Project Search")
13440                .with_project_items(&[
13441                    dirty_regular_buffer.read(cx).project_items[0].clone(),
13442                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13443                    clear_regular_buffer.read(cx).project_items[0].clone(),
13444                ])
13445        });
13446        workspace.update_in(cx, |workspace, window, cx| {
13447            workspace.add_item(
13448                pane.clone(),
13449                Box::new(dirty_regular_buffer.clone()),
13450                None,
13451                false,
13452                false,
13453                window,
13454                cx,
13455            );
13456            workspace.add_item(
13457                pane.clone(),
13458                Box::new(dirty_regular_buffer_2.clone()),
13459                None,
13460                false,
13461                false,
13462                window,
13463                cx,
13464            );
13465            workspace.add_item(
13466                pane.clone(),
13467                Box::new(dirty_multi_buffer.clone()),
13468                None,
13469                false,
13470                false,
13471                window,
13472                cx,
13473            );
13474        });
13475
13476        pane.update_in(cx, |pane, window, cx| {
13477            pane.activate_item(2, true, true, window, cx);
13478            assert_eq!(
13479                pane.active_item().unwrap().item_id(),
13480                dirty_multi_buffer.item_id(),
13481                "Should select the multi buffer in the pane"
13482            );
13483        });
13484        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13485            pane.close_active_item(
13486                &CloseActiveItem {
13487                    save_intent: None,
13488                    close_pinned: false,
13489                },
13490                window,
13491                cx,
13492            )
13493        });
13494        cx.background_executor.run_until_parked();
13495        assert!(
13496            !cx.has_pending_prompt(),
13497            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13498        );
13499        close_multi_buffer_task
13500            .await
13501            .expect("Closing multi buffer failed");
13502        pane.update(cx, |pane, cx| {
13503            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13504            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13505            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13506            assert_eq!(
13507                pane.items()
13508                    .map(|item| item.item_id())
13509                    .sorted()
13510                    .collect::<Vec<_>>(),
13511                vec![
13512                    dirty_regular_buffer.item_id(),
13513                    dirty_regular_buffer_2.item_id(),
13514                ],
13515                "Should have no multi buffer left in the pane"
13516            );
13517            assert!(dirty_regular_buffer.read(cx).is_dirty);
13518            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13519        });
13520    }
13521
13522    #[gpui::test]
13523    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13524        init_test(cx);
13525        let fs = FakeFs::new(cx.executor());
13526        let project = Project::test(fs, [], cx).await;
13527        let (multi_workspace, cx) =
13528            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13529        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13530
13531        // Add a new panel to the right dock, opening the dock and setting the
13532        // focus to the new panel.
13533        let panel = workspace.update_in(cx, |workspace, window, cx| {
13534            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13535            workspace.add_panel(panel.clone(), window, cx);
13536
13537            workspace
13538                .right_dock()
13539                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13540
13541            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13542
13543            panel
13544        });
13545
13546        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13547        // panel to the next valid position which, in this case, is the left
13548        // dock.
13549        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13550        workspace.update(cx, |workspace, cx| {
13551            assert!(workspace.left_dock().read(cx).is_open());
13552            assert_eq!(panel.read(cx).position, DockPosition::Left);
13553        });
13554
13555        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13556        // panel to the next valid position which, in this case, is the bottom
13557        // dock.
13558        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13559        workspace.update(cx, |workspace, cx| {
13560            assert!(workspace.bottom_dock().read(cx).is_open());
13561            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13562        });
13563
13564        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13565        // around moving the panel to its initial position, the right dock.
13566        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13567        workspace.update(cx, |workspace, cx| {
13568            assert!(workspace.right_dock().read(cx).is_open());
13569            assert_eq!(panel.read(cx).position, DockPosition::Right);
13570        });
13571
13572        // Remove focus from the panel, ensuring that, if the panel is not
13573        // focused, the `MoveFocusedPanelToNextPosition` action does not update
13574        // the panel's position, so the panel is still in the right dock.
13575        workspace.update_in(cx, |workspace, window, cx| {
13576            workspace.toggle_panel_focus::<TestPanel>(window, cx);
13577        });
13578
13579        cx.dispatch_action(MoveFocusedPanelToNextPosition);
13580        workspace.update(cx, |workspace, cx| {
13581            assert!(workspace.right_dock().read(cx).is_open());
13582            assert_eq!(panel.read(cx).position, DockPosition::Right);
13583        });
13584    }
13585
13586    #[gpui::test]
13587    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13588        init_test(cx);
13589
13590        let fs = FakeFs::new(cx.executor());
13591        let project = Project::test(fs, [], cx).await;
13592        let (workspace, cx) =
13593            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13594
13595        let item_1 = cx.new(|cx| {
13596            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13597        });
13598        workspace.update_in(cx, |workspace, window, cx| {
13599            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13600            workspace.move_item_to_pane_in_direction(
13601                &MoveItemToPaneInDirection {
13602                    direction: SplitDirection::Right,
13603                    focus: true,
13604                    clone: false,
13605                },
13606                window,
13607                cx,
13608            );
13609            workspace.move_item_to_pane_at_index(
13610                &MoveItemToPane {
13611                    destination: 3,
13612                    focus: true,
13613                    clone: false,
13614                },
13615                window,
13616                cx,
13617            );
13618
13619            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13620            assert_eq!(
13621                pane_items_paths(&workspace.active_pane, cx),
13622                vec!["first.txt".to_string()],
13623                "Single item was not moved anywhere"
13624            );
13625        });
13626
13627        let item_2 = cx.new(|cx| {
13628            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13629        });
13630        workspace.update_in(cx, |workspace, window, cx| {
13631            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13632            assert_eq!(
13633                pane_items_paths(&workspace.panes[0], cx),
13634                vec!["first.txt".to_string(), "second.txt".to_string()],
13635            );
13636            workspace.move_item_to_pane_in_direction(
13637                &MoveItemToPaneInDirection {
13638                    direction: SplitDirection::Right,
13639                    focus: true,
13640                    clone: false,
13641                },
13642                window,
13643                cx,
13644            );
13645
13646            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13647            assert_eq!(
13648                pane_items_paths(&workspace.panes[0], cx),
13649                vec!["first.txt".to_string()],
13650                "After moving, one item should be left in the original pane"
13651            );
13652            assert_eq!(
13653                pane_items_paths(&workspace.panes[1], cx),
13654                vec!["second.txt".to_string()],
13655                "New item should have been moved to the new pane"
13656            );
13657        });
13658
13659        let item_3 = cx.new(|cx| {
13660            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13661        });
13662        workspace.update_in(cx, |workspace, window, cx| {
13663            let original_pane = workspace.panes[0].clone();
13664            workspace.set_active_pane(&original_pane, window, cx);
13665            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13666            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13667            assert_eq!(
13668                pane_items_paths(&workspace.active_pane, cx),
13669                vec!["first.txt".to_string(), "third.txt".to_string()],
13670                "New pane should be ready to move one item out"
13671            );
13672
13673            workspace.move_item_to_pane_at_index(
13674                &MoveItemToPane {
13675                    destination: 3,
13676                    focus: true,
13677                    clone: false,
13678                },
13679                window,
13680                cx,
13681            );
13682            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13683            assert_eq!(
13684                pane_items_paths(&workspace.active_pane, cx),
13685                vec!["first.txt".to_string()],
13686                "After moving, one item should be left in the original pane"
13687            );
13688            assert_eq!(
13689                pane_items_paths(&workspace.panes[1], cx),
13690                vec!["second.txt".to_string()],
13691                "Previously created pane should be unchanged"
13692            );
13693            assert_eq!(
13694                pane_items_paths(&workspace.panes[2], cx),
13695                vec!["third.txt".to_string()],
13696                "New item should have been moved to the new pane"
13697            );
13698        });
13699    }
13700
13701    #[gpui::test]
13702    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13703        init_test(cx);
13704
13705        let fs = FakeFs::new(cx.executor());
13706        let project = Project::test(fs, [], cx).await;
13707        let (workspace, cx) =
13708            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13709
13710        let item_1 = cx.new(|cx| {
13711            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13712        });
13713        workspace.update_in(cx, |workspace, window, cx| {
13714            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13715            workspace.move_item_to_pane_in_direction(
13716                &MoveItemToPaneInDirection {
13717                    direction: SplitDirection::Right,
13718                    focus: true,
13719                    clone: true,
13720                },
13721                window,
13722                cx,
13723            );
13724        });
13725        cx.run_until_parked();
13726        workspace.update_in(cx, |workspace, window, cx| {
13727            workspace.move_item_to_pane_at_index(
13728                &MoveItemToPane {
13729                    destination: 3,
13730                    focus: true,
13731                    clone: true,
13732                },
13733                window,
13734                cx,
13735            );
13736        });
13737        cx.run_until_parked();
13738
13739        workspace.update(cx, |workspace, cx| {
13740            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13741            for pane in workspace.panes() {
13742                assert_eq!(
13743                    pane_items_paths(pane, cx),
13744                    vec!["first.txt".to_string()],
13745                    "Single item exists in all panes"
13746                );
13747            }
13748        });
13749
13750        // verify that the active pane has been updated after waiting for the
13751        // pane focus event to fire and resolve
13752        workspace.read_with(cx, |workspace, _app| {
13753            assert_eq!(
13754                workspace.active_pane(),
13755                &workspace.panes[2],
13756                "The third pane should be the active one: {:?}",
13757                workspace.panes
13758            );
13759        })
13760    }
13761
13762    #[gpui::test]
13763    async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13764        init_test(cx);
13765
13766        let fs = FakeFs::new(cx.executor());
13767        fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13768
13769        let project = Project::test(fs, ["root".as_ref()], cx).await;
13770        let (workspace, cx) =
13771            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13772
13773        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13774        // Add item to pane A with project path
13775        let item_a = cx.new(|cx| {
13776            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13777        });
13778        workspace.update_in(cx, |workspace, window, cx| {
13779            workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13780        });
13781
13782        // Split to create pane B
13783        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13784            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13785        });
13786
13787        // Add item with SAME project path to pane B, and pin it
13788        let item_b = cx.new(|cx| {
13789            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13790        });
13791        pane_b.update_in(cx, |pane, window, cx| {
13792            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13793            pane.set_pinned_count(1);
13794        });
13795
13796        assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13797        assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13798
13799        // close_pinned: false should only close the unpinned copy
13800        workspace.update_in(cx, |workspace, window, cx| {
13801            workspace.close_item_in_all_panes(
13802                &CloseItemInAllPanes {
13803                    save_intent: Some(SaveIntent::Close),
13804                    close_pinned: false,
13805                },
13806                window,
13807                cx,
13808            )
13809        });
13810        cx.executor().run_until_parked();
13811
13812        let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13813        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13814        assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13815        assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13816
13817        // Split again, seeing as closing the previous item also closed its
13818        // pane, so only pane remains, which does not allow us to properly test
13819        // that both items close when `close_pinned: true`.
13820        let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13821            workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13822        });
13823
13824        // Add an item with the same project path to pane C so that
13825        // close_item_in_all_panes can determine what to close across all panes
13826        // (it reads the active item from the active pane, and split_pane
13827        // creates an empty pane).
13828        let item_c = cx.new(|cx| {
13829            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13830        });
13831        pane_c.update_in(cx, |pane, window, cx| {
13832            pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13833        });
13834
13835        // close_pinned: true should close the pinned copy too
13836        workspace.update_in(cx, |workspace, window, cx| {
13837            let panes_count = workspace.panes().len();
13838            assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13839
13840            workspace.close_item_in_all_panes(
13841                &CloseItemInAllPanes {
13842                    save_intent: Some(SaveIntent::Close),
13843                    close_pinned: true,
13844                },
13845                window,
13846                cx,
13847            )
13848        });
13849        cx.executor().run_until_parked();
13850
13851        let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13852        let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13853        assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13854        assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13855    }
13856
13857    mod register_project_item_tests {
13858
13859        use super::*;
13860
13861        // View
13862        struct TestPngItemView {
13863            focus_handle: FocusHandle,
13864        }
13865        // Model
13866        struct TestPngItem {}
13867
13868        impl project::ProjectItem for TestPngItem {
13869            fn try_open(
13870                _project: &Entity<Project>,
13871                path: &ProjectPath,
13872                cx: &mut App,
13873            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13874                if path.path.extension().unwrap() == "png" {
13875                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13876                } else {
13877                    None
13878                }
13879            }
13880
13881            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13882                None
13883            }
13884
13885            fn project_path(&self, _: &App) -> Option<ProjectPath> {
13886                None
13887            }
13888
13889            fn is_dirty(&self) -> bool {
13890                false
13891            }
13892        }
13893
13894        impl Item for TestPngItemView {
13895            type Event = ();
13896            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13897                "".into()
13898            }
13899        }
13900        impl EventEmitter<()> for TestPngItemView {}
13901        impl Focusable for TestPngItemView {
13902            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13903                self.focus_handle.clone()
13904            }
13905        }
13906
13907        impl Render for TestPngItemView {
13908            fn render(
13909                &mut self,
13910                _window: &mut Window,
13911                _cx: &mut Context<Self>,
13912            ) -> impl IntoElement {
13913                Empty
13914            }
13915        }
13916
13917        impl ProjectItem for TestPngItemView {
13918            type Item = TestPngItem;
13919
13920            fn for_project_item(
13921                _project: Entity<Project>,
13922                _pane: Option<&Pane>,
13923                _item: Entity<Self::Item>,
13924                _: &mut Window,
13925                cx: &mut Context<Self>,
13926            ) -> Self
13927            where
13928                Self: Sized,
13929            {
13930                Self {
13931                    focus_handle: cx.focus_handle(),
13932                }
13933            }
13934        }
13935
13936        // View
13937        struct TestIpynbItemView {
13938            focus_handle: FocusHandle,
13939        }
13940        // Model
13941        struct TestIpynbItem {}
13942
13943        impl project::ProjectItem for TestIpynbItem {
13944            fn try_open(
13945                _project: &Entity<Project>,
13946                path: &ProjectPath,
13947                cx: &mut App,
13948            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13949                if path.path.extension().unwrap() == "ipynb" {
13950                    Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13951                } else {
13952                    None
13953                }
13954            }
13955
13956            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13957                None
13958            }
13959
13960            fn project_path(&self, _: &App) -> Option<ProjectPath> {
13961                None
13962            }
13963
13964            fn is_dirty(&self) -> bool {
13965                false
13966            }
13967        }
13968
13969        impl Item for TestIpynbItemView {
13970            type Event = ();
13971            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13972                "".into()
13973            }
13974        }
13975        impl EventEmitter<()> for TestIpynbItemView {}
13976        impl Focusable for TestIpynbItemView {
13977            fn focus_handle(&self, _cx: &App) -> FocusHandle {
13978                self.focus_handle.clone()
13979            }
13980        }
13981
13982        impl Render for TestIpynbItemView {
13983            fn render(
13984                &mut self,
13985                _window: &mut Window,
13986                _cx: &mut Context<Self>,
13987            ) -> impl IntoElement {
13988                Empty
13989            }
13990        }
13991
13992        impl ProjectItem for TestIpynbItemView {
13993            type Item = TestIpynbItem;
13994
13995            fn for_project_item(
13996                _project: Entity<Project>,
13997                _pane: Option<&Pane>,
13998                _item: Entity<Self::Item>,
13999                _: &mut Window,
14000                cx: &mut Context<Self>,
14001            ) -> Self
14002            where
14003                Self: Sized,
14004            {
14005                Self {
14006                    focus_handle: cx.focus_handle(),
14007                }
14008            }
14009        }
14010
14011        struct TestAlternatePngItemView {
14012            focus_handle: FocusHandle,
14013        }
14014
14015        impl Item for TestAlternatePngItemView {
14016            type Event = ();
14017            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14018                "".into()
14019            }
14020        }
14021
14022        impl EventEmitter<()> for TestAlternatePngItemView {}
14023        impl Focusable for TestAlternatePngItemView {
14024            fn focus_handle(&self, _cx: &App) -> FocusHandle {
14025                self.focus_handle.clone()
14026            }
14027        }
14028
14029        impl Render for TestAlternatePngItemView {
14030            fn render(
14031                &mut self,
14032                _window: &mut Window,
14033                _cx: &mut Context<Self>,
14034            ) -> impl IntoElement {
14035                Empty
14036            }
14037        }
14038
14039        impl ProjectItem for TestAlternatePngItemView {
14040            type Item = TestPngItem;
14041
14042            fn for_project_item(
14043                _project: Entity<Project>,
14044                _pane: Option<&Pane>,
14045                _item: Entity<Self::Item>,
14046                _: &mut Window,
14047                cx: &mut Context<Self>,
14048            ) -> Self
14049            where
14050                Self: Sized,
14051            {
14052                Self {
14053                    focus_handle: cx.focus_handle(),
14054                }
14055            }
14056        }
14057
14058        #[gpui::test]
14059        async fn test_register_project_item(cx: &mut TestAppContext) {
14060            init_test(cx);
14061
14062            cx.update(|cx| {
14063                register_project_item::<TestPngItemView>(cx);
14064                register_project_item::<TestIpynbItemView>(cx);
14065            });
14066
14067            let fs = FakeFs::new(cx.executor());
14068            fs.insert_tree(
14069                "/root1",
14070                json!({
14071                    "one.png": "BINARYDATAHERE",
14072                    "two.ipynb": "{ totally a notebook }",
14073                    "three.txt": "editing text, sure why not?"
14074                }),
14075            )
14076            .await;
14077
14078            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14079            let (workspace, cx) =
14080                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14081
14082            let worktree_id = project.update(cx, |project, cx| {
14083                project.worktrees(cx).next().unwrap().read(cx).id()
14084            });
14085
14086            let handle = workspace
14087                .update_in(cx, |workspace, window, cx| {
14088                    let project_path = (worktree_id, rel_path("one.png"));
14089                    workspace.open_path(project_path, None, true, window, cx)
14090                })
14091                .await
14092                .unwrap();
14093
14094            // Now we can check if the handle we got back errored or not
14095            assert_eq!(
14096                handle.to_any_view().entity_type(),
14097                TypeId::of::<TestPngItemView>()
14098            );
14099
14100            let handle = workspace
14101                .update_in(cx, |workspace, window, cx| {
14102                    let project_path = (worktree_id, rel_path("two.ipynb"));
14103                    workspace.open_path(project_path, None, true, window, cx)
14104                })
14105                .await
14106                .unwrap();
14107
14108            assert_eq!(
14109                handle.to_any_view().entity_type(),
14110                TypeId::of::<TestIpynbItemView>()
14111            );
14112
14113            let handle = workspace
14114                .update_in(cx, |workspace, window, cx| {
14115                    let project_path = (worktree_id, rel_path("three.txt"));
14116                    workspace.open_path(project_path, None, true, window, cx)
14117                })
14118                .await;
14119            assert!(handle.is_err());
14120        }
14121
14122        #[gpui::test]
14123        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14124            init_test(cx);
14125
14126            cx.update(|cx| {
14127                register_project_item::<TestPngItemView>(cx);
14128                register_project_item::<TestAlternatePngItemView>(cx);
14129            });
14130
14131            let fs = FakeFs::new(cx.executor());
14132            fs.insert_tree(
14133                "/root1",
14134                json!({
14135                    "one.png": "BINARYDATAHERE",
14136                    "two.ipynb": "{ totally a notebook }",
14137                    "three.txt": "editing text, sure why not?"
14138                }),
14139            )
14140            .await;
14141            let project = Project::test(fs, ["root1".as_ref()], cx).await;
14142            let (workspace, cx) =
14143                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14144            let worktree_id = project.update(cx, |project, cx| {
14145                project.worktrees(cx).next().unwrap().read(cx).id()
14146            });
14147
14148            let handle = workspace
14149                .update_in(cx, |workspace, window, cx| {
14150                    let project_path = (worktree_id, rel_path("one.png"));
14151                    workspace.open_path(project_path, None, true, window, cx)
14152                })
14153                .await
14154                .unwrap();
14155
14156            // This _must_ be the second item registered
14157            assert_eq!(
14158                handle.to_any_view().entity_type(),
14159                TypeId::of::<TestAlternatePngItemView>()
14160            );
14161
14162            let handle = workspace
14163                .update_in(cx, |workspace, window, cx| {
14164                    let project_path = (worktree_id, rel_path("three.txt"));
14165                    workspace.open_path(project_path, None, true, window, cx)
14166                })
14167                .await;
14168            assert!(handle.is_err());
14169        }
14170    }
14171
14172    #[gpui::test]
14173    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14174        init_test(cx);
14175
14176        let fs = FakeFs::new(cx.executor());
14177        let project = Project::test(fs, [], cx).await;
14178        let (workspace, _cx) =
14179            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14180
14181        // Test with status bar shown (default)
14182        workspace.read_with(cx, |workspace, cx| {
14183            let visible = workspace.status_bar_visible(cx);
14184            assert!(visible, "Status bar should be visible by default");
14185        });
14186
14187        // Test with status bar hidden
14188        cx.update_global(|store: &mut SettingsStore, cx| {
14189            store.update_user_settings(cx, |settings| {
14190                settings.status_bar.get_or_insert_default().show = Some(false);
14191            });
14192        });
14193
14194        workspace.read_with(cx, |workspace, cx| {
14195            let visible = workspace.status_bar_visible(cx);
14196            assert!(!visible, "Status bar should be hidden when show is false");
14197        });
14198
14199        // Test with status bar shown explicitly
14200        cx.update_global(|store: &mut SettingsStore, cx| {
14201            store.update_user_settings(cx, |settings| {
14202                settings.status_bar.get_or_insert_default().show = Some(true);
14203            });
14204        });
14205
14206        workspace.read_with(cx, |workspace, cx| {
14207            let visible = workspace.status_bar_visible(cx);
14208            assert!(visible, "Status bar should be visible when show is true");
14209        });
14210    }
14211
14212    #[gpui::test]
14213    async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14214        init_test(cx);
14215
14216        let fs = FakeFs::new(cx.executor());
14217        let project = Project::test(fs, [], cx).await;
14218        let (multi_workspace, cx) =
14219            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14220        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14221        let panel = workspace.update_in(cx, |workspace, window, cx| {
14222            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14223            workspace.add_panel(panel.clone(), window, cx);
14224
14225            workspace
14226                .right_dock()
14227                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14228
14229            panel
14230        });
14231
14232        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14233        let item_a = cx.new(TestItem::new);
14234        let item_b = cx.new(TestItem::new);
14235        let item_a_id = item_a.entity_id();
14236        let item_b_id = item_b.entity_id();
14237
14238        pane.update_in(cx, |pane, window, cx| {
14239            pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14240            pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14241        });
14242
14243        pane.read_with(cx, |pane, _| {
14244            assert_eq!(pane.items_len(), 2);
14245            assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14246        });
14247
14248        workspace.update_in(cx, |workspace, window, cx| {
14249            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14250        });
14251
14252        workspace.update_in(cx, |_, window, cx| {
14253            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14254        });
14255
14256        // Assert that the `pane::CloseActiveItem` action is handled at the
14257        // workspace level when one of the dock panels is focused and, in that
14258        // case, the center pane's active item is closed but the focus is not
14259        // moved.
14260        cx.dispatch_action(pane::CloseActiveItem::default());
14261        cx.run_until_parked();
14262
14263        pane.read_with(cx, |pane, _| {
14264            assert_eq!(pane.items_len(), 1);
14265            assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14266        });
14267
14268        workspace.update_in(cx, |workspace, window, cx| {
14269            assert!(workspace.right_dock().read(cx).is_open());
14270            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14271        });
14272    }
14273
14274    #[gpui::test]
14275    async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14276        init_test(cx);
14277        let fs = FakeFs::new(cx.executor());
14278
14279        let project_a = Project::test(fs.clone(), [], cx).await;
14280        let project_b = Project::test(fs, [], cx).await;
14281
14282        let multi_workspace_handle =
14283            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14284        cx.run_until_parked();
14285
14286        let workspace_a = multi_workspace_handle
14287            .read_with(cx, |mw, _| mw.workspace().clone())
14288            .unwrap();
14289
14290        let _workspace_b = multi_workspace_handle
14291            .update(cx, |mw, window, cx| {
14292                mw.test_add_workspace(project_b, window, cx)
14293            })
14294            .unwrap();
14295
14296        // Switch to workspace A
14297        multi_workspace_handle
14298            .update(cx, |mw, window, cx| {
14299                mw.activate_index(0, window, cx);
14300            })
14301            .unwrap();
14302
14303        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14304
14305        // Add a panel to workspace A's right dock and open the dock
14306        let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14307            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14308            workspace.add_panel(panel.clone(), window, cx);
14309            workspace
14310                .right_dock()
14311                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14312            panel
14313        });
14314
14315        // Focus the panel through the workspace (matching existing test pattern)
14316        workspace_a.update_in(cx, |workspace, window, cx| {
14317            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14318        });
14319
14320        // Zoom the panel
14321        panel.update_in(cx, |panel, window, cx| {
14322            panel.set_zoomed(true, window, cx);
14323        });
14324
14325        // Verify the panel is zoomed and the dock is open
14326        workspace_a.update_in(cx, |workspace, window, cx| {
14327            assert!(
14328                workspace.right_dock().read(cx).is_open(),
14329                "dock should be open before switch"
14330            );
14331            assert!(
14332                panel.is_zoomed(window, cx),
14333                "panel should be zoomed before switch"
14334            );
14335            assert!(
14336                panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14337                "panel should be focused before switch"
14338            );
14339        });
14340
14341        // Switch to workspace B
14342        multi_workspace_handle
14343            .update(cx, |mw, window, cx| {
14344                mw.activate_index(1, window, cx);
14345            })
14346            .unwrap();
14347        cx.run_until_parked();
14348
14349        // Switch back to workspace A
14350        multi_workspace_handle
14351            .update(cx, |mw, window, cx| {
14352                mw.activate_index(0, window, cx);
14353            })
14354            .unwrap();
14355        cx.run_until_parked();
14356
14357        // Verify the panel is still zoomed and the dock is still open
14358        workspace_a.update_in(cx, |workspace, window, cx| {
14359            assert!(
14360                workspace.right_dock().read(cx).is_open(),
14361                "dock should still be open after switching back"
14362            );
14363            assert!(
14364                panel.is_zoomed(window, cx),
14365                "panel should still be zoomed after switching back"
14366            );
14367        });
14368    }
14369
14370    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14371        pane.read(cx)
14372            .items()
14373            .flat_map(|item| {
14374                item.project_paths(cx)
14375                    .into_iter()
14376                    .map(|path| path.path.display(PathStyle::local()).into_owned())
14377            })
14378            .collect()
14379    }
14380
14381    pub fn init_test(cx: &mut TestAppContext) {
14382        cx.update(|cx| {
14383            let settings_store = SettingsStore::test(cx);
14384            cx.set_global(settings_store);
14385            cx.set_global(db::AppDatabase::test_new());
14386            theme::init(theme::LoadThemes::JustBase, cx);
14387        });
14388    }
14389
14390    #[gpui::test]
14391    async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14392        use settings::{ThemeName, ThemeSelection};
14393        use theme::SystemAppearance;
14394        use zed_actions::theme::ToggleMode;
14395
14396        init_test(cx);
14397
14398        let fs = FakeFs::new(cx.executor());
14399        let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14400
14401        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14402            .await;
14403
14404        // Build a test project and workspace view so the test can invoke
14405        // the workspace action handler the same way the UI would.
14406        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14407        let (workspace, cx) =
14408            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14409
14410        // Seed the settings file with a plain static light theme so the
14411        // first toggle always starts from a known persisted state.
14412        workspace.update_in(cx, |_workspace, _window, cx| {
14413            *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14414            settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14415                settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14416            });
14417        });
14418        cx.executor().advance_clock(Duration::from_millis(200));
14419        cx.run_until_parked();
14420
14421        // Confirm the initial persisted settings contain the static theme
14422        // we just wrote before any toggling happens.
14423        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14424        assert!(settings_text.contains(r#""theme": "One Light""#));
14425
14426        // Toggle once. This should migrate the persisted theme settings
14427        // into light/dark slots and enable system mode.
14428        workspace.update_in(cx, |workspace, window, cx| {
14429            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14430        });
14431        cx.executor().advance_clock(Duration::from_millis(200));
14432        cx.run_until_parked();
14433
14434        // 1. Static -> Dynamic
14435        // this assertion checks theme changed from static to dynamic.
14436        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14437        let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14438        assert_eq!(
14439            parsed["theme"],
14440            serde_json::json!({
14441                "mode": "system",
14442                "light": "One Light",
14443                "dark": "One Dark"
14444            })
14445        );
14446
14447        // 2. Toggle again, suppose it will change the mode to light
14448        workspace.update_in(cx, |workspace, window, cx| {
14449            workspace.toggle_theme_mode(&ToggleMode, window, cx);
14450        });
14451        cx.executor().advance_clock(Duration::from_millis(200));
14452        cx.run_until_parked();
14453
14454        let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14455        assert!(settings_text.contains(r#""mode": "light""#));
14456    }
14457
14458    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14459        let item = TestProjectItem::new(id, path, cx);
14460        item.update(cx, |item, _| {
14461            item.is_dirty = true;
14462        });
14463        item
14464    }
14465
14466    #[gpui::test]
14467    async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14468        cx: &mut gpui::TestAppContext,
14469    ) {
14470        init_test(cx);
14471        let fs = FakeFs::new(cx.executor());
14472
14473        let project = Project::test(fs, [], cx).await;
14474        let (workspace, cx) =
14475            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14476
14477        let panel = workspace.update_in(cx, |workspace, window, cx| {
14478            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14479            workspace.add_panel(panel.clone(), window, cx);
14480            workspace
14481                .right_dock()
14482                .update(cx, |dock, cx| dock.set_open(true, window, cx));
14483            panel
14484        });
14485
14486        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14487        pane.update_in(cx, |pane, window, cx| {
14488            let item = cx.new(TestItem::new);
14489            pane.add_item(Box::new(item), true, true, None, window, cx);
14490        });
14491
14492        // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14493        // mirrors the real-world flow and avoids side effects from directly
14494        // focusing the panel while the center pane is active.
14495        workspace.update_in(cx, |workspace, window, cx| {
14496            workspace.toggle_panel_focus::<TestPanel>(window, cx);
14497        });
14498
14499        panel.update_in(cx, |panel, window, cx| {
14500            panel.set_zoomed(true, window, cx);
14501        });
14502
14503        workspace.update_in(cx, |workspace, window, cx| {
14504            assert!(workspace.right_dock().read(cx).is_open());
14505            assert!(panel.is_zoomed(window, cx));
14506            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14507        });
14508
14509        // Simulate a spurious pane::Event::Focus on the center pane while the
14510        // panel still has focus. This mirrors what happens during macOS window
14511        // activation: the center pane fires a focus event even though actual
14512        // focus remains on the dock panel.
14513        pane.update_in(cx, |_, _, cx| {
14514            cx.emit(pane::Event::Focus);
14515        });
14516
14517        // The dock must remain open because the panel had focus at the time the
14518        // event was processed. Before the fix, dock_to_preserve was None for
14519        // panels that don't implement pane(), causing the dock to close.
14520        workspace.update_in(cx, |workspace, window, cx| {
14521            assert!(
14522                workspace.right_dock().read(cx).is_open(),
14523                "Dock should stay open when its zoomed panel (without pane()) still has focus"
14524            );
14525            assert!(panel.is_zoomed(window, cx));
14526        });
14527    }
14528
14529    #[gpui::test]
14530    async fn test_panels_stay_open_after_position_change_and_settings_update(
14531        cx: &mut gpui::TestAppContext,
14532    ) {
14533        init_test(cx);
14534        let fs = FakeFs::new(cx.executor());
14535        let project = Project::test(fs, [], cx).await;
14536        let (workspace, cx) =
14537            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14538
14539        // Add two panels to the left dock and open it.
14540        let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14541            let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14542            let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14543            workspace.add_panel(panel_a.clone(), window, cx);
14544            workspace.add_panel(panel_b.clone(), window, cx);
14545            workspace.left_dock().update(cx, |dock, cx| {
14546                dock.set_open(true, window, cx);
14547                dock.activate_panel(0, window, cx);
14548            });
14549            (panel_a, panel_b)
14550        });
14551
14552        workspace.update_in(cx, |workspace, _, cx| {
14553            assert!(workspace.left_dock().read(cx).is_open());
14554        });
14555
14556        // Simulate a feature flag changing default dock positions: both panels
14557        // move from Left to Right.
14558        workspace.update_in(cx, |_workspace, _window, cx| {
14559            panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14560            panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14561            cx.update_global::<SettingsStore, _>(|_, _| {});
14562        });
14563
14564        // Both panels should now be in the right dock.
14565        workspace.update_in(cx, |workspace, _, cx| {
14566            let right_dock = workspace.right_dock().read(cx);
14567            assert_eq!(right_dock.panels_len(), 2);
14568        });
14569
14570        // Open the right dock and activate panel_b (simulating the user
14571        // opening the panel after it moved).
14572        workspace.update_in(cx, |workspace, window, cx| {
14573            workspace.right_dock().update(cx, |dock, cx| {
14574                dock.set_open(true, window, cx);
14575                dock.activate_panel(1, window, cx);
14576            });
14577        });
14578
14579        // Now trigger another SettingsStore change
14580        workspace.update_in(cx, |_workspace, _window, cx| {
14581            cx.update_global::<SettingsStore, _>(|_, _| {});
14582        });
14583
14584        workspace.update_in(cx, |workspace, _, cx| {
14585            assert!(
14586                workspace.right_dock().read(cx).is_open(),
14587                "Right dock should still be open after a settings change"
14588            );
14589            assert_eq!(
14590                workspace.right_dock().read(cx).panels_len(),
14591                2,
14592                "Both panels should still be in the right dock"
14593            );
14594        });
14595    }
14596}